Presentation is loading. Please wait.

Presentation is loading. Please wait.

Loops October 10, 2017.

Similar presentations


Presentation on theme: "Loops October 10, 2017."— Presentation transcript:

1 Loops October 10, 2017

2 Loops A portion of a program that repeats a statement or group of statements is called a loop. Each repetition of the statement or group of statements (called the body of the loop) is called an iteration. Know this for the AP! Three loops you will frequently see are: For loops While loops Do-while loops

3 While Loops A while loop repeats as long as (while) a certain Boolean expression is true: while (x > 0) { //statement } If the expression in parentheses is never true, the body of the loop will never execute.

4 While Loops Consider the following code:
int x = 0; while (x < 10) { cout << "Hello! "; } How many times will this loop output "Hello!"?

5 While Loops A loop that never ends (like on the previous slide) is called an infinite loop. If the Boolean condition involves a number, be sure to increase or decrease (increment/decrement) the number every time the loop executes! Handy shortcuts: x++; is the same as x = x + 1; x--; is the same as x = x - 1;

6 While Loops Consider the following code:
int x = 0; while (x < 10) { cout << "Hello! "; x++; } How many times will this loop output "Hello!"?

7 Do-While Loops A do-while loop is similar to a while loop, but the Boolean condition is checked after the loop executes—so it will always execute at least once. The syntax is as follows: do { //statement } while(condition);

8 Do-While Loops Consider the following code: char ans; do {
cout << "Hello!\n"; cout << "Would you like another greeting? (Y/N)\n"; cin >> ans; } while(ans == 'y' || ans == 'Y');


Download ppt "Loops October 10, 2017."

Similar presentations


Ads by Google