Friday, 10 April 2015

Looping Statements in C

           A loop involves repeating some portion of the program either a specified number of times or until a condition is satisfied. This repetitive operation (loop) is achieved in C through a for, or while or do-while loop.



               The statements within the loop would keep getting executed till the condition being tested remains true. When the condition becomes false, the control is transferred to first statement that follows the body of the loop.
For loop:
Syntax:
for(initialization; testing; increment/decrement)
{
          //sequence of statements;
}
Example:
for(i=1;i<=5;i++)
{
          printf“\n%d”,i);
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
          clrscr();
int i,factorial=1,n;
printf(“\nEnter the Number to find the factorial”);
scanf(“%d”,&n); //getting the input
for(i=1;i<=n;i++)
{
factorial=factorial*i;
}
printf(“\nThe factorial of %d is %d ”,n,factorial); //Displaying the output
getch();
}
Aim of this program is to find the factorial of the given number.
Program Explanation:
Include header files
Using scanf get the input to find the factorial.
Using for loop find the factorial of the given number.
Display the ouput.
While loop:
Syntax:
while(test_expression)
{
//sequence of statements;
}
Example:
while(i<5>
{
printf(“%d”,i);
i++;
}
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
         
clrscr();
int i=1,factorial=1,n;
printf(“\nEnter the Number to find the factorial”);
scanf(“%d”,&n); //getting the input
while(i<=n)
{
factorial=factorial*i;
i++;
}
printf(“\nThe factorial of %d is %d ”,n,factorial); //Displaying the output
getch();
}


About the Author

Unknown

Author & Editor

Hi Friends, I am Kayalvizhi doing Computer science engineering in Madurai. My hobbies are browsing, reading books and playing puzzles. I love programming. Read more

No comments:

Post a Comment

 
KayalSpot © 2015 - Designed by Templateism.com