For Loops
Main body structure for(declare an integer, declare conditions, declare iteration) for(int n = 0, n <= 10, n++) { // whatever code you want to execute on the for loop } In this for loop, n is initialized to 0, our condition is that n must be less than or equal to 0, n will go up by 1 every iteration of the loop
for(int n = 0; n <= 100; n++) for(int n = 10; n <= 100; n+5) for(int n = 100; n < 100; n++) for(int n = 0; n < 10; n+10) for(int n = 50; n > 100; n+30) for(int n = 0; n <= 10; n+3)
Some Rules regarding the loop for(int n = 0; n <= 100; n++) If integer n is declared outside of this loop, it will generate error. The scope of n is inside this loop meaning: { } n = 5 // this generates an error because the scope of n has finished
Is this ok? int n; for(n = 0; n <= 100; n++) { } What about this: int x = 100 for(int n = 0; n <= x; n++) Finally, what about this? int s = 0; for(int n = s; n <= 100; n++)
To Review for(integer initialization; condition; iteration) Give the loop its starting condition, if you want to start at 0, let this be equal to zero. Tell it the condition in which the loop terminates. Be careful not to hit an infinite loop Tell it how fast the loop will increment.
Exercise 1 Use a for loop to display hello world exactly 10 times Now do it 10 times but set your starting condition to n = 50;
Exercise 2 Ask a user for input of an integer greater than 100 Exercise 2 Ask a user for input of an integer greater than 100. Use a for loop to count down from the input number to 0. Subtract 5 from the number every time you loop. Display the value of the number every time you loop.
Exercise 3 Use a for loop to count down from 100 to 0. Output: 100 99 98 97 96
Challenge 1 Figure out how many numbers are divisible by 7 from 150 - 300 Challenge 2 Tell us how many factors of 100 can exist between 0-100. Challenge 3 Display the following pattern. 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 Challenge 4: Display the following pattern. 10 9 8 7 6 5 4 3 2 1 10 9 8 7 6 5 4 3 2 10 9 8 7 6 5 4 3 10 9 8 7 6 5 4 10 9 8 7 6 5 10 9 8 7 6 10 9 8 7 10 9 8 10 9 10