FOR Loops and WHILE Loops

 

Modules - CSE1120 Structured Programming 2

 

Teacher’s Notes:

========================================================================

This exercise is a pretty simple one that is meant to show students that FOR loops and WHILE loops can be used interchangeably but that their structures are different. 

I emphasize that in FOR loops, you sometimes want to create the variable outside of the loop so that it won't fall out of scope later.  

I also mention that (for me anyways) FOR loops are usually used when you know how many times you want to perform a loop whereas WHILE loops are used for situations where you are waiting for some condition to be true but aren't sure how many iterations it will be before that happens.  You may not agree so if you want to leave this out, then go ahead.

 

Assignment:

========================================================================

 

 

Rewrite each of the following code blocks using a FOR loop.  The output of the program should be EXACTLY the same.


Block 1:

int counter1 = 1;

while(counter1 <= 5)

    System.out.println("The count is:" +counter1++);

 

 

Block 2:

 

int counter2 = 1;

while(counter2 < 11) {

    System.out.println("The count is:" + counter2);

    counter2 *= 2;

}

System.out.println("Final Count: " +counter2);


Rewrite each of the following code blocks using a WHILE loop.  The output of the program should be EXACTLY the same.

 

Block 3:

 

for(int counter= 10; counter >= 0; counter -= 2) {

    System.out.println(counter);

}

 

 

Solution (JAVA):

========================================================================

 

Solution for Block 1:

 

for(int counter1 = 1; counter1 <= 5; counter1++)

    System.out.println("The count is:" +counter1);

 
 

Solution for Block 2:

 

int counter2 = 1;

for(counter2 = 1; counter2 < 11; counter2 *=2)

    System.out.println("The count is:" + counter2);

System.out.println("Final Count: " +counter2);

 

Solution for Block 3:

 

int counter = 10;

while(counter >= 0) {

    System.out.println(counter);

    counter -= 2;

}