Loop Structures

1 The Importance of Repetition in Problem Solving

Repetition is an essential concept in programming because it allows us to solve problems efficiently by automating repetitive tasks. For example:

  • Printing numbers from 1 to 100 without manually writing each print statement.

  • Calculating the sum of all elements in a list of numbers.

  • Continuously asking a user for valid input until they enter a correct value.

By using loops, we can save time, reduce code duplication, and make our programs more flexible and dynamic.

2 The Concept of Loop Counters and Termination Conditions

Repetition in programming often requires two key elements:

  1. A loop counter: A variable that keeps track of the current iteration or state of the loop.

  2. A termination condition: A logical expression that determines when the loop should stop executing.

2.1 Loop Counters

A loop counter is essential for tasks that need a specific number of iterations. For instance, if you need to print numbers from 1 to 10, the loop counter increments in each iteration to track progress. The value of the counter can also be used within the loop to perform calculations or access specific data.

Vars i: integer Start For i 1 to 10 Do write (i) EndFor End

2.2 Termination Conditions

Termination conditions ensure that a loop eventually stops. Without a valid termination condition, a loop may run indefinitely, causing program errors. For example, a loop that adds numbers stops when there are no more numbers left to add.

Vars num, total: integer Start total 0 read (num) While num 0 Do total total + num read (num) EndWhile write (total) End

2.3 Infinite Loops: A Common Pitfall

If the termination condition is never met, the loop will run forever, which is called an infinite loop. This is usually a programming error but can be intentional in specific use cases, such as waiting for user input or monitoring a system state.

Vars input: character Start While true Do read (input) write ("You entered: ", input) EndWHile End

3 The While Loop

The While loop executes a block of code as long as a condition is true.

Vars num, total: integer Start total 0 read (num) While num 0 Do total total + num read (num) EndWhile write (total) End

4 The Repeat Loop

The Repeat loop executes a block of code at least once and stops when a condition is met.

Vars num: integer Start Repeat read (num) Until num > 0 End

5 The For Loop

The For loop is used when the number of iterations is known in advance.

Vars i: integer Start For i 1 to 10 Do write (i) EndFor End

6 Nested Loops

Loops can be nested to handle more complex problems, such as iterating over a grid or performing matrix operations.

Vars i, j: integer Start For i 1 to 10 Do For j 1 to 10 Do write (i * j) EndFor EndFor End

7 Repetitive Structures in C

In programming, loops allow us to execute a block of code repeatedly, either a fixed number of times or until a certain condition is met. This repetition is vital for tasks that require the same action to be performed multiple times, such as processing items in a list, computing iterative values, or continuously checking a condition.

7.1 Types of Loops

There are three primary types of loops used in most programming languages:

  1. For Loop: Repeats a block of code a specific number of times.

  2. While Loop: Repeats a block of code as long as a specified condition is true.

  3. Do-While Loop: Similar to the while loop but guarantees at least one execution of the block of code, as the condition is checked after the block is executed.

7.2 Why Use Loops?

Loops are essential when performing repetitive tasks such as:

  • Iterating over arrays or data structures.

  • Performing mathematical calculations that require multiple iterations (e.g., summing numbers or computing factorials).

  • Continuously checking conditions in scenarios such as user input validation or game loops.

Loops reduce redundancy in code, allowing us to avoid manually writing the same code multiple times, which would be inefficient and error-prone.

7.3 Examples in C

7.3.1 For Loop

    // For loop example
    #include <stdio.h>
    
    void main() 
    {
        // Print numbers from 1 to 5
        for (int i = 1; i <= 5; i++) 
        {
            printf("%d\n", i);
        }
    }

In this example, the for loop initializes i to 1, checks the condition i <= 5, and increments i after each iteration. The loop will print the numbers from 1 to 5.

7.3.2 While Loop

    // While loop example
    #include <stdio.h>
    
    void main() 
    {
        int count = 1;
        
        // Print numbers from 1 to 5
        while (count <= 5) 
        {
            printf("%d\n", count);
            count++;
        }
    }

The while loop checks the condition count <= 5. As long as the condition is true, the block of code inside the loop will execute. The count variable is incremented with each iteration, and the loop will stop once count exceeds 5.

7.3.3 Do-While Loop

    // Do-While loop example
    #include <stdio.h>
    
    void main() 
    {
        int count = 1;
        
        // Print numbers from 1 to 5
        do 
        {
            printf("%d\n", count);
            count++;
        } 
        while (count <= 5);
    }

In a do-while loop, the block of code is executed at least once, regardless of the condition. In this case, the loop behaves similarly to the while loop example, but the condition is checked after the block of code is executed.

7.4 Loop Control Statements

Sometimes we need to alter the flow of a loop:

  • Break: Exits the loop immediately.

  • Continue: Skips the rest of the current iteration and proceeds to the next iteration.

7.4.1 Break Example

    // Break statement example
    #include <stdio.h>
    
    void main() 
    {
        for (int i = 1; i <= 10; i++) 
        {
            if (i == 6) 
            {
                break; // Exit the loop when i is 6
            }
            printf("%d\n", i);
        }
    }

In this example, the loop will print the numbers from 1 to 5. When i becomes 6, the break statement is encountered, and the loop terminates.

7.4.2 Continue Example

    // Continue statement example
    #include <stdio.h>
    
    void main() 
    {
        for (int i = 1; i <= 5; i++) 
        {
            if (i == 3) 
            {
                continue; // Skip the current iteration when i is 3
            }
            printf("%d\n", i);
        }
    }

Here, the loop will print the numbers 1, 2, 4, and 5. When i equals 3, the continue statement skips the rest of the iteration and moves to the next value of i.

Last modified: Saturday, 23 November 2024, 4:23 PM