5 ForLoop

5 ForLoop - for loops for Do exactly the same thing as...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: for loops for Do exactly the same thing as while loops Use when you know the exact number of times you want to count Parts of the loop Initialize (counter) Condition (boolean test) Update (iteration expression) 1 for loop 1 Start with this 2 Test this if false Exit for (int i = 0; i < 10; i++){ for (int i = 0; i < 10; i++){ 3 Run the code 4 Do this 5 Return to #2 #4 & #5 are “invisible } 2 A while loop A int count = 1; while(count < 4) { println("count is " + count); println("count count++; count++; } 3 A while loop A int count = 1; while(count < 4) { println("count is " + count); println("count count++; count++; } /* Output is count is 1 count is 2 count is 3 */ 4 A while and a for loop that do the A exactly the same thing int count = 1; while(count < 4) { println("count is " + println("count count++; count++; } Is the same as for(int count = 1;count { println("count is " + println("count } count); < 4;count++) count); 5 Notice both have the same 3 parts Notice both have the same 3 parts int count = 1; while(count < 4) { println("count is " + println("count count++; count++ } Is the same as for(int count = 1;count { println("count is " + println("count } count); < 4;count++) count); 6 Why both? Why both? Some programmers prefer the for loop since it uses fewer lines of code Most beginning programmers find the while loop easier to understand Good Style: Use for loops only when you know in advance how many times you want the loop to run. In all other circumstances use a while loop. 7 Practice Quiz Question Practice Quiz Question Write a program that uses two for loops to produce the following output xxxxxx 10 9 8 7 6 5 4 3 2 1 8 ...
View Full Document

Ask a homework question - tutors are online