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.
Size: 204.05 KB
Language: en
Added: Apr 09, 2020
Slides: 17 pages
Slide Content
Prepared By Dr. Chandan Kumar
Topic Objective Understand the basics of looping. To use the looping statements such as whi le , do-while and for statement to execute statements in a program repeatedly.
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 .
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 (); } INTRODUCTION
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. INTRODUCTION
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
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
TYPES OF LOOP while loop do-while loop for loop
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 }
Example : int i=0; while(i<3){ printf ( “ Hello \n ”) ; i++; } Output: Hello Hello Hello Flow diagram
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 do- while loop will execute one or more t imes. Syntax: do{ <statement/block>; }while(condition);
Example: int i=0; do{ Printf ( “Hello \ n ”) ; i++; } while (i<3); Flow diagram Output: Hello Hello Hello
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.
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.