You are on page 1of 12

Programming Fundamentals

Lab
Lecture 4

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Iteration

 Iteration cause statements to be executed zero or more times, subject to some loop-
termination criteria.
 When these statements are compound statements, they are executed in order, except when
either the break statement or the continue statement is encountered.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


In C++

 C++ provides four iteration statements —


while 
do 
for 
range-based for

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


While loop

 Executes statement repeatedly until expression evaluates to zero.

 Syntax

while ( expression )
{
Statement;
}

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


While terminates

 A while loop can also terminate when break, goto or return within the statement body is
executed.
 Use continue to terminate the current iteration without exiting the while loop.
 Continue passes control to the next iteration of the while loop.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Flow control

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Example
Write a program to display numbers from 1 to 20.

int main () {
// Local variable declaration:
int a = 1;
// while loop execution
while( a <= 20 ) {
cout << "value of a: " << a << endl;
a++;
}
return 0;
}

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Example
Write a program to calculate the sum of first consecutive1000 natural numbers.

int sum , number ;


sum = 0 ;
number = 1 ;
while ( number <= 1000 )
{
sum = sum + number ;
number = number + 1 ;
}
cout << “ The sum of the first 1000 integer starting from 1 is ” << sum ;
Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar
Task

 Write a program to print the numbers from 10 in descending order.(Using while loop)

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Task 2

 Write a program take the limit of the series from user and using While loop find the sum of
the series.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Task 3

 Write a program in C++ language to find the factorial of a number. (using while loop)

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar


Task 4

 Write a program to print the table of “6” using while loop.

Prepared by Aqsa Gul, Lecturer Institute of Management Sciences Peshawar

You might also like