Loop Statement in C
Loop statement is used to execute one or more statement repeatedly multiple times. There are three types of loops in C language. Why use loop? We can use loop because it executes a block of code multiple times and it reduces the length of the code. Example: Let suppose we have to print counting 1to 50 then we have to use 50 times lines of code but if we use loop then print it by 2 or 5 lines of code.
- for loop
- while loop
- do while loop
The following syntax of for Loop:
for(initialization;condition;incr/decr) { //code to be executed }Example1
#include<stdio.h> int main(){ int i; for(i=0;i<=5;i++){ printf("%d \n", i); } return 0; }Output
0 1 2 3 4 5Example 2 //To print any childish table of any number
#include<stdio.h> #include<stdlib.h> int main(){ int n,temp,i; printf("Enter any number for Table :"); scanf("%d",&n); for(i=1;i<=10;i++){ temp=n*i; printf("%d * %d = %d \n",n,i,temp); } return 0; }Output
Enter any number for Table :32764 * 1 = 32764 32764 * 2 = 65528 32764 * 3 = 98292 32764 * 4 = 131056 32764 * 5 = 163820 32764 * 6 = 196584 32764 * 7 = 229348 32764 * 8 = 262112 32764 * 9 = 294876 32764 * 10 = 327640While Loop
While loop is an entry-controlled loop statement. The basic format of the while statement is:
Syntax:
while( test condition{ body of loop; }Or
Assignment; while(condition) { Statements; ...... Increment/decrements (++ or --); }
Note: While loop is used when the number is uncertain or unknown.
Example:
#include<stdio.h> int main(){ printf("To Print Counting by using While Loop \n"); int i=1; while(i<5){ printf("\n%d",i); i++; } return 0; }Output
To Print Counting by using While Loop 1 2 3 4Do while Loop
Do while loop is used to execute the program. In do while loop, the first part of the execution is body then evaluate the text condition. If the condition is true, the body of the loop is executed again and again until the condition becomes false.
Syntax:
do{ Statement(s); }while(condition);Let us consider the flow chart of the C program
Let us consider an example: