B

05.Looping

Chapter 5: Looping Overview

  • Examines various types of loops in programming, particularly focusing on their structure and functionality.

Types of Loops

While Loops

  • Definition: A pre-test loop that checks a condition before each iteration.

  • Structure:

    • Consists of a boolean condition and a block of statements.

  • Example:

    while (boolean_expression) {
        // Statements executed if true
    }
  • Can execute zero times if the condition is false on the first check.

Do-While Loops

  • Definition: Similar to the while loop, but checks the condition after the block executes, guaranteeing at least one execution.

  • Structure:

    do {
        // Statements to execute
    } while (boolean_expression);

For Loops

  • Designed for a specific type of counting iteration.

  • Structure:

    for (initialization; condition; update) {
        // Statements executed each iteration
    }
  • Combines initialization, condition checking, and update statement in one line.

Looping Mechanics

Conditional Execution vs. Repeated Execution

  • Conditional Structures execute based on true/false (if, switch).

  • Repetition Structures execute multiple times based on user decision or condition.

Iteration

  • Definition: A single execution of the loop body.

  • Infinite loops occur when the loop does not exit, usually due to unchecked conditions.

Input Validation with While Loops

  • Validates user input within a loop until valid input is obtained.

  • Example:

    while (condition) {
        // Prompt and receive input
    }

Increment and Decrement Operators

  • Increment: ++ operator increases a variable's value by one.

  • Decrement: -- operator decreases a variable's value by one.

Nested Loops

  • Definition: Loops within loops; each complete iteration of the outer loop may run the entire inner loop.

  • Applications:

    • Processing multi-dimensional data, such as grids or tables.

    • Handling collections of items systematically.

Loop Control Keywords

Break and Continue

  • Break: Exits the current loop entirely.

  • Continue: Skips the current iteration and returns to condition checking.

File Handling

File Streams

  • Basic file handling relies on ifstream for input and ofstream for output.

File Opening

  • Files are opened using the .open() method.

    ifstream file(