Download presentation
Presentation is loading. Please wait.
1
For Loops
2
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
3
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)
4
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
5
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++)
6
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.
7
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;
8
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.
9
Exercise 3 Use a for loop to count down from 100 to 0. Output:
10
Challenge 1 Figure out how many numbers are divisible by 7 from Challenge 2 Tell us how many factors of 100 can exist between Challenge 3 Display the following pattern. Challenge 4: Display the following pattern. 10 9 8 10 9 10
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.