In this article do while loop in c we give the information about do while it may be necessary to execute the main part of the loop before testing it. Such situations can be controlled with the help of Do…while statement.
do while loop loop in C:
Do…While Statement:
The while loop construct, which we discussed in the previous article, tests the condition before the loop is executed. Therefore, if the conditions are not met on the first attempt, the main part of the loop cannot be executed at all. In some cases it may be necessary to execute the main part of the loop before testing it. Such situations can be controlled with the help of Do…while statement.
do while flowchart:
Do….While Syntax:
do
{
Body of the loop
}
while (test-condition);
Upon reaching the do statement, the program proceeds to evaluate the main part of the first loop. At the end of the loop, the test-position is evaluated in the while statement. If the condition is true, the program continues to evaluate the main part of the loop once again. This process continues as long as the situation is true. When the condition is false, the loop will end and control will be moved to the statement that appears immediately after the statement.
Since the test-position at the bottom of the loop is being evaluated, the do construction provides an exit-controlled loop and therefore the main part of the loop is always executed at least once.
// Program to add numbers until user enters zero
#include <stdio.h>
#include<conio.h>
void main()
{
int number, sum = 0;
// loop body is executed at least once
do
{
printf(“Enter a number: “);
scanf(“%d”, &number);
sum = sum + number;
}
while(number != 0);
printf(“Sum = %d”,sum);
getch();
}
OutPut:
Enter a number: 5
2
6
3
0
Sum = 16
// Program to show first ten natural numbers.
#include <stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
do
{
printf(“\n %d”,i);
i++;
}while(i<=10);
getch();
}
O/P:-
1
2
3
4
5
6
7
8
9
10
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining