Computer Applications
Analyze the following program segment and determine how many times the loop will be executed. What will be the output of the program segment?
int k=1,i=2;
while(++i<6)
k*=i;
System.out.println(k);
Answer
60
The loop executes 3 times.
Working
This table shows the change in values of i and k as while loop iterates:
| i | k | Remarks |
|---|---|---|
| 2 | 1 | Initial values |
| 3 | 3 | 1st Iteration |
| 4 | 12 | 2nd Iteration |
| 5 | 60 | 3rd Iteration |
| 6 | 60 | Once i becomes 6, condition is false and loop stops iterating. |
Notice that System.out.println(k); is not inside while loop. As there are no curly braces so only the statement k *= i; is inside the loop. The statement System.out.println(k); is outside the while loop, it is executed once and prints value of k which is 60 to the console.
Related Questions
Analyze the following program segment and determine how many times the body of the loop will be executed (show the working).
x = 5; y = 50; while(x<=y) { y = y / x; System.out.println(y); }What will be the output of the following code?
int m=2; int n=15; for(int i=1;i<5;i++) m++; --n; System.out.println("m="+m); System.out.println("n="+n);Give the output of the following program segment and also mention the number of times the loop is executed.
int a,b; for(a=6;b=4; a <= 4; a=a+ 6) { if(a%b==0) break; } System.out.println(a);Give the output of the following program segment and also mention how many times the loop is executed.
int i; for(i = 5; i > 10; i++) System.out.println(i); System.out.println(i * 4);