C Programming

Loop (Iteration)

Loop or iteration or repetition is a programming construct that allows a set of instructions to be executed multiple times until a specific condition is met.

Loops are used to perform repetitive tasks without having to write the same code multiple times. They are fundamental in programming and are used in various applications, such as processing data, automating tasks, and creating interactive programs.

When To Use Loops

  1. Repetitive Tasks: When you need to perform the same action multiple times, such as processing items in a list or performing calculations on a set of data.
  2. Indeterminate Iterations: When the number of iterations is not known beforehand and depends on a condition being met, such as reading user input until a valid response is received.
  3. Automating Tasks: When you want to automate tasks that would otherwise require manual repetition, such as generating reports or performing batch operations.
  4. Searching and Sorting: When you need to search for specific items in a dataset or sort data in a particular order.

Things To Know About Loops

  1. Loop Control Variables: Loops often use control variables to determine how many times the loop should execute. These variables are typically initialized before the loop starts and updated within the loop. The control variable must be updated within the loop to ensure it eventually meets the termination condition.
  2. Loop Conditions: The condition that controls the loop must eventually become false to prevent infinite loops. It's important to ensure that the loop's logic allows for this.
  3. True from start: Except for do-while loops, which execute at least once before checking the condition. Other loops' condition must be true from start before the loop can execute.
  4. Nested Loops: Loops can be nested inside other loops, allowing for more complex iterations, such as iterating through multi-dimensional arrays.

Except processes (web servers) that runs without stopping which are placed in an infinite loop, it is important to always ensure that loops have a proper termination condition.

Apart from servers, many computing processes such as embedded systems and microcontrollers, Graphical User Interfaces (GUIs), operating system tasks, device drivers and monitoring tools, event-driven applications,etc. are intentionally designed to run in an infinite loop—often called an event loop or main loop — to ensure they continuously monitor, respond, or function until the system is turned off or terminated.

Infinite loops can cause a program to hang or consume excessive system resources.

Types of Loops

There are three main types of loops in C and other programming languages:

  1. For Loop: Used when the number of iterations is known beforehand.
  2. While Loop: Used when the number of iterations is not known, and the loop continues as long as a condition is true.
  3. Do-While Loop: Similar to a while loop, but it executes at least once before checking the condition.

For Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a for loop in C is as follows:

for (initialization; condition; update) {
    // code to be executed
}

In a for loop, the initialization step is executed only once at the beginning of the loop. The condition is evaluated before each iteration, and if it evaluates to true, the code block inside the loop is executed. After each iteration, the update step is executed, which typically modifies the control variable.

The update is done either by increasing (++) or decreasing (--) the control variable.

For instance if the control variable is i, the increment will be i++ and the decrement will be i--.

In most programming languages like C, you must declare and initialize the control variable before the loop.

For instance if we want to start the loop from 1 to 10, we can initialize the control variable as int i = 1;.

When ascending (from least to highest), the control variable is increased.

When descending (from highest to least), the control variable is decreased.

You have to use appropriate comparator operators (e.g., <, >, <=, >=) in the condition to make the condition true from start and end at a point.

For instance, if we want the loop to iterate from 1 to 10, we can use any of the following conditions if we have initialized a control variable i to 1:

  1. i < 11
  2. i <= 10

The first condition reads as i is less than 11. The loop will continue as long as i is less than 11.

i increases after each iteration.

Note: most programmers use i as the control variable because of the word iteration but you can use any variable name of your choice.

Iteration Number Calculation Value of i Loop Status
1 i = 1 1 True, loop continues (since 1 < 11)
2 i = 1 + 1 2 True, loop continues (since 2 < 11)
3 i = 2 + 1 3 True, loop continues (since 3 < 11)
4 i = 3 + 1 4 True, loop continues (since 4 < 11)
5 i = 4 + 1 5 True, loop continues (since 5 < 11)
6 i = 5 + 1 6 True, loop continues (since 6 < 11)
7 i = 6 + 1 7 True, loop continues (since 7 < 11)
8 i = 7 + 1 8 True, loop continues (since 8 < 11)
9 i = 8 + 1 9 True, loop continues (since 9 < 11)
10 i = 9 + 1 10 True, loop continues (since 10 < 11)
11 i = 10 + 1 11 False, loop terminates (since 11 is not less than 11)

The second condition reads as i is less than or equal to 10. The loop will continue as long as i is less than or equal to 10.

i increases after each iteration.

Iteration Number Calculation Value of i Loop Status
1 i = 1 1 True, loop continues (since 1 < 10)
2 i = 1 + 1 2 True, loop continues (since 2 < 10)
3 i = 2 + 1 3 True, loop continues (since 3 < 10)
4 i = 3 + 1 4 True, loop continues (since 4 < 10)
5 i = 4 + 1 5 True, loop continues (since 5 < 10)
6 i = 5 + 1 6 True, loop continues (since 6 < 10)
7 i = 6 + 1 7 True, loop continues (since 7 < 10)
8 i = 7 + 1 8 True, loop continues (since 8 < 10)
9 i = 8 + 1 9 True, loop continues (since 9 < 10)
10 i = 9 + 1 10 True, loop continues (since 10 <= 10)
11 i = 10 + 1 11 False, loop terminates (since 11 is not less than or equal to 10)

