Looping Statements in C Programming

            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. Looping conditions are tested either at the entry level or at the exit level. Entry level checking loops are for loop and while loop. Exit level checking loop is 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. We will see only entry level condition checking loops in this article

For loop:
Syntax:
for(initialization; condition checking; increment/decrement)
{
          //sequence of statements;
}
Example:
for(i=1;i<=5;i++)
{
          printf(“\n%d”,i);
}
Example Program:
#include<stdio.h>
#include<conio.h>
void main()
{
          clrscr();
int i,factorial=1,num;
printf(“\nEnter the Number to find the factorial”);
scanf(“%d”,&num); //getting the input
for(i=1;i<=num;i++)
{
factorial=factorial*i;
}
printf(“\nThe factorial of %d is %d ”,num,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 output.
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();
}

Kayalvizhi Ganesan

Web developer, Blogger, You-tuber and a learner. I am always open up for learning new things and sharing it with people. This Blog is to share the things which I have learnt. My goal is to help TYRO to become a PRO

Leave a Reply

Your email address will not be published. Required fields are marked *