Loops Statements in C
In programming, a loop is used to repeat a block of code until the specified condition is met.
Looping Statements in C execute the series of statements many times until the stated condition becomes false.The loop in C consists of two parts, the main part of the loop and the control statements. We may encounter situations when the block of code has to be executed a few times.
we may encounter situations, when a block of code needs to be executed some number of times. In general, statements are executed sequential manner: The first statement in a L is executed first, followed by the second, and so on.
Types of Loops in C
Looping statements in C are classified into two types: they depend on the position of the control statement in the program,
1. Entry controlled loop
2. Exit controlled loop
Entry controlled loop
In the entry control loop in C, the position of the main part of the loop is checked before execution. This is also called pre-checking loop. EX. while, for
Exit controlled loop
In an Exit controlled loops, a condition is checked after executing the body of a loop.Also called post-checking loop. EX. do while
Types of C Loops
There are three types of loops in C language :
do while
while
for
Advantage of loops in C
1) It provides code Reusability.
2) Using loops, we do not need to write the same code repeatedly.
3) Using loops, We can navigate through the elements of data structures (array or linked lists).
for Loop
A for loop is a repetitive control structure that allows us to write loops that are executed at specific times. The loop enables you to complete n steps in a row simultaneously.
Syntax:
for (initialization expr; test expr; update expr)
{
// body of the loop
// statements we want to execute
}
In for loop, a variable is used to control the loop is known as loop variable. First start this loop variable in some value, then check if this variable is less or greater than the counter value. If statement is true, then loop body is executed and loop variable value gets updated . Steps are repeated till exit condition comes.
- Initialization Expression: In this expression you have to initialize the loop counter to some value. for example: int i=1;
- Test expression: In this expression you have to test the condition. If the condition evaluation is true then we will execute the main part of the loop and go to the expression update otherwise we will exit the for loop. For example: i <= 10;
- Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: i++.\