Page Content

Tutorials

A Complete Guide For C Iteration Statements With Examples

C Iteration Statements

Basic programming structures known as looping statements enable a set of instructions to be carried out again. This repetition can continue until a condition is met or a set number of times. While, do-while, and for are C main loop statements.

Primary methods to control iteration:

  • Counter-Controlled Iteration: The quantity of iterations is known beforehand. This determines when the loop should end by initialising, incrementing (or decrementing), and testing a control variable (also known as a loop counter) against a condition.
  • Sentinel-Controlled Iteration: It is unknown in advance how many times it will be done. The loop keeps going until a particular value known as the sentinel value is reached, signifying the termination condition or the end of the data.

Another way to categorise loops is by the time the condition is checked:

  • Entry-Controlled Loops: Before the body of the loop is run, the condition is tested. If the condition is originally false, the loop body might not run at all. In C, the for and while loops are entry-controlled.
  • Exit-Controlled Loops: Following the execution of the loop body, the condition is tested. This ensures that, regardless of the beginning situation, the loop body gets run at least once. An exit-controlled loop is the do-while loop in C.

Let’s take a closer look at the while, do-while, and for loops:

The while Loop

A set of statements is repeated using the while loop as long as a predetermined condition is met. Because it is an entry-controlled loop, the condition is verified prior to the body of the loop being run. The body of the loop is completely skipped if the condition is originally false.

A while loop’s general syntax is:

initialization_statement(s); // Usually before the loop 
while (condition) {
    // Loop body - statements to be repeated 
    // Update statement(s); // Necessary to eventually make the condition false 
}

The body of the loop is made up of the statements included in { }. For a single statement, braces are not required, however they are recommended for clarity. As long as the condition evaluates to true (non-zero), the loop keeps running.

Both counter-controlled and sentinel-controlled iteration are possible with the while loop.

Here is an example in C that prints numbers 1 through 5 using a while loop and counter-controlled iteration:

#include <stdio.h>
int main(void) {
    int counter = 1; // initialization 
    while (counter <= 5) { // condition 
        printf("%i\n", counter); // loop body 
        ++counter; // update 
    }
    return 0;
}

The counter is initialised to 1 by this software. It checks the while condition counter <= 5. The body of the loop runs because it is true, printing the counter and then increasing it. The loop ends when the condition counter <= 5 is false, which happens when the counter reaches 6.

The do-while Loop

As an exit-controlled loop, the do-while loop’s body is run at least once prior to testing the loop-continuation condition. As long as the condition evaluates to true after each iteration, the loop will keep repeating.

General do-while loop syntax:

initialization_statement(s); // Usually before the loop 
do {
    // Loop body - statements to be repeated 
    // Update statement(s); // Typically inside the loop body
} while (condition); // Condition tested after body; semicolon is required 

Do-while loops are appropriate when a user is prompted for input and the loop repeats until valid input is entered.

This C code prints “Hello World!” ten times using the do-while loop:

#include <stdio.h>
int main() {
    int i = 1; // Initialization 
    do {
        printf("\n Hello World!"); // Loop body 
        ++i; // Updating expression 
    } while (i <= 10); // Conditional expression 
    printf("\n Thank you");
    return 0;
}

I is initialised to 1 in this example. When the do block is run, “Hello World!” is printed and i is increased to 2. Next, the condition i <= 10 is examined. The cycle continues because it is true. This keeps going until i gets to 11, which makes the condition i <= 10 false. At that point, the loop ends and the printf instruction is executed. The while clause is followed by a semicolon.

The for Loop

The for loop is an entry-controlled loop that is mainly utilised for counter-controlled iteration. It makes counting loops more readable and concise by combining the initialisation, condition, and iteration (update) portions of a loop into a single line.

A for loop’s general syntax is:

for (initialization_expression; condition_expression; loop_expression) {
    // Loop body - statement(s) to be repeated 
}

Semicolons are used to separate the three expressions enclosed in parenthesis:

  • initialization_expression: carried out once at the start of the loop. The loop counter is frequently declared and initialised. The scope of the variables stated here is the for statement.
  • condition_expression: assessed before to every iteration. As long as this condition (non-zero) remains true, the loop keeps going. The body is not executed if it is initially false.
  • loop_expression: carried out following the loop body at the conclusion of each iteration. The loop counter is usually updated with it.

A while statement with the structure initialization_expression; while (condition_expression) { loop_statement; loop_expression; } is the same as the for statement.

Here’s an example in C that prints even numbers from 1 to a user-specified number using a for loop:

#include <stdio.h>
int main() {
    int num, i;
    printf("Enter Number:");
    scanf("%d", &num);
    for(i=1; i<=num; i++) // initialization; condition; increment 
    {
        if(i%2==0) // Loop body with conditional check
            printf("\t%d", i);
    }
    return 0;
}

Extra Features of the for Loop

Optional Expressions: It is possible to leave out any or all of the three phrases in the for heading. An infinite loop results from the condition expression defaulting to true if it is left out. If the variable is set before the loop, you can skip initialisation; if the update occurs inside the body, you can skip the loop expression.

Multiple Expressions: Commas (,) can be used to separate loop expressions and multiple initialisation expressions. Although it can combine many conditions using logical operators, only one condition expression is permitted.

  • An example using loop expressions and several initialisations:

Null Statement Body: If all operations are carried out inside the expressions in the for header, the loop body may be a null statement (;). For instance:

Scope of Variable: A for loop’s initialisation expression contains variables that are scoped to the loop statement and are not accessible from outside of it.

Loops (while, do-while, and for) can have their typical flow of execution changed by using the break and continue commands. While continue skips the remainder of the current iteration and moves on to the next, break triggers an instantaneous escape from the innermost loop. Although the goto statement permits leaping as well, structured control statements are typically preferred for its use.

You can also read Understanding C Pseudocode With Code Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index