Convert this While to a For

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Almost any while loops can be converted into a for loop and vice versa. In fact, a for loop is just a while loop that iterates for a set number of times.

Take a look at the following sample program. This program prints a list of numbers in descending order from 1000 to zero decreasing by two each time.

 public class WhileLoop
{
	public static void main(String[] args)
	{
		int i = 1000;
		
		while(i>=0)
		{
			System.out.println(i);
			i -= 2;
		}
	}	
} 

Change this program so that it uses a for loop instead of a while loop to increment i and to decide when to stop.

 

...By Students

"One of the first fundamental programming practices you will have learned is to declare your variables at the beginning of each class or method. This organizes things better and makes it easier for anyone reading your code, but it also serves at least one other purpose. If you declare and initialize your variable within a loop at the same time, the data that your variable holds won't be available outside the loop. By declaring your variable outside the loop, you allow the rest of your code to use that variable. Of course, sometimes you may not want to do this. If your variable is only used within the loop and nowhere else in your code, it is generally considered okay to declare your variable inside your loop. An example of this is declaring the counter variable in a for loop (eg. for (int i = 1; i < 10; i++))."

"I learned this lesson the hard way in one of my first programs that involved more than a few lines of code. After several hours of trying to decipher compiler errors and faulty output, I moved the declaration of the variable outside of the loop. All of a sudden, my code worked! It was one of many, many moments that time was spent trying to fix a simple error. Sometimes, the biggest problems are solved with the smallest solutions."

Solution

Remember that there are 3 arguments in a for loop statement. The form is for(initialization, condition, iteration) statement. In the example,

 int i = 1000; 

is the initialization,

 while(i>=0) 

is the condition, and

 i -= 2; 

is the iteration.

All of this can be combined into one for loop statement

 for(int i = 1000; i>=0; i -= 2) 


The complete working program is shown below.

Code

Solution Code

Back to the Program-A-Day homepage