C Tutorials
- What is C?
- History Of C?
- Feature of C?
- How to Install C?
- How to write c program?
- First c program
- Flow of C program
- printf() and scanf() in C
- C Program Structure
- Variables in C
- Data Types in C
- Keywords in C
- C Operators
- Comments in C
- Escape Sequence in C
- Escape Sequence in C
- Constants in C
- C - Storage Classes
- C - Decision Making
- Switch statement in C
- C Loops
- Loop Control Statements
- Type Casting in C
- functions in C
- call by value Or call by reference
- Recursion in C
- Storage Classes in C
- Array
- String
- Pointer
- Pointer And Array
- Pointer with function
- Structure
- Union
- File Handling
- Preprocessor Directives
Important Links
C Loops
loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
A loop statement allows us to execute a statement or group of statements multiple times.
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed, and execution breaks out of the loop.
Why use loops in C language? :-
Types of C Loops :-
while loop :-
It is completed in 3 steps.
Syntax :
variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
Output :-
do while loop :-
Syntax :-
do
{
.....
.....
}
while(condition)
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
Output :-
for loop :-
for(initialization; condition; increment/decrement)
{
statement-block;
}
Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.
In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. But it can have only one condition.
void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}
Output :-
Nested for loop :-
for(initialization; condition; increment/decrement)
{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
output :-
21
321
4321
54321