Download presentation
Presentation is loading. Please wait.
1
For Loops October 12, 2017
2
For Loops A for loop repeats for a specified interval—until some condition is met. The syntax is as follows: for (initialization; condition; increment/decrement) { //statement }
3
For Loops for (initialization; condition; increment/decrement) { //statement } You can declare the variable inside this portion of the loop: both x = 0; and int x = 0; are valid. Unlike with a while loop, the variable must be numerical (typically an int).
4
For Loops for (initialization; condition; increment/decrement) { //statement } The loop repeats as long as this condition is true. The condition is checked at the beginning of each execution. Examples: x < 10; x >= 5;
5
For Loops for (initialization; condition; increment/decrement) { //statement } This is the same as the increment/decrement in a while loop: x++, x--, and their ilk. The increment/decrement takes place after the loop executes. Unlike with a while loop, don’t put this statement in the body of the loop!
6
For Loops Consider this sample for loop:
for (int x = 0; x < 5; x++) { cout << "Hello! “; } This code segment will output “Hello!” five times.
7
For Loops Consider this sample for loop:
for (int x = 0; x > 5; x++) { cout << "Hello! "; } How many times will this code segment output “Hello!”?
8
For Loops Consider this sample for loop:
for (int x = 0; x < 5; x++) { cout << "Hello! "; x++; } How many times will this code segment output “Hello!”?
9
For Loops Consider this sample for loop:
for (int x = 0; x <= 5; x++) { cout << x << " "; } What is the output of this code?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.