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 the do-while loop

The statements within the loop would keep getting executed until the condition being tested remains true. When the condition becomes false, the control is transferred to the 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();
}

Share

Leave a Reply

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