For example, the following for loop prints the numbers from 1 to 10 as explained:

for (int i = 1; i <= 10; i++) {
    printf("%d ", i);
}

Since there is no newline character in the printf statement, all the numbers will be printed on the same line.

If we wish each number to be printed on a new line, we can add a newline character (\n) to the printf statement:

for (int i = 1; i <= 10; i++) {
    printf("%d\n", i);
}

To loop in a descending order, we can display the numbers from 10 to 1:

If we initialize our control variable i to 10 and the loop is supposed to continue while i is greater than 0, our condition will be i > 0:

How The Descending Order Loop Works

i = 10

Iteration Number Calculation Value of i Loop Status
1 i = 10 10 True, loop continues (since 10 > 0)
2 i = 10 - 1 9 True, loop continues (since 9 > 0)
3 i = 9 - 1 8 True, loop continues (since 8 > 0)
4 i = 8 - 1 7 True, loop continues (since 7 > 0)
5 i = 7 - 1 6 True, loop continues (since 6 > 0)
6 i = 6 - 1 5 True, loop continues (since 5 > 0)
7 i = 5 - 1 4 True, loop continues (since 4 > 0)
8 i = 4 - 1 3 True, loop continues (since 3 > 0)
9 i = 3 - 1 2 True, loop continues (since 2 > 0)
10 i = 2 - 1 1 True, loop continues (since 1 > 0)
11 i = 1 - 1 0 False, loop terminates (since 0 is not greater than 0)

For example, the following for loop prints the numbers from 10 to 1 as explained:

for (int i = 10; i > 0; i--) {
    printf("%d ", i);
}

For fun sake, let's print "*" characters 5 times:

  1. Horizontally
  2. Vertically

Since our task is to display 5 starts (*), we can intialize our control variable to 1 and the loop is supposed to start at 5, hence our condition will either be i <= 5 or i < 6.

Horizontally

Since our task is to display horizontally, we won't use the newline character:

for (int i = 1; i <= 5; i++) {
    printf("*");
}

Aternatively,

for (int i = 1; i < 6; i++) {
    printf("*");
}

Alternatively,

for (int i = 0; i < 5; i++) {
    printf("*");
}

Vertically

Since our task is to display vertically, we will use the newline character:

for (int i = 1; i <= 5; i++) {
    printf("*\n");
}

Aternatively,

for (int i = 1; i < 6; i++) {
    printf("*\n");
}

Alternatively,

for (int i = 0; i < 5; i++) {
    printf("*\n");
}

Occasions To Use The For Loop

  1. When the number of iterations is known: For loops are ideal when you know in advance how many times you want to execute a block of code. For example, if you want to print the numbers from 1 to 10, a for loop is a good choice.
  2. When iterating over arrays or collections: For loops are commonly used to iterate over arrays or collections of data. They allow you to access each element in the array and perform operations on it.
  3. When you need a concise syntax: For loops provide a compact syntax that combines initialization, condition checking, and updating in a single line. This can make your code more readable and easier to understand.

While Loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The syntax of a while loop in C is as follows:

while (condition) {
    // code to be executed
    // update control variable
}

In a while loop, the condition is evaluated before each iteration. If the condition evaluates to true, the code block inside the loop is executed. The loop continues until the condition becomes false.

For example, the following while loop prints the numbers from 1 to 5:

int i = 1;
while (i <= 5) {
    printf("%d ", i);
    i++;
}

The control variable is i and its value is updated within the loop to ensure the loop terminates when the condition becomes false.

Note: if there is no update to the control variable within the loop, it may result in an infinite loop and the program may hang, freeze or crash.

When To Use The While Loop

  1. When the number of iterations is not known: While loops are ideal when you don't know in advance how many times you want to execute a block of code. For example, if you want to read user input until a valid response is received, a while loop is a good choice.
  2. When you need to repeat a block of code based on a condition: While loops allow you to repeat a block of code as long as a certain condition is true. This can be useful for tasks such as validating user input or performing calculations until a specific result is achieved.
  3. When you want to create an infinite loop: While loops can be used to create infinite loops by using a condition that always evaluates to true. This can be useful for certain applications, such as server processes or event listeners, where you want the program to run indefinitely until it is manually stopped.

To intentionally create an infinite loop, you can use a condition that always evaluates to true, such as while (1).

For example, the following while loop creates an infinite loop:

while (1) {
    // code to be executed
}

The code below runs an infinite loop:

#include <stdio.h>
int main() {
    int i = 1;
    while(1){
        printf("%d\n",i);
        i++;
    }

    return 0;
}

You can also use while(true) but unless you include #include <stdbool.h>

