For Loop While Loop Do while Loop
Loops help us to execute specific number of statements a specified number of times. “C” language provides 2 types of loops.
(i). Entry control loops (for loop and while loop)
(ii). Exit control loops (do while loop)
These statements are also known as iteration or looping statements.
Entry control loops
Entry control loops are the loops in which the condition is checked first and then the control enters the loop.
In “C” language we have two entry control loops.
(i) for loop
(ii) while loop
For loop
for loop is an entry control loop. In for loop we are required to pass three arguments.
Syntax:
(i).
for(A;B;C)
single Statement;
(ii).
for(A;B;C)
{
Statements;
Statements;
Statements;
}
A : initialization
B : Test condition
C : Increment / decrement
Syntax:
for(initialization ;test condition ;increment/decrement)
{
Statements;
Statements;
Statements;
}
Note: all the arguments passed in for loops are optional.
For loop can take following forms
1. for(a;b;c)
2. for(;b;c)
3. for(a;;c)
4. for(a;b;)
5. for(a;;)
6. for(;b;)
7. for(;;c)
8. for(;;)
For loop examples:
Example:1
C program to print numbers from 1 to 10
Sol:
#include <stdio.h> int main() { int i; for(i=1;i<=10;i++) { printf("%d\n",i); } return 0; }
Output:
1 2 3 4 5 6 7 8 9 10
Example:2
Write a C program to print numbers from 1 to 10 in reverse order
Sol:
#include<stdio.h> int main() { int i; for(i=10;i>=1;i--) { printf("%d\n",i); } return 0; }
Output:
10 9 8 7 6 5 4 3 2 1
Example:3
Write a C program to print all even numbers from upto 20
Sol:
#include <stdio.h> int main() { int i; for(i=2;i<=20;i=i+2) { printf("%d\n",i); } return 0; }
Output:
2 4 6 8 10 12 14 16 18 20
Example:4
Write a C program to print all even numbers from upto 20 in reverse order
Sol:
#include <stdio.h> int main() { int i; for(i=20;i>=2;i=i-2) { printf("%d\n",i); } return 0; }
Output:
20 18 16 14 12 10 8 6 4 2
Example:5
Write a C program to print all odd numbers from upto 25
Sol:
#include <stdio.h> int main() { int i; for(i=1;i<=25;i=i+2) { printf("%d\n",i); } return 0; }
Output:
25 23 21 19 17 15 13 11 9 7 5 3 1