Lecture 13 – Loops (for)


There are situations where we need to repeat a statement or a number of statements. To achieve this functionality C provides us with two types of loops or iterative structures.

Counter controlled

This type of loop executes for the specified number of times. We have only one loop in this category; that is a ‘for’ loop.

Syntax

for(intilization; termination_condition; meansToGetToTerminiationCondition)

{

// statements to be executed

}

 

A labeled diagram…


Figure 2 - Breakup of for loop

Keyword is a reserved word which cannot be used for any other purpose. It is somewhat like an instruction for the compiler.

Initialization is required at this step, because we need to tell from where to start.

Termination condition is required because we do not want an infinite loop, it has to end stop sometime.

There must be some way in which you can get to the termination condition; otherwise there would be an infinite loop.

 

Let’s write a program to display your name five times, without a loop and then with a loop.

Without loop
Example 23 - Display name five times without loop
With for loop
Example 24- Display name five times with for loop

Output
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
#include <stdio.h>


#include <conio.h>
void main()
{
clrscr();
printf(“\nHammad Naqvi”);
printf(“\nHammad Naqvi”);
printf(“\nHammad Naqvi”);
printf(“\nHammad Naqvi”);
printf(“\nHammad Naqvi”);
getch();
}                             

Output
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
Hammad Naqvi
#include <stdio.h>
#include <conio.h>
void main()
{
int count=0;
clrscr();
for(count=1; count<=5; count++)
                {
                printf(“\nHammad Naqvi”);
                }
getch();
}                             

Table 8 - Advantage of using Loop

The program in Example 24 is flexible. It is flexible in a sense if we need to print the name for 100 times; we can do it just by changing count<=5 to count<=100. But in the Example 23 we need to type the lines for a total of 100 times.

Comments

Popular posts from this blog

Lecture 17 – Functions (continued)

Lecture 6 – Operators in C (continued)

Lecture 10 – Decisions (if-else-if)