The code will look like this:

#include <stdio.h>
#include <stdbool.h>

int main() {
    int i = 1;
    while(true){
        printf("%d\n",i);
        i++;
    }

    return 0;
}

You should only use an infinite loop when it is intentional and you have specific need for it.

In this example, the while loop will continue to execute indefinitely, printing the value of i and incrementing it by 1 on each iteration. The loop will only stop if the program is manually terminated.

Do-While Loop

A do-while loop is a control flow statement that allows code to be executed at least once and then repeatedly based on a given boolean condition. The syntax of a do-while loop in C is as follows:

do {
    // code to be executed
    // update control variable
} while (condition);

In a do-while loop, the code block inside the loop is executed first, and then the condition is evaluated. If the condition evaluates to true, the loop continues; otherwise, it terminates.

Since the condition is checked after the first iteration, the code block is guaranteed to execute at least once.

For example, the following do-while loop prints the numbers from 1 to 5:

int i = 1;
do {
    printf("%d ", i);
    i++;
} while (i <= 5);

When To Use The Do-While Loop

  1. When you want to ensure the code block is executed at least once: Do-while loops are useful when you need to execute a block of code at least once, regardless of whether the condition is true or false.
  2. When the condition depends on the result of the code block: Do-while loops are suitable when the condition for continuing the loop depends on the outcome of the code block executed in the previous iteration.

It is mostly used to repeatedly ask a user for input until a valid response is received.

Let's modify our previous grading system that we built earlier to use a do-while loop to repeated ask the user to enter a score until a user enters a score between 0 to 100.

Our previous code was:

#include <stdio.h>
int main() {
    int score;
    printf("Enter your score: ");
    scanf("%d", &score);

    if (score >= 75) {
        printf("Your grade is 1.\n");
    } else if (score >= 70) {
        printf("Your grade is 2.\n");
    } else if (score >= 65) {
        printf("Your grade is 3.\n");
    } else if (score >= 60) {
        printf("Your grade is 4.\n");
    } else if (score >= 55) {
        printf("Your grade is 5.\n");
    } else if (score >= 50) {
        printf("Your grade is 6.\n");
    } else if (score >= 45) {
        printf("Your grade is 7.\n");
    } else if (score >= 40) {
        printf("Your grade is 8.\n");
    } else {
        printf("Your grade is 9.\n");
    }

    return 0;
}

We will put the taking of the value from the user in a loop to continually ask the user to enter until a valid response is given.

Caption of the part to modify is below:

do{
        printf("Enter your score (0 - 100): ");
        scanf("%d", &score);
    }while((score < 0)||(score > 100));

The do-while loop first asks the user to enter the score. If a user enters the correct range of score, the condition in the do-while loop will be false and the loop ends but if not, the loop will be repeated until user enters the correct input.

Our updated code will be:

#include <stdio.h>
int main() {
    int score;
    do{
        printf("Enter your score (0 - 100): ");
        scanf("%d", &score);
    }while((score < 0)||(score > 100));

    if (score >= 75) {
        printf("Your grade is 1.\n");
    } else if (score >= 70) {
        printf("Your grade is 2.\n");
    } else if (score >= 65) {
        printf("Your grade is 3.\n");
    } else if (score >= 60) {
        printf("Your grade is 4.\n");
    } else if (score >= 55) {
        printf("Your grade is 5.\n");
    } else if (score >= 50) {
        printf("Your grade is 6.\n");
    } else if (score >= 45) {
        printf("Your grade is 7.\n");
    } else if (score >= 40) {
        printf("Your grade is 8.\n");
    } else {
        printf("Your grade is 9.\n");
    }

    return 0;
}

We can also use a loop to make our program run multiple times until a user enters a particular number or character to exit the program.

We will modify the grading program above and place it in a while loop. We will ask a user to enter 0 to exit the program and any other number to continue.

We first have to initialize our control variable to a number which is not 0.

#include <stdio.h>
int main() {
    int score;
    int exit = 1;
    while(exit !=0){
        do{
            printf("Enter your score (0 - 100): ");
            scanf("%d", &score);
        }while((score < 0)||(score > 100));

        if (score >= 75) {
            printf("Your grade is 1.\n");
        } else if (score >= 70) {
            printf("Your grade is 2.\n");
        } else if (score >= 65) {
            printf("Your grade is 3.\n");
        } else if (score >= 60) {
            printf("Your grade is 4.\n");
        } else if (score >= 55) {
            printf("Your grade is 5.\n");
        } else if (score >= 50) {
            printf("Your grade is 6.\n");
        } else if (score >= 45) {
            printf("Your grade is 7.\n");
        } else if (score >= 40) {
            printf("Your grade is 8.\n");
        } else {
            printf("Your grade is 9.\n");
        }
        /* Alert user to enter 0 to exit or other number to continue and get the value from the user */
        printf("Enter 0 to exit or any other number to continue: ");
        scanf("%d",&exit);
    }

    return 0;
}