Loops

 

Introduction to Loops:

A loop in programming is a control structure that repeats a block of code until a specified condition is met. It allows you to execute a certain piece of code repeatedly, saving you from having to write the same code multiple times. Loops are fundamental in programming and are used in various scenarios to automate repetitive tasks or to iterate through collections of data.

Types of Loop

Loops are categorized into two parts based on their control machanism:

  • Entry-Controlled loops - In Entry controlled loops the test condition is checked before entering the main body of the loop. For Loop and While Loop is Entry-controlled loops.

  • Exit-Controlled loops - In Exit controlled loops the test condition is evaluated at the end of the loop body. The loop body will execute at least once, irrespective of whether the condition is true or false. Do-while Loop is an example of Exit Controlled loop.

Entry-Controlled loop

An entry-controlled loop, also known as a pre-test loop, is a type of loop where the condition is evaluated before the loop body is executed. If the condition is false initially, the loop body will not execute at all. This means that the loop may not execute even once if the condition is false from the start.

Common examples of entry-controlled loops include the while loop and the for loop in various programming languages.

Here’s an example of an entry-controlled loop using a while loop in C++:

#include <iostream>
using namespace std;

int main()
{

    // Entry-controlled for loop
    int i;
    for (i = 0; i < 5; i++) {
        cout << i << " ";
    }
    cout << endl;

    // Entry-controlled while loop
    i = 0;
    while (i < 5) {
        cout << i << " ";
        i++;
    }

    return 0;
}

Output :

0 1 2 3 4
0 1 2 3 4

Exit-Controlled loop

An exit-controlled loop, also known as a post-test loop, is a type of loop where the condition is evaluated after the loop body has been executed at least once. This means that the loop body will always execute at least once before the condition is checked.

The most common example of an exit-controlled loop is the do-while loop, although not all programming languages have built-in support for this type of loop. In languages like C/C++, the do-while loop is used for exit-controlled looping.

Here’s an example of an exit-controlled loop using a do-while loop in C++:

#include <iostream>
using namespace std;

int main()
{
    // Exit controlled do-while loop
    int i = 0;
    do {
        cout << i << " ";
        i++;
    } while (i < 5);
    return 0;
}

Output :

0 1 2 3 4 

For loop:

A for loop is a type of loop commonly used in programming to iterate over a sequence of values or to execute a block of code a predetermined number of times. It’s particularly useful when you know in advance how many times you want to repeat a certain task.

Here’s the basic syntax of a for loop in C++:

for (initialization; condition; iteration) {
    // Block of code to be executed
}

The basic syntax of a for loop varies slightly across programming languages, but the general structure remains similar. Here’s a typical example in C++:

#include <iostream>
using namespace std;

int main()
{
    for (int i = 0; i < 5; i++) {
        cout << i << " ";
    }
    cout << endl;
    return 0;
}

Output :

0 1 2 3 4

In this example:

  • The loop begins with the keyword for.
  • The loop variable i is initialized to 0.
  • The loop continues as long as i is less than 5 (i < 5).
  • After each iteration, i is incremented by 1 (i++).
  • Inside the loop, cout << i << " " prints the current value of i in same line.

    While loop:

    A while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Unlike the for loop, which is often used when the number of iterations is known in advance, the while loop is useful when you want to iterate based on a condition that might change during the execution of the loop.

Here’s the basic syntax of a while loop in C++:

while (condition) {
    // Block of code to be executed
}

Here’s an example of a while loop in C++:

#include <iostream>

int main() {
    int i = 0;
    while (i < 5) {
        std::cout << i << std::endl;
        i++;
    }
    return 0;
}

Output :

0
1
2
3
4

In this example, the loop continues to execute as long as i is less than 5, and i is incremented by 1 after each iteration.

Do-While loop

A do-while loop is a control flow statement in programming that executes a block of code repeatedly until a specified condition evaluates to false. Unlike a while loop, which checks the condition before the loop is executed, a do-while loop checks the condition after the loop has executed at least once. This guarantees that the block of code inside the loop will be executed at least once, regardless of whether the condition is initially true or false.

Do-While loop follows this syntax:

do {
    // Block of code to be executed
} while (condition);

Here’s a simple example to illustrate how a do-while loop works:

#include <iostream>

int main() {
    int i = 0;
    
    do {
        std::cout << "The value of i is: " << i << std::endl;
        i++;
    } while (i < 5);
    
    return 0;
}

Output :

The value of i is: 0
The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4

In this example, the loop will execute at least once because the condition i < 5 is evaluated after the first execution of the loop. The loop will continue to execute until i is no longer less than 5.

Once i becomes equal to 5, the condition i < 5 becomes false, and the loop terminates.

Nested Loops

Nested loops refer to placing one loop inside another loop. This is a common programming construct used to iterate over elements in a multi-dimensional array or to perform repetitive tasks in a structured manner. Here’s an example in C++:

#include <iostream>

int main() {
    // Outer loop
    for (int i = 1; i <= 3; ++i) {
        // Inner loop
        for (int j = 1; j <= 3; ++j) {
            std::cout << "i: " << i << ", j: " << j << std::endl;
        }
    }
    
    return 0;
}

In this example, we have an outer loop that iterates over the values of i from 1 to 3, and within this outer loop, there’s an inner loop that iterates over the values of j from 1 to 3. This results in a total of 9 iterations, as the inner loop runs completely for each iteration of the outer loop.

The output of this code will be:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3

Each combination of i and j is printed out, demonstrating the behavior of nested loops.

For loop vs While loop vs Do-While loop in Programming

Charateristics for loop while loop do-while loop
Syntax for (initialization; condition; update) while (condition) do { } while (condition);
Condition Check Checked before each iteration. Checked before entering the loop. Checked after executing the loop body.
Update/Increment Executed after each iteration. Should be included within the loop body. Executed after each iteration.
Use Cases Suitable when the number of iterations is known. Useful when the loop condition is based on a state that can change anywhere in the loop body. Ensures the loop body is executed at least once before checking the condition.

Practice Questions: