Jun 25, 2014

C Programming #22: Loop - while

This article discusses the while loop.

Syntax of while loop:

while(condition) {
   statement; // body of the loop
}


Code flow for while loop:
First, condition is evaluated, if condition is true then statement is evaluated. Loop will exit only when condition is false. It does not have all the 4 parts discussed in this article.

While you could make it contain all 4 parts by doing as below.

initialize_counter;
while(condition) {
   statement; // body of the loop
   change_condition;
}

Program that checks number for prime
Prime number is a number which is evenly divisible by 1 or itself only(More details)
Strategy:  If the number is n, and it is divisible by any number(x) between 2 and n/2 then it is not prime otherwise it is prime.


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

   while(((n % x) != 0) && (x < n/2)) {
      x++;
   }
   if((n % x) == 0) {
      printf("%d Not prime, because it is divisible by %d \n", n, x);
   }else {
      printf("%d is prime\n", n);
   }
}

Output of above program is as follows


7913 Not prime, because it is divisible by 41 

Explanation
Condition in while loop (((n % x) != 0) && (x < n/2)) is making sure n is not divisible by x and x is always smaller than n/2. Body of loop only contains increment, which makes sure x has all the value between 2 to n/2. Loop will exit if n is divisible x or x become greater than n/2. In the end if statement distinguishes above two condition, to determine whether it is prime or not.

Links

Quiz - Not Yet written !!
Next Article - C Programming #23: Loop - do while
Previous Article - C Programming #21: Loop - for
All Articles - C Programming

No comments :

Post a Comment