The condition is evaluated after the body of the loop gets executed
The structure of the do…while loop is as follows:
do
{
//statements
} while (condition);
A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/* demonstrates a do…while statement */ #include <stdio.h> int num; main() { int num; char ans; do { printf("Enter a number: "); scanf("%d",&num); printf("want to enter another no y/n "); getchar(); scanf("%c" &ans); } while(ans == 'y') return 0; } |
The for Loop:
for ( initial; condition; increment )
{ statements; }
initiali, condition, and increment are all C expressions, and statement is a single or compound C statement.
Some valid for statements:
for (count = 100; count > 0; count–)
for (count = 0; count < 1000; count += 5)
count = 1;
for ( ; count < 1000; count++)
for (i = 0, j = 999; i < 1000; i++, j–)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* Program to calculate factorial of a number */ #include <stdio.h> int main() { int i=0; int fact=1; int number=0; printf("Enter number: "); scanf("%d",&number); for(i=2;i<=number;i++) { fact *= i; } printf("Factorial of %d is %d",number,fact); } |
1 2 3 4 5 6 7 8 9 10 11 12 |
/* Program to print a table of a number */ int main() { int i; int tableof; printf("Enter the number: "); scanf("%d",&tableof); for(i=1;i<=10;i++) { printf("%d * %d = %d\n",tableof,i,tableof*i); } } |
Mr. Sandeep Soni
Founder, Trainer & CEO, Deccansoft Software Services.
Sandeep has 21 yrs of experience working in various Microsoft Technologies/Platforms incl. VB6.0, ASP, VC++, VB.NET, C#. He is involved in managing and architecting projects at Deccansoft. He will be your liaison to Deccansoft, for any kind of communication and project updates. He knows what works and what doesn’t, and what practices are most suitable for design and programming with the ultimate goal of producing a quality system.