Computer Applications

Consider the following program segment and answer the questions given:

for(int k=1;k<=5;k++) 
System.out.println(k); 
System.out.println(k);

(a) Will the program segment get executed successfully?
(b) If not, state the type of error?
(c) How do you correct the program if it has any error?

Java Iterative Stmts

2 Likes

Answer

(a) No, the program segment will not execute successfully.

(b) The error is a syntax error because the variable k is not known outside the loop. The variable k is created inside the for loop and only exists there. When the program tries to use k after the loop, it does not recognize it, so the program gives an error.

(c) To fix the error, declare k before the loop:

int k;
for (k = 1; k <= 5; k++)
System.out.println(k);
System.out.println(k);

Answered By

2 Likes


Related Questions