loops play a vital role in any programming language, they allow the programmer to write more readable and effective code. The looping concept also allows us to reduce the number of lines.
2. Topic Objective
Understand the basics of looping.
To use the looping statements such as while, do-while and
for statement to execute statements in a program repeatedly.
3. INTRODUCTION
Statements in a program are executed one after the other
ex: statement 1;
statement 2;
:
statement n;
Sometimes, the user want to execute a set of statements
repeatedly.
4. For Example, You want to print your name i.e. Rahul, 5 times
then here is a simple program to do the same.
#include<stdio.h>
#include<conio.h>
void main()
{
printf(“Rahul”);
printf(“Rahul”);
printf(“Rahul”);
printf(“Rahul”);
printf(“Rahul”);
getch();
}
5. The program prints your name five times but suppose is you
wants to print your name 100 times then we can certainly not
write printf() statement 100 times.
In this situation, we use loop concept to execute statements up
to a desire number of times.
C provides various forms of loops, which can be used to
execute one or more statements repeatedly.
6. Loop statements are used to repeat the execution of
statement or blocks.
Iteration of a loop: the number of times the body of loop is
executed.
Two types of loop structure are:
Pretest : Entry - controlled loop
Posttest : Exit – controlled loop
7. PRETEST VS. POSTTEST
Pretest : Condition is tested before each iteration to check
if loops should occur.
Posttest : Condition is tested after each iteration to check
if loop should continue (at least a single iteration occurs).
Statements
Conditio
n
Evaluate
true
false
Statements
true
Conditio
n
Evaluate
false
9. while Loop
It is an entry control loop, so condition is tested
before each iteration to decide whether to continue or
terminate the loop.
The body of a while loop will execute zero or more
times
Syntax: while( condition)
{
// statements
}
11. do…while Loop
It is an exit control loop, condition is
checked after one time execution of the body
of the loop.
The body of a d o - while loop will execute o n e or
more times.
Syntax: do{
<statement/block>;
}while(condition);
13. for Loop
for loop has three parts:
Initializer is executed at start of loop.
Loop condition is tested before iteration to decide
whether to continue or terminate the loop.
Increment/Decrement is executed at the end of each
loop iteration.
16. CONCLUSION
Importance of loops in any programming language is
immense, they allow us to reduce the number of lines in a
code, making our code more readable and efficient.