Jun 25, 2014

C Programming #23: Loop - do while

This article discusses do while loop.

syntax of the do while:

do {
   // statement;
}while(condition);


It does the post check of the condition (when compared to while loop). First the statement is executed, then condition is evaluated, if condition is true loop continues, otherwise loop exits. do while makes sure that statement is executed at least once.

We can make it use all 4 parts of loop as discussed in article as follows

initialize_counter;
do {
   // statement;
   change_condition;
}while(condition);


Flow chart for "do while" loop is as follows.

Note that it is different when compared other loops.

Program that finds factorial of a number
You can find definition and details about factorial in this link.
Strategy:
If n is a number, factorial of n is defined as
n! = n * (n - 1) * (n - 2) ..... 2 * 1


#include <stdio.h>
int main() 
{
   int n = 8;
   int fact;
   int x;

   fact = 1;
   x = n;

   do {
      fact = fact * x;
      x--;
   }while(x >=1);

   printf("Factorial of %d is %d \n", n, fact);

   return 0;
}

Output of above program is


Factorial of 8 is 40320


Explanation
There are two new variable introduced fact and x. fact will hold factorial of a number while x will assume all the value between n to 1, which will help in factorial calculation.


Links

Quiz - Not Yet written !!
Next Article - C Programming #24: Loop - break
Previous Article - C Programming #22: Loop - while
All Articles - C Programming

No comments :

Post a Comment