c > constructs > iterative constructs > iterative constructs

Iterative Constructs

When we are solving a problem, we may want to repeat a section (block) of our code. This is achieved through the use of iterative constructs. In C, we have three (3) common iterative constructs:

Iterative constructs can be bounded (e.g. for loops) or unbounded (while and do-while loops).

For loops

The for loop is a bounded loop. This is because we can tell how many times it will be executed before termination. We can know the number of iterations from how we construct the for loop.


#include <stdio.h>

int main(void)
{
    int i;
    for(i=0;i<10;i++){
        printf("The value of i is %d\n",i);
    }
    return 0;
}

↗ Open 📋 Copy c/constructs/iterative_constructs/for_loops.c

Challenge

While loops

The while loop is a type of unbounded iteration. This is because its execution is not terminated when a certain number of iterations are finished but rather when a condition is met. This means that a while loop and run 10 or 1000 or an infinite number of times based on if the condition is met.

The while loop checks the condition before executing the block of code. This means that it is possible for the contents of a while loop to never be executed.


#include <stdio.h>

int main()
{
    int i = 0;
    while(i<=5){
        printf("The value of i is %d\n",i);
        i = i+1; // OR i+=1 OR i++
    }

    int pin;
    while(1){
        printf("Please enter your pin:\n");
        scanf("%d",&pin);
        if (pin==1234){
            printf("Correct pin!! You get a cookie...");
            break;
        }else{
            printf("Wrong pin bro...\n");
        }
    }
    return 0;
}

↗ Open 📋 Copy c/constructs/iterative_constructs/while_loops.c

Challenge

Do-while loops

A do-while loop will always run at least once because the condition is checked at the end of each iteration.


#include <stdio.h>

int main(){
    int i = 0;

    do{
        printf("%d\n",i);
        i++;
    }while(i<10);
    
    int ret,number;
    do{
        printf("Please enter a valid number:\n");
        ret = scanf("%d",&number);

    }while(ret==0);
    printf("Ghee thanks!!");
}

↗ Open 📋 Copy c/constructs/iterative_constructs/do_while_loops.c

Challenge

The lesson on loops continues here