0% found this document useful (0 votes)
3 views

PF_Lab01_Revision_Repetition_&_Flow_Control_Structures (2)

The document is a laboratory manual for a Programming Fundamentals Lab (CS1002) focusing on repetition and flow control structures in C++. It outlines the learning objectives, tools required, and provides detailed explanations of various loop structures such as while loops, do-while loops, and for loops, including their syntax and use cases. Additionally, it includes a task for students to implement a program that converts speeds from kilometers per hour to miles per hour using a for loop.

Uploaded by

i222222
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

PF_Lab01_Revision_Repetition_&_Flow_Control_Structures (2)

The document is a laboratory manual for a Programming Fundamentals Lab (CS1002) focusing on repetition and flow control structures in C++. It outlines the learning objectives, tools required, and provides detailed explanations of various loop structures such as while loops, do-while loops, and for loops, including their syntax and use cases. Additionally, it includes a task for students to implement a program that converts speeds from kilometers per hour to miles per hour using a for loop.

Uploaded by

i222222
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Programming Fundamentals Lab

(CS1002 )
LABORATORY MANUAL
Spring 2025

LAB 01
Revision REPETITION AND FLOW CONTROL STRUCTURES

Nimra Khan 24i-6145 EE-D

STUDENT NAME ROLL NO SEC

______________________________________

LAB ENGINEER'S SIGNATURE & DATE


Nimra Fatima
Fasih Ahmad

MARKS AWARDED: /10


____________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (NUCES), ISLAMABAD
Prepared by:
Fasih Ahmad 17.01.2025
Nimra Fatima

Verified by:
19.01.2025 Version 1.0
Shahid Qureshi
Revision Repetition and Flow Control Structures LAB 01

Lab Learning Objectives:


In this lab session you will learn about:
 To revise the understanding of Flow Control Structures.
 To recall and implement Repetition Control Structures or Loops.
Tools needed:
1. PC running Windows Operating System (OS)
2. Dev C++/Visual Studio (installed)

Turn on the PC and log into it using your student account information.

Note:
The information and concepts discussed in this
lab manual are in sufficient detail but are
still not exhaustive. It is assumed that all
these concepts have already been taught in your
theory class.

1. Repetition Control Structures or Loops


A loop is a control structure that causes a statement or group of statements to repeat. C+
+ has three looping control structures: the “while” loop, the “do-while” loop, and the “for”
loop. The difference between these structures is how they control the repetition.
Whenever we need to do any task repetitively, we use loops. Three types of loops are
used in C++ -- while loop, for loop, and do-while loop.

while loop:
The while loop has two important parts:
I. An expression that is tested for a true or false value.
II. A statement or block that is repeated as long as the expression is true.
The following Figure shows the logic of a while loop.

The structure of a while loop is:

while(expression)
statement;

PF LAB FAST NUCES, ISLAMABAD Page 2 of 14


Revision Repetition and Flow Control Structures LAB 01
In general format, an expression is any expression that can be evaluated as true or false,
and the statement is any valid C++ statement. The first line shown in the format is
sometimes called the loop header. It consists of the keyword “while” followed by an
expression enclosed in parentheses.
Here’s how the loop works: the expression is tested, and if it is true, the statement is
executed. Then, the expression is tested again. If it is true, the statement is executed.
This cycle repeats until the expression is false. The statement that is repeated is known
as the body of the loop. It is also considered a conditionally executed statement because
it is executed only under the condition that the expression is true.
Notice there is no semicolon after the expression in parentheses. Like the if statement,
the while loop is not complete without the statement that follows it.
If you want a while loop to repeat a block of statements, its format is:

while(expression)
{
statement;
statement;
// Place as many statements here
// as necessary
}

The while loop works like an “if” statement that executes over and over. As long as the
expression inside the parentheses is true, the conditionally executed statement or block
will repeat. Figure 1 uses the while loop to print “Hello” five times.

Figure 1

Let’s understand this program. In line 7 an integer variable, number, is defined and
initialized with the value 0. In line 9 the “while” loop begins with this statement:
while (number < 5)
This statement tests the variable number to determine whether it is less than 5. If it is,
then the statements in the body of the loop (lines 11 and 12) are executed; The
statement in line 11 prints the word “Hello.” The statement in line 12 uses the increment
operator to add one to a number. This is the last statement in the body of the loop, so
after it executes, the loop starts over. It tests the expression number < 5 again, and if it is
true, the statements in the body of the loop are executed again. This cycle repeats until
the expression number < 5 is false. This is illustrated in the below figure.

