Loop Constructs

(a) Define loop. Why are loops used? Explain the different types of loops available in C language.

A statement or a set of statements that is executed repeatedly is known as loop. Loops are basically used to execute a statement or number of statements for a specified number of times. For example, a user may display his name on screen for 10 times. Also to use a sequence of values. For example, a user may display a set of natural number from 1 to 10.

There are three main types of loops available in C language.
1. for loop
2. while loop
3. do-while loop

(b) Explain briefly the “while loop”. Also write its syntax.

while loop is the simplest loop of C language. This loop executes one or more statements while the given condition remains true. It is useful where the number of iterations is not known in advance. Syntax of while loop is as follows:
while (condition)
{
statement 1;
statement 2;
.
.
statement N;
}

(c) Explain briefly the “do-while” statement. Also write its syntax.

do-while is an iterative control in C language. This loop executes one or more statements while the given condition is true. In this loop, the condition comes after the body of loop. The loop is important in a situation where a statement must be executed at least once. The important point about do-while loop is that the condition ends with a semicolon. Syntax of do-while loop is as follows:
do
{
statement 1;
statement 2;
.
.
statement N;
}
while (condition);

(d) Write a note on “break statement” and “continue statement”.

Break statement
It terminates the execution of the nearest enclosing do, for, switch, or while loop in which it appears. When this statement is executed in the loop body, the control directly moves outside the body and statement that comes after the body is executed.

Continue Statement
It is used in the body of loop to move the control to the start of the loop body. When this statement is executed , the remaining statements of current iteration are not executed. The control directly moves to the next iteration.

(e) What is  “for loop” ? Explain its working. Also write its syntax.

for loop executes one or more statements for a specified number of times. This loop is also called counter-controlled loop. It is the most flexible loop. That is why the most programmers use this loop in programs.
Syntax of the for loop is as follows:
for (initialization; condition; increment/decrement)
{
statement 1;
statement 2;
.
.
statement N;
}

Working of for loop
After initialization, the given condition is evaluated. If it is true, the control enters the body of the loop and executes all statements in it. Then the increment/decrement part is executed. The control again moves to condition part. This process continues while the condition remains true. The loop is terminated when the condition becomes false.