Operators in C programming Language
This article is a overview of the various loops in C programming.
What are Loops ?
Loops are used when a set or a block of code needs to be executed several number of times. In any programming language, in a set of codes, the code is executed in a sequence i.e. first line of statement is executed first and followed by each line of statement.
But, when we need to execute a line or a block of code for several times until a certain condition is satisfied, that is where looping takes its role.
When and where is a loop used?
When we perform a operation, some condition is checked such as whether the condition has reached the prescribed number. **Condition not reached: **If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeat it.
Condition reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop.
Depending upon the requirement C programming supports the following loops:
for loop
Executes a sequence of statements to a specified number of times. Syntax:
for (initialization Statement; condition; update Statement)
{
//statements inside the body of loop
}
while loop
While loop tests the condition before executing the loop body. It repeats a statement or group of statements until a given condition is true.
Syntax:
while (condition)
{
//statements inside the body of the loop
}
do...while loop
Unlike while loop, it test the condition at the end of the loop. syntax:
do
{
statements inside the body of the loop
}
while (condition);
nested loops
You can use one or more loops inside any other while, for, or do..while loop.
Loop Control Statements
Loop control statements changes the execution of a loop from its normal sequence. C supports the following control statements.
break statement
Terminates the loop or switch statement and executes the statement following the loop or switch.
continue statement
Causes the loop to skip the current iteration and continue with the next iteration.
goto statement
When a goto statement is applied, the control of the program jumps to the labelled statement.
Note:
- Use ‘for loop’ when the number of iterations is known i.e. the number of times the loop body is needed to be executed is known.
- Use while loops when the number of iterations is unknown but the loop termination condition is known.
- Use do while loop if the code needs to be executed at least once.