PF LAB FAST NUCES, ISLAMABAD Page 3 of 14


Revision Repetition and Flow Control Structures LAB 01

Each repetition of a loop is known as an “iteration”. This loop will perform five iterations
because the variable number is initialized with the value 0, and it is incremented each
time the body of the loop is executed. When the expression number < 5 is tested and
found to be false, the loop will terminate and the program will resume execution at the
statement that immediately follows the loop.

The above figure shows the logic of this loop. Where the expression provides an entry
condition to the loop, i.e., the loop will be executed only when the expression evaluates
to true. Once the body of the loop is executed, the expression is checked again and if it
evaluates to true the body of the loop is executed again. This evaluation of the
expression and execution of the body of the loop continues until the expression
evaluates to false after which the code next to the body of the loop executes.

Don’t Forget the Braces with a Block of Statements:


If you write a loop that conditionally executes a block of statements, don’t forget to
enclose all of the statements in a set of braces. If the braces are accidentally left out, the
while statement conditionally executes only the very next statement. For example, look
at the following code:

In this code, the number++ statement is not in the body of the loop. Because the braces
are missing. The “while” statement only executes the statement that immediately follows
it. This loop will execute infinitely because there is no code in its body that changes the
number variable.
Each execution of the body of the loop is called an “iteration”.
Another common pitfall with loops is accidentally using the = operator when you intend to
use the == operator. The following is an infinite loop because the test expression assigns

PF LAB FAST NUCES, ISLAMABAD Page 4 of 14


Revision Repetition and Flow Control Structures LAB 01
1 to the remainder each time it is evaluated instead of testing whether the remainder is
equal to 1.

Remember, any nonzero value is evaluated as true.

Counter-Controlled while loop:


A counter is a variable that is regularly incremented or decremented each time a loop
iterates.
Sometimes it’s important for a program to control or keep track of the number of
iterations a loop performs. For example, figure 2 displays a table consisting of the
numbers 1 through 10 and their squares, so its loop must iterate 10 times.

Figure 2

In the above program (figure 2), the variable num, which starts at 1, is incremented each
time through the loop. When num reaches 11 the loop stops. num is used as a counter
variable, which means it is regularly incremented in each iteration of the loop. In
essence, num keeps count of the number of iterations the loop has performed.

do-while loop:
The do-while loop is a posttest loop, which means its expression, is tested after each
iteration.
The do-while loop looks something like an inverted while loop. Here is the do-while
loop’s format when the body of the loop contains only a single statement:

PF LAB FAST NUCES, ISLAMABAD Page 5 of 14


Revision Repetition and Flow Control Structures LAB 01

do
statement;
while (expression);

Here is the format of the do-while loop when the body of the loop contains multiple
statements:

Do
{
statement;
statement;
// Place as many statements here
// as necessary
} while (expression);

NOTE: The do-while loop must be terminated with a semicolon.

The do-while loop is a posttest loop. This means it does not test its expression until it has
completed an iteration. As a result, the do-while loop always performs at least one
iteration, even if the expression is false to begin with. This differs from the behavior of a
while loop, which you will recall is a pretest loop. For example, in the following while
loop, the cout statement will not execute at all:

But the cout statement in the following do-while loop will execute once because the do-
while loop does not evaluate the expression x < 0 until the end of the iteration.

Below figure illustrates the logic of the do-while loop.

You should use the do-while loop when you want to make sure the loop executes at least
once. For example, the following program (figure 3) averages a series of three test
scores for a student. After the average is displayed, it asks the user if he or she wants to
average another set of test scores. The program repeats as long as the user enters Y for
yes.

PF LAB FAST NUCES, ISLAMABAD Page 6 of 14


Revision Repetition and Flow Control Structures LAB 01

Figure 3
When this program was written, the programmer had no way of knowing the number of
times the loop would iterate. This is because the loop asks the user if he or she wants to
repeat the process. This type of loop is known as a user-controlled loop because it
allows the user to decide the number of iterations.

