Loop Control Structures in C

Loop Control Structures in C

Sometimes we may come across a case where we need to perform a task multiple times. In that case we may repeat code several times or write that code inside a loop.
Consider you have to repeat a code for hundred times, so it is feasible to write it in loop rather than repeating the code.
In C there are three looping methods for, while, do-while which can be used to loop certain part of our program.

[1] for loop
for loop consists of three parts – Initialization, Test Condition and Increment or decrement statement. 
Initialization occurs only once, at the start of loop.
Test condition is checked for every iteration, if it is true then the statement or block of statements will be executed.
Increment or decrement is done after the execution of the block of statement. It is important as it will take us to the final condition and terminate the loop.
Syntax

//for single statement
for ( initialization; test condition; increment/decrement )
statement;//for multiple statement


for ( initialization; test condition; increment/decrement )
{
block of statement
}

//C code to illustrate do-while loop
#include <stdio.h>
int main()
{
    int a = 10;
    do
    {
        printf("value of a: %d\n", a);
        a--;
    } while (a > 0);
    return 0;
}
$ gcc for.c
$ ./a.out
Number from 1 to 10:
1
2
3
4
5
6
7
8
9
10$

[2] while loop
The statements within the while loop will keep on executing until the condition remains true.

Syntax

initialize loop counter;
while (test loopcounter using a condition)
{
//statements to execute in loop
increment/decrement loopcounter;
}
#include <stdio.h>
int main()
{
    int a = 10;
    while (a > 0)
    {
        printf("value of a: %d\n", a);
        a--;
    }
    return 0;
}
 $ gcc while.c
$ ./a.out
10
9
8
7
6
5
4
3
2
1

[3] do-while loop
The while and for loop tests the condition at the top. But do-while test the condition after the body is executed once. If the test condition is true it will keep on executing.

Syntax

do
{
statements;
}while (expression);
//C code to illustrate do-while loop
#include <stdio.h>
int main()
{
    int a = 10;
    do
    {
        printf("value of a: %d\n", a);
        a--;
    } while (a > 0);
    return 0;
}
 $ gcc do.c
$ ./a.out
10
9
8
7
6
5
4
3
2
1

If you like the post Loop Control Structures in C, please share the feedback!

also see

C Programming language
Go Programming language
Linked List Array
Simplification Queue
DBMS Reasoning
Aptitude HTML
Previous articleConditional Flow Control Structures in C
Next articleHTML Styles

LEAVE A REPLY

Please enter your comment!
Please enter your name here