Mathematics & Computer Programming: Toqeer Mahmood
Mathematics & Computer Programming: Toqeer Mahmood
Programming
Toqeer Mahmood
Dept. of Civil Engg.
UET, Taxila
Lecture
#
07
The “while” Loop
It is a conditional loop statement.
It is used to execute a statement or a set of
statements as long as the given condition remains
true.
Syntax:
while (condition)
statement;
while (condition)
{
statement(s);
}
The “while” Loop
When “while” loop statement is executed,
the compiler first evaluates the given
condition.
If the given condition is true the
statement/s in the body of the loop
executes.
There must be a statement to make the
loop condition false to end the execution
of the loop. Other wise the loop never
ends and becomes an infinite loop.
Flow chart of the “while” loop
False
condition
True
Body of Loop
Statement
immediately after
while loop
Sample Program
Write a program to calculate the sum of first ten odd numbers and also print
the ODD numbers.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int a=1, sum=0;
while (a<=20)
{
sum = sum + a;
cout<< a <<endl;
a = a + 2;
}
cout<<“----------”;
cout<<“sum = ”<<sum<<endl;
getch();
}
Sample Program
Write a program to print a table of a given number
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int table, n=1;
Syntax:
do
{
statement/s ;
}
while (condition);
The “do-while” loop
In “do-while” loop, the body of the loop is
executed at least once before the
condition is tested.
It iterates as long as the test condition
remains true.
If the given condition becomes false at any
stage during the program execution, the
loop terminates and control shifts to the
statement that comes immediately after
the keyword “while”.
Flow chart of the “do-while” loop
Body of Loop
condition
True
False
Statement
immediately after
while loop
Difference between “while” and
“do-while” loop
In “while” loop, the test condition comes
before the body of the loop. First the
condition is tested and then the body of
the loop is executed.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int n;
n=1;
do
{
cout << n << endl;
n++;
}
while (n<=10);
getch();
}
Sample Program
Write a program to input and print the record of a student. Repeat this
process for other students until the given condition remains true.
#include <iostream.h>
#include <conio.h>
void main()
{
int marks;
char name[25], address[15], ch;
do
{
clrscr();
cout << “Enter name of a student = ”; cin >> name;
cout << “Enter Address of student = ”; cin >> address;
cout << “Enter marks obtained = ”; cin >> marks;
getch();
}
Lab work
Write all the example programs of
todays lecture.