for loop:
The “for” loop is ideal for performing a known number of iteration(s).
In general, there are two categories of loops: conditional loops and count-controlled
loops. A conditional loop executes as long as a particular condition exists. For example,
an input validation loop executes as long as the input value is invalid. When you write a
conditional loop, you have no way of knowing the number of times it will iterate.
Sometimes you know the exact number of iterations that a loop must perform. A loop
that repeats a specific number of times is known as a count-controlled loop. For
example, if a loop asks the user to enter the sales amounts for each month in the year, it
will iterate twelve times. In essence, the loop counts to twelve and asks the user to enter
a sales amount each time it makes a count. A count-controlled loop must possess three
elements:
1. It must initialize a counter variable to a starting value.
2. It must test the counter variable by comparing it to a maximum value. When the
counter variable reaches its maximum value, the loop terminates.
3. It must update the counter variable during each iteration. This is usually done by
incrementing the variable.
Count-controlled loops are so common that C++ provides a type of loop specifically for
them. It is known as the “for” loop. The for loop is specifically designed to initialize, test,
and update a counter variable. Here is the format of the for loop when it is used to repeat

PF LAB FAST NUCES, ISLAMABAD Page 7 of 14


Revision Repetition and Flow Control Structures LAB 01
a single statement:

for ( initialization; test; update )


statement;

The format of the “for” loop when it is used to repeat a block is:

for ( initialization; test; update )


{
statement;
statement;
// Place as many statements here
// as necessary.
}

The first line of the for loop is the loop header. After the keyword “for”, there are three
expressions inside the parentheses, separated by semicolons. (Notice there is not a
semicolon after the third expression.) The first expression is the initialization expression.
It is normally used to initialize a counter variable to its starting value. This is the first
action performed by the loop, and it is only done once. The second expression is the test
expression. This is an expression that controls the execution of the loop. As long as this
expression is true, the body of the “for” loop will repeat. The for loop is a pretest loop, so
it evaluates the test expression before each iteration. The third expression is the update
expression. It executes at the end of each iteration. Typically, this is a statement that
increments the loop’s counter variable.
Here is an example of a simple for loop that prints “Hello” five times:

In this loop, the initialization expression is count = 0, the test expression is count < 5, and
the update expression is count++. The body of the loop has one statement, which is the
cout statement. The following flow chart (figure 5) illustrates the sequence of events that
takes place during the loop’s execution. Notice that Steps 2 through 4 are repeated as
long as the test expression is true.

PF LAB FAST NUCES, ISLAMABAD Page 8 of 14


Revision Repetition and Flow Control Structures LAB 01

Figure 4: Show the "for" loop logic in form of flow chart

Notice how the counter variable, count, is used to control the number of times that the
loop iterates. During the execution of the loop, this variable takes on the values 1
through 5, and when the test expression count < 5 is false, the loop terminates. Also
notice that in this example the count variable is used only in the loop header, to control
the number of loop iterations. It is not used for any other purpose. It is also possible to
use the counter variable within the body of the loop. For example, look at the following
code:

The counter variable in this loop is the number. In addition to controlling the number of
iterations, it is also used in the body of the loop. This loop will produce the following
output:

As you can see, the loop displays the contents of the number variable during each
iteration. The following program (figure 6) shows another example of a for loop that uses
its counter variable within the body of the loop. This is yet another program that displays
a table showing the numbers 1 through 10 and their squares.

PF LAB FAST NUCES, ISLAMABAD Page 9 of 14


Revision Repetition and Flow Control Structures LAB 01

Figure 5
You should use the for loop instead of the while or do-while loop in any situation that
clearly requires an initialization, uses a false condition to stop the loop, and requires an
update to occur at the end of each loop iteration. Above program (figure 6) is a perfect
example. It requires that the num variable be initialized to 1, it stops the loop when num
is greater than 10, and it increments num at the end of each loop iteration. Recall that
when we first introduced the idea of a counter variable we examined a program in figure
2, which uses a while loop to display the table of numbers and their squares. Because
the loop in that program requires an initialization, uses a false test expression to stop,
and performs an increment at the end of each iteration, it can easily be converted to a
“for” loop. Below figure 7 shows how the while loop in figure 2 and the “for” loop in
Program 6 each have initialization, test, and update expressions.

