do-while Loop In C Programming Language

In this video tutorial lets learn about the general syntax and working of do-while loop in C programming language.

Related Read:
while loop in C programming
For Loop In C Programming Language
Using Scanf in C Program

Video Tutorial: do-while Loop In C Programming Language



YouTube Link: https://www.youtube.com/watch?v=iGZACvW1HhA [Watch the Video In Full Screen.]

Source Code: do-while Loop In C Programming Language

#include<stdio.h>

int main()
{
    int count = 1;

    do
    {
        printf("Apple\n");
        printf("IBM\n");

    }while(count > 5);

    return 0;
}

Output
Apple
IBM

Note: Even though the while condition is false, the code inside do block gets executed atleast once.

Source Code: do-while Loop In C Programming Language

#include<stdio.h>

int main()
{
    char ch;

    do
    {
        printf("Apple\n");
        printf("IBM\n");

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

        fflush(stdin);

    }while(ch == 'y');

    return 0;
}

Output
Apple
IBM
Do you want to continue?(y/n)y
Apple
IBM
Do you want to continue?(y/n)y
Apple
IBM
Do you want to continue?(y/n)y
Apple
IBM
Do you want to continue?(y/n)y
Apple
IBM
Do you want to continue?(y/n)n

Working of do-while Loop

Unlike in while and for loop, in do-while loop the statements inside do block gets executed atleast once. After executing the statements present in do block atleast once, the condition present in while is checked. If while condition is true, then the block of code in do{} gets executed once again. If condition in while is false then the control exists do-while loop.

Note: Since we might start to input information from the keyboard repeatedly inside do-while block, scanf() method keeps checking the input buffer. And often times it gets confused with the input buffer and thinks that the user has pressed the enter key. To avoid that we flush out the previous buffer present in input device(ex: keyboard) using function fflush(). fflush takes stdin as argument, so that it can clear the buffer of standard input device. fflush(stdin);

Source Code: Infinite Looping in do-while Loop – In C Programming Language

#include<stdio.h>

int main()
{
    do
    {
        printf("Apple\n");
        printf("IBM\n");

    }while(1);

    return 0;
}

Output
do-while loop gets into infinite loop as the condition in while is non-zero number, which means the condition is always true.

Apple
IBM

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

View Comments