Lecture 14 – Loops (while)
Sentinel
controlled
There’s
a problem with for loop. That is, if we want to terminate the program
pre-maturely based upon a condition, we cannot do it. It will execute for the
specified number of times.
For
achieving this functionality, we have two sentinel controlled loops. The term
sentinel refers to a guard.
while
loop
In
while loop the condition is checked first and the control is transferred to the
loop’s body.
Syntax
initialization
while(termination_conditon)
{
//
Statements to be executed
meansToGetToTerminationCondition
}
Figure
3- Breakup of while loop
Let’s continue with
Example 23, let’s compare both loops
|
With for loop
|
With while loop
Example 25 - Display name five times using while
loop
|
||
#include <stdio.h>
#include
<conio.h>
void
main()
{
int
count=0;
clrscr();
for(count=1; count<=5;
count++)
{
printf(“\nHammad Naqvi”);
}
getch();
}
|
#include <stdio.h>
#include
<conio.h>
void
main()
{
int
count=1;
clrscr();
while(count<=5)
{
printf(“\nHammad Naqvi”);
count++;
}
getch();
}
|
Table
9 - Comparison of for and while loop
|
Output
Enter your marks (-ve number to quit): 5
Enter your marks (-ve number to quit): 7
Enter your marks (-ve number to quit): 15
Enter your marks (-ve number to quit): 13
Enter your marks (-ve number to quit): 22
Enter your marks (-ve number to quit): 21
Enter your marks (-ve number to quit): 5
Enter your marks (-ve number to quit): -1
Average marks 12.57142
|
This was same example with two different loop constructs. Now let’s
have another example in which I shall show you how you can limit the iteration
of the loop based upon condition. Consider a scenario where you have to
calculate average marks of the students in computer science subject, and you do
not know the number of students at hand. The program would be able to calculate
the number of students automatically.
#include
<stdio.h>
#include
<conio.h>
void
main()
{
int
student_count=0;
float
marks=0.0, total_marks=0.0; average_marks=0.0;
clrscr();
printf(“\nEnter your marks (-ve number to quit):”);
scanf(“%f”, &marks);
student_count=1;
total_marks = total_marks + marks;
while(marks>0)
{
printf(“\nEnter
your marks (-ve number to quit):”);
scanf(“%f”, &marks);
total_marks = total_marks + marks;
student_count = student_count + 1; // or you can write
student_count++
}
average_marks = (total_marks-marks) / (student_count-1);
printf(“\n\nAverage marks %f”, average_marks);
getch();
}
Example 26 - Calculating average marks using while
loop
Comments
Post a Comment