For Loops October 12, 2017
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 }
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).
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;
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!
For Loops Consider this sample for loop: for (int x = 0; x < 5; x++) { cout << "Hello! “; } This code segment will output “Hello!” five times.
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!”?
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!”?
For Loops Consider this sample for loop: for (int x = 0; x <= 5; x++) { cout << x << " "; } What is the output of this code?