6. Chapter 5 Loops and Files - compscisi/Programming-Fundamentals-1-SI GitHub Wiki

Some facts about break statements:

  1. Used to terminate execution of a loop
  2. Only terminates the loop its in
  3. Used to terminate case in switch statements
  4. The syntax of a break statement: break;
  5. A break statement is used for when a condition is false
  6. 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
      1. If true, then statement is executed, and expression is evaluated again
      2. If false, then the loop is finished and program statements following statement execute
  • Logic of a while loop:

    WhileLogic

  • 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
    1. perform initialization
    2. evaluate test expression
      • If true, execute statement
      • If false, terminate loop execution
    3. execute update, then re-evaluate test expression
  • The For loop is a pre-test loop