Figure 6

PF LAB FAST NUCES, ISLAMABAD Page 10 of


14
Revision Repetition and Flow Control Structures LAB 01

Task # 1:

Write a program that displays a table of speeds in kilometers per hour with their values
converted to miles per hour. The formula for converting kilometers per hour to miles per hour
is:
MPH = KPH * 0.6214
In the formula, MPH is the speed in miles per hour and KPH is the speed in kilometers per
hour. The table that your program displays should show speeds from 60 kilometers per hour
through 130 kilometers per hour, in increments of 10, along with their values converted to
miles per hour. The table should look something like this: (Use for Loop)

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int kph=50, mph;
cout<<"kph"<< "\t"<< "mph"<<endl;
for(int i=0; i<8; i++)
{
kph+=10;
cout<<kph<<"\t"<<kph*0.6214<<endl;
}
return 0;
}
kph mph
60 37.284
70 43.498
80 49.712
90 55.926
100 62.14
110 68.354
120 74.568
130 80.782

--------------------------------
Process exited after 0.1095 seconds with return value 0
Press any key to continue . . .

Task # 2:

Develop a program that asks the user to input a positive integer and uses a while loop to find
all its divisors. The program should keep running until the user enters 0. (Use While Loop)

PF LAB FAST NUCES, ISLAMABAD Page 11 of


14
Revision Repetition and Flow Control Structures LAB 01

Enter a positive integer to find its divisors (enter 0 to exit): 12


Divisors of 12 are: 1 2 3 4 6 12
Enter another positive integer (or 0 to exit): 0
Program terminated.

#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int num, i=1, devisor;
cout<< "Enter a number"<<endl;
cin>>num;
while(i<=num)
{
if(num%i==0)
cout<<"devisors are"<<"\t"<< i<< endl;
i++;
}

}
Enter a number
4
devisors are 1
devisors are 2
devisors are 4

--------------------------------
Process exited after 2.847 seconds with return value 0
Press any key to continue . . .
Task# 3:

Write a C++ program that prompts the user to guess a secret number (between 1 and 100).
The program should use a flag-controlled while loop to repeatedly ask the user for guesses
until they guess the correct number. The program should provide feedback if the guess is
too high or too low.

 Set a flag to false initially.


 Once the user guesses the correct number, set the flag to true to exit the loop.
 Display a congratulatory message when the correct guess is made.

#include<iostream>
using namespace std;
int main()
{
int guess, secretnum=50;
bool flag=false;
while(!flag)
{
cout<< "Enter a guess number"<<endl;
cin>>guess;
if(guess>secretnum)

PF LAB FAST NUCES, ISLAMABAD Page 12 of


14
Revision Repetition and Flow Control Structures LAB 01

{
cout<<"your guess is too high enter again"<<endl;
}
if(guess<secretnum)
{
cout<<"your guess is too low enter again"<<endl;
}
if(guess==secretnum)
{
cout<<"your guess is right"<<endl;
flag=true;
}

}
}
Enter a guess number
5
your guess is too low enter again
Enter a guess number
50
your guess is right

--------------------------------
Process exited after 9.157 seconds with return value 0
Press any key to continue . . .
Task# 4:

Write a program that checks if a given number is a perfect number (e.g.; 6, 28, 496, … are
perfect numbers). A perfect number is a positive integer that is equal to the sum of its proper
divisors (excluding the number itself like; 6 = 3+2+1). (Use do-while Loop)
Hint: Continue summing divisors until you reach half of the number.

# include <iostream>
using namespace std;
int main()
{
int n,i=1, sum=0;
cout<<"Enter a number"<<endl;
cin>>n;
do
{
if(n%i==0)
{
sum=sum+i;
i++;
}} while(i<=n/2);
if(sum==n)
{
cout<<"its a perfect number";
}

PF LAB FAST NUCES, ISLAMABAD Page 13 of


14
Revision Repetition and Flow Control Structures LAB 01
else
{
cout<<"its not a perfect number";
}

Enter a number
6
its a perfect number
--------------------------------
Process exited after 2.07 seconds with return value 0
Press any key to continue . . .}

PF LAB FAST NUCES, ISLAMABAD Page 14 of


14

You might also like