C Language Tutorials by Ghulam Murtaza Dahar - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

Output

Enter a number.

5

Factorial=120

do...while loop

In C, do...while loop is very similar to while loop. Only difference between these two loops is that, in while loops, test expression is checked at first but, in do...while loop code is executed at first then the condition is checked. So, the code are executed at least once in do...while loops.

Syntax of do...while loops

do {

some code/s;

}

while (test expression);

At first codes inside body of do is executed. Then, the test expression is checked. If it is true, code/s inside body of do are executed again and the process continues until test expression becomes false(zero).

Notice, there is semicolon in the end of while (); in do...while loop.

Example of do...while loop

Write a C program to add all the numbers entered by a user until user enters 0.

/*C program to demonstrate the working of do...while statement*/

#include <stdio.h>

int main(){

int sum=0,num;

do /* Codes inside the body of do...while loops are at least executed

once. */

{

printf("Enter a number\n");

scanf("%d",&num);

sum+=num;

}

while(num!=0);

printf("sum=%d",sum);

return 0;

}