C Programming Questions and Answers

Questions Index

Question: Explain with example different types of Loops in C language.

Answer:

Looping statements in C language are:
1. while loop
2. do-while loop
3. for loop

1. while loop

Syntax of while loop
while(condition)
{
    statement(s);
}

In the while loop a condition is first evaluated. If the condition is true, the loop body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly as long as the condition remains true. As soon as the condition becomes false, it comes out of the loop and goes to the statement next to the ‘while’ loop.

/* This program illustrates while loop. */

#include <stdio.h>

int main()
{
    int i = 1;

    while (i <= 10)
    {
        printf("%d ", i);
        i++;
    }
    return 0;
}

Output:
1 2 3 4 5 6 7 8 9 10

2) do-while loop

Syntax of do-while loop
do
{
    statements;
} while (condition);

In the do while loop, the loop repetition test is performed after each execution the loop body. Hence, the loop body is always executed least once.

/* This program illustrates do..while loop. */

#include <stdio.h>

int main()
{
    int number, sum = 0;
    char choice;

    do
    {
        printf("Enter a number :");
        scanf("%d", &number);

        sum += number;

        printf("Do you want to continue(y/n)? ");
        scanf("%c", &choice);

    }while (choice == 'y' || choice == 'Y');

    printf("\nSum of numbers :%d", sum);

    return 0;
}

Output:
Enter a number :12
Do you want to continue(y/n)? y
Enter a number :6
Do you want to continue(y/n)? y
Enter a number :19
Do you want to continue(y/n)? n

Sum of numbers :37

3) for loop

It is a count-controlled loop in the sense that the program knows in advance how many times the loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
    statement(s);
}

In for loop three operations take place:
i. Initialization of loop control variable
ii. Testing of loop control variable
iii. Update the loop control variable either by incrementing or decrementing.

Operation (i) is used to initialize the value. On the other hand, operation (ii) is used to test whether the condition is true or false. If the condition is true, the program executes the body of the loop and then the value of loop control variable is updated. Again, it checks the condition and so on. If the condition is false, it gets out of the loop.

/* This program illustrates the working of for loop */

#include <stdio.h>

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

Output:
1 2 3 4 5 6 7 8 9 10