C Programming Do While Loop

C Programming Do While Loop

C Programming Do While Loop

C Programming Do While Loop

Table of Contents

A loop in a C program do…while is guaranteed to execute at least once. In this chapter you do…while will learn to create loops in C programs.

A loop is used to repeat a specific block of code until an end condition is reached. There are three types of loops in C programming:

                    1. For Loop

                    2. While Loop

                    3. Do While Loop

Syntax of do...while loop in C Programming

				
					do
{
 // This code will execute
}
while (testExpression);
				
			

do…while Loops and while loops are similar except for one important difference. do…while The loop code block is executed onnce before checking the test Expression. So do…while the loop executes at least once.

How do do...whille loops work in C programming?


Example 1: do...while loop

				
					// // C program to output integers 1 to 5


#include<stdio.h>
#include<conio.h>

int main()
{
 int i;
 clrscr();
 i=1;
 do
 {
 printf("\n%d",i);
 i++;
 }
 while(i<=5);
 getch();
}
				
			
c programming continue statement

output
				
					1
2
3
4
5
				
			


Example 2: do...while loop

				
					// Program to sum until user enters 0(zero).

#include <stdio.h>
int main()
{
 double number, sum = 0;

 //The body of the loop is executed at least once.
 do
 {
 printf("Enter a number: ");
 scanf("%lf", &number);
 sum += number;
 }
 while(number != 0.0);

 printf("Sum = %.2lf",sum);

 return 0;
}
				
			

output
				
					Enter a number: 3
Enter a number: 5.5
Enter a number: -5
Enter a number: 10
Enter a number: -3.5
Enter a number: 0
Sum = 10
				
			

When the value of test Expression is True and when it is False is discussed in the Relational and Logical Operators page.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *