while statement in C programming - Ocean of Programming

Sunday 31 December 2017

while statement in C programming

        In the previous article, we have seen if, if....else Statement in C programming if you did not read the previous article you read it before proceeding further.
       Loops are used to execute some block of statements repeatedly. It executes until termination condition gets executed. Types of loop statement are
1. if statement
2. while statement
3. do-while statement

while statement

           In while statement first the expression is tested. If true then program enters into the while loop and executes statements of while and after execution of all statements again condition is tested. If the condition is true then while loop again executed and it continues until the condition becomes false. If the condition becomes false the loop terminates and control comes out of while loop.

The syntax for while statement:

while(expression)
{

            statement 1;

            statement 2;

            statement 3;
} 
 Flowchart of while statement

Program 1

#include<stdio.h>
int main()
{
        int i=0;
        while(i<20)         
 {
     printf("%d ",i);
       i = i+2;
   }
     printf("\n");
}
The output for above program is

 Program 2: To find factorial of a given number

#include<stdio.h>
int main()
{
     int n,num;
     long long fact;
     printf("Enter a number\n");
     scanf("%d",&num);
     n=num;
     fact=1;
     if(num&gt0)
         printf("Factorial of negative number is not possible\n");
     else
     {
         while(num>1)
         {
              fact = fact * num;  //fact*=n;
              num--;
         }
         printf("The factorial of a number %d is %lld\n",n,fact);
     }
}
The output for above program is
              Note that we must need to mention expression otherwise it will give error as
        Please feel free to comment if you find anything incorrect or you want to share more information about the topic discussed above.

No comments:

Post a Comment