What are looping in C language
If I tell you that you have to print a “this is my program” 10 times then how will you do this? Generally speaking: You can write 10 printf () statements to do this.
This is a useless approach. That’s why You have provided loops in C language. With the help of loops, you can execute the same statement repeatedly. Each type of loop provides a block in which statements are written which you want to execute more than once.
Loops Depends upon 3 major factors
- Initial variable
- Condition
- Increment/decrement
Syntax in FOR Loop
For
(variable ; condition; increment/decrement)
{
Statement 1
Statement 2
}
Let’s understand the For Loop by taking an example
#include<stdio.h>
#include<conio.h>
Void main()
{
Int num=10;
for (num=1 ; num<=10; num++)
printf("this is my program");
getch();
}
Output :
This is my program
This is my program
This is my program
This is my program
This is my program
This is my program
This is my program
This is my program
This is my program
This is my program
When user/programmers want to enter repedative statements here Loops are used
Types of Loop
- For
- While
- Do-while
we will implement above example on all three Loops
While
#include<stdio.h>
#include<conio.h>
void main()
{
Int num=10;
While (num<=10)
printf("this is my program");
num++;
getch();
}
Do While
#include<stdio.h>
#include<conio.h>
void main()
{
Int num=10;
Do{
printf("this is my program");
num++;
}
While(num<=10);
getch();
}
So in all three cases the output will be Same
No comments:
Post a Comment