Name________________________________Date________ Pd_______________
Loop Practice Java
1. How many times will the following loop run?
int i = 0;
while (i < 10)
{
System.out.println(i);
i++;
}
2. What is the output of the code snippet given below?
int i = 0;
while (i != 9)
{
System.out.print(i + " ");
i = i + 2;
}
3. What is the output of the code fragment given below?
int i = 0;
int j = 0;
while (i < 27)
{
i = i + 2;
j++;
}
System.out.println("j=" + j);
4. What is the output of the following code snippet?
int i = 1;
while (i < 10)
{
System.out.print(i + " ");
i = i + 2;
if (i == 5)
{
i = 9;
}
}
5. What are the values of i and j after the following code fragment runs?
int i = 60;
int j = 50;
int count = 0;
while (count < 5)
{
i = i + i;
i = i + 1;
j = j - 1;
j = j - j;
count++;
}
System.out.println("i=" + i + ", j=" + j);
6. What is the output of the following code fragment?
int i = 1;
int sum = 0;
while (i <= 11)
{
sum = sum + i;
i++;
}
System.out.println("The value of sum is " + sum);
7. What are the values of i and j after the following code snippet is run?
int i = 10;
int j = 20;
int count = 0;
while (count < 5)
{
i = 2*i;
i = i + 1;
j = j - 1;
count++;
}
System.out.println("i = " + i + ", j = " + j);
8. What is the output of the following code snippet?
double r = 1;
double b = 2;
int i = 16;
while (i > 0)
{
if (i % 2 == 0) // i is even
{
b = b * b;
i = i / 2;
}
else
{
r = r * b;
i = i - 1;
}
}
System.out.println("r = " + r);
9. What for loop can be used in the indicated area so the code will print:
****
***
**
*
for (int val = 0; val < 4; val ++)
{
for( ; ; ) // fill in this loop header
{
System.out.print("*");
}
System.out.println();
}
10.The following loop does not work as intended. What error exists?
for (int i = 0; i < 10; i++);
{
System.out.println("Loop Execution");
}
11.What is the output of the following code snippet?
int f1 = 0;
int f2 = 1;
int fRes;
System.out.print(f1 + " ");
System.out.print(f2 + " ");
for (int i = 1; i < 10; i++)
{
fRes = f1 + f2;
System.out.print(fRes + " ");
f1 = f2;
f2 = fRes;
}
System.out.println();
12.What does the following code snippet print?
int n1 = 120;
int n2 = 90;
int result = 1;
for (int k = 1; k <= n1 && k <= n2; k++)
{
if (n1 % k == 0 && n2 % k == 0)
{
result = k;
}
}
System.out.println(result);
ANSWERS: 1) 10 2) 0 2 4 6 8 10 12 14 ….. infinite loop 3) j=14 4) 1 3 9 5) i = 1951, j = 0
6) The value of sum is 66 7) i = 351, j = 15 8) r = 65536.0 9) for(int num=0; num<4-val; num++)
10) semi-colon after for loop 11) 0 1 1 2 3 5 8 13 21 34 55 12) 30