Loop In C Programming Language
Introduction
In this post, we will learn about loops in c programming language. In C programming language, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.Remember in our very first we wrote a program to print "Hello, World". Now suppose we want to repeat this for 1000 times, means we want to print Hello, World 1000 in a program. It is not practically possible to repeat printf("Hello, World"); 1000 times and because here statement print "Hello, World" is repeatable we can use a loop.
Types of Loop in C programming language
There are three types of loop in C programming language.- For Loop
- While Loop
- Do While Loop
For Loop in C
These are the steps that we follow while using for loop in c- It first evaluates the initialization code.
- Then it checks the condition expression.
- If it is true, it executes the for-loop body.
- Then it evaluates the increment/decrement condition and again follows from step 2.
- When the condition expression becomes false, it exits the loop.
#include<stdio.h>
void main( )
{
int i;
for(x = 0; i < 1000; i++)
{
printf("Hello, World\n");
}
}
While loop in C
while loop can be addressed as an entry control loop. It is completed in 3 step- Variable initialization.(e.g int i = 0;)
- Condition(e.g while(i <= 10))
- Variable increment or decrement ( i++ or i-- or i = i + 2 )
Example: Print "Hello, World" 1000 times using While loop.
#include<stdio.h>
int main()
{
int i = 0;
while(i<1000) {
printf("Hello, World\n");
i = i + 1;
}
}
Do While loop in C
In some situations, it is necessary to execute the body of the loop before testing the condition. Such situations can be handled with the help of do-while loop.- Variable initialization
- Execute body
- check the condition
#include <stdio.h>
void main( )
{
int i = 0;
do {
printf("Hello, World\n");
x = i + 1;
}while(i<1000)
}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Comments
Post a Comment