Do while loop in C Programming

Do while loop in C

  • This loop is useful to execute a group of statements repeatedly as long as a condition is true. Once the condition becomes false, the loop terminates.
Syntax: do{
        statements;
        }while(condition);
  • First, the compiler executes all the statements and then tests the condition. If the condition is true, then it goes back and executes the statements the second time.
  • If the condition is true, again it goes back and executes the statements. In this way, the statements are executed repeatedly as long as the condition is true. Once the condition becomes false, the loop terminates.

 

Example: int digit=0;
        do
        printf("%d\t",digit+=2);
       while(digit<10);
  • In the above example since only one statement is there inside the loop, we need not enclose it in curly braces. In the printf() statement digit+=2 represents that we are adding 2 to digit value and storing it again in the digit. It means digit=digit+2.
  • Now, the digit value becomes 2. In the condition digit<10, it means as long as digit value is less than 10, the loop is repeated. So, it will display even numbers up to 10 as 2,4,6,8,10.

Program to find the sum of digits of a number.

#include<stdio.h>
void main()
{
  int num,digit,sum=0;
  printf("\n Enter the number:");
  scanf("%d",&num);
  do{
  digit=num%10;
  sum+=digit;
  num/=10;
}while(num>0);
 pritnf("\nThe sum of digits=%d",sum);
}

Output:

Enter a number: 1048
The sum of digits: 13
naveed08st
 

Click Here to Leave a Comment Below 0 comments

Leave a Reply:

Select Language
Copy link
Powered by Social Snap