The document provides an overview of looping in programming using C, detailing the use of while, do-while, and for loops to execute statements repeatedly. It explains the differences between pretest and posttest loops, along with syntax and examples for each loop type. The conclusion emphasizes the importance of loops for code efficiency and readability.
Topic Objective
Understandthe 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 ina 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 programprints 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 areused 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
while Loop
It isan 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
}
do…while Loop
It isan 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);
for Loop
for loophas 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.
CONCLUSION
Importance ofloops 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.