Name: _________________
Block: _____
While Loop Worksheet
Directions for 1-5: In the following program segments do:
a) Show the memory simulation for the variable count. Make sure to show the last value of count
b) Write the output
1. count output
int count = 0;
while (count < 3)
{
count++;
System.out.print(count + " ");
}
2.
count output
int count = 0;
while (count < 3)
{
System.out.print(count + " ");
count++;
3.
int count = 0;
count output
while (count <= 3)
{
System.out.print(count + " ");
count++;
4.
int count = 0; count output
while (count <= 10 && count % 5 == 0)
{
System.out.print(count + " ");
count++;
5.
int count = 0;
boolean done = false; count output
while (count <= 10 && !done)
{
System.out.println(count);
if(count == 8)
done = true;
count++;
}
System.out.print(count);
6. How many times does the following loop execute?
int count = 0;
int number = 2;
boolean done = false;
while (! done)
{
number = number * 2;
if (number > 64)
done = true;
count++; // This is the iteration counter!
}
7. What is the output of the following code?
int i = 1;
int j = 1;
while(i < 5)
{
i++
j = j*2;
}
System.out.println(j);
8. Does the following code terminate? Show why/why not by tracing the code
int balance = 10;
while(true)
{
if (balance < 9)
break;
balance = balance – 9;
}
9. Write a while loop that will print out “A” to the screen 100 times. Make sure to only print 5 “A”s on each
line.
10. Provide an example of a while loop that never loops.