6. Chapter 5 Loops and Files - compscisi/Programming-Fundamentals-1-SI GitHub Wiki
break
statements:
Some facts about - Used to terminate execution of a loop
- Only terminates the loop its in
- Used to terminate case in switch statements
- The syntax of a break statement:
break;
- A break statement is used for when a condition is false
- If left out of a switch statement it will “fall through”
Increment and Decrement Operators
- Increment sign:
++
; increments the value by one - Decrement sign:
--
; decrements the value bye one
Prefix vs Postfix - examples
int num, val = 12;
cout << val++; // displays 12, val is now 13;
cout << ++val; // sets val to 14, then displays it
num = --val; // sets val to 13, stores 13 in num
num = val--; // stores 13 in num, sets val to 12
The while Loop
Loop: a control structure that cause a statement or statements to repeat General format of the while loop:
while (expression)
statement; //can also be a block of statements enclosed in { }
-
How it works:
- Expression is evaluated
- If true, then statement is executed, and expression is evaluated again
- If false, then the loop is finished and program statements following statement execute
- Expression is evaluated
-
Logic of a while loop:
-
The while loop is a pretest loop
-
Expression is evaluated before the loop executes. The following loop will never execute:
int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}
- Watch out for infinite loops
- The loop must contain code to make expression become false
- Otherwise, the loop will have no way of stopping
- Such a loop is called an infinite loop, because it will repeat an infinite number of times.
- Example:
int number = 1; while (number <= 5) { cout << "Hello\n"; }
The do-while loop
Do-while: a post test loop - execute the loop, then test the expression General format:
do
statement; // or block in { }
while (expression);
Semicolon is required after (expression)
- Loop always executes at least once
- Execution continues as long as expression is true, stops repetition when expression becomes false
The for Loop
Useful for counter-controlled loop General Format:
for(initialization; test; update)
statement; // or block in { }
No semicolon after the update expression or after the )
- For loop - mechanics
- perform initialization
- evaluate test expression
- If true, execute statement
- If false, terminate loop execution
- execute update, then re-evaluate test expression
- The For loop is a pre-test loop