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

PF-CE Lab02_Flow Control

This laboratory manual for Programming Fundamentals (CL1002) focuses on flow control structures in C++, including nested control structures, the ternary operator, and switch-case statements. It provides detailed explanations and examples for each concept, along with exercises for students to practice coding. The manual emphasizes the importance of operator precedence and offers guidelines for writing effective C++ code.

Uploaded by

almautulamreeka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

PF-CE Lab02_Flow Control

This laboratory manual for Programming Fundamentals (CL1002) focuses on flow control structures in C++, including nested control structures, the ternary operator, and switch-case statements. It provides detailed explanations and examples for each concept, along with exercises for students to practice coding. The manual emphasizes the importance of operator precedence and offers guidelines for writing effective C++ code.

Uploaded by

almautulamreeka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Programming Fundamentals

(CL1002)

LABORATORY MANUAL
BS-CE, Spring 2025

LAB 02
FLOW CONTROL STRUCTURES

________________________________________ __________ ____

STUDENT NAME ROLL NO SEC

______________________________________

LAB ENGINEER'S SIGNATURE & DATE


Maryam Zafar

MARKS AWARDED: /10


_____________________________________________________________________
NATIONAL UNIVERSITY OF COMPUTER AND EMERGING SCIENCES (NUCES), ISLAMABAD
Prepared by: Engr. Aamer Munir, Muhammad Hammad Version: 1.1
Date last
Last edited by: Engr. Azhar Rauf, Engr. Aamer Munir Sep 27, 2018
edited:
Date last
Verified by: Engr. Azhar Rauf Jan 10, 2025
edited:
Repetition and Flow Control Structures LAB 07

Lab Learning Objectives:


In this lab session you will learn about:
1. Nested control structures
2. Ternary operator (? :)
3. Switch-case control structure
Tools needed:
1. PC running Windows Operating System (OS)
2. DevC++ (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 are already taught to you in your
PF theory class.

1. Nested control structures

In C++, a nested if-else statement is used to create a conditional structure within another
conditional structure. This allows you to check multiple conditions and execute different code
blocks based on the results of these conditions.

Nesting can go as deep as is required. There is no limit on the level of nesting.

If the testexpr1 evaluates to true, the statements inside the body of if are executed. If the
testexpr1 evaluates to false, the single statement inside the body of else is executed, which
in itself is an if-else statement, and so on.

Nesting can be done within if body as well, if required.

For example, look at the case below:

if( testexpr1 )
{
//statements to execute if testexpr1 is true
if( testexpr11 )
{
//statements to execute if testexpr11 is true
if( testexpr111 )
{
//statements to execute if testexpr111 is true
}
}
}

2. ternary operator (? :)

Sometimes for simpler conditions ternary operator is used for better readability. For
example, look at the code:

PF LAB NUCES, ISLAMABAD Page 2 of 7


Repetition and Flow Control Structures LAB 07
if( a < b )
max = b;
else
max = a;

Which can be written more compactly as:

max = a < b ? b : a;

to mean the same thing. Alternatively:

a < b ? max = b : max = a;

carries the same behaviour.

3. switch-case control structure

if-else statement allows us to check multiple test expressions or conditions using logical
operators. However, in cases where we need to check the value of a single variable instead
of nested if-elses, use of a switch-case control structure is preferrable.

For example, to test a variable n for various values, switch-case syntax is as follows:

switch( n )
{
case constant1:
//code to be executed if n is equal to constant1
break;
case constant2:
//code to be executed if n is equal to constant2
break;
case constant3:
//code to be executed if n is equal to constant3
break;
.
.
.
default:
//code to be executed if n does not match any
constant
}
When a case constant is found that matches the switch expression, control of the program
passes to the block of code associated with that case.

In the above pseudocode, suppose the value of n is equal to constant2. The compiler will
execute the block of code associated with the case statement until the end of switch block,
or until the break statement is encountered.

The break statement is used to prevent the code running into the next case.

If break statement is not used, all cases after correct case are executed. Sometimes this
may be desirable.

PF LAB NUCES, ISLAMABAD Page 3 of 7


Repetition and Flow Control Structures LAB 07
Give special attention to few important aspects of coding as mentioned below before moving
to actual coding tasks.

Operator precedence:

In case multiple operators are used in a single statement without parentheses then the order
in which the operations will be performed depends on the precedence of the operators.
The following table illustrates operators in the order of their precedence.

Operators Preceden
ce
!, +, - (unary First
operators)
*, /, % Second
+, - Third
<, <=, >, >= Fourth
==, != Fifth
&& Sixth
|| Seventh
= (assignment operator) Last

So, in the following code:

int x=100; x = !x > 10 && x >= 90;

Firstly, the unary operation of logical NOT will be performed on the variable x. Since the
value of x is 100 (true in bool), !x will result in false (i.e., 0 in int). All this is because x taken
as a relational operation implicitly typecasts int to bool.
After !, the precedence of > and >= is same so the operator on the left will be evaluated.
Below is given a step-by-step procedure to highlight evaluation of operators in order.

x =
!x > 10 && x >= 90;
x =
!true > 10 && x >= 90;
x =
false > 10 && x >= 90;
x =
0 > 10 && x >= 90;
x =
false && x >= 90;
x =
false && true; // the second term is actually not
evaluated
// since the first term is false (short-
circuit
// evaluation since false && anything is
false)
x = false;
x = 0;

PF LAB NUCES, ISLAMABAD Page 4 of 7


Repetition and Flow Control Structures LAB 07
To do something against rules of precedence, parentheses are used. For example:

x = !(x > 10) && x >= 90;

Relational statements to test a range of values of a variable:


A C++ statement of the form in an if statement would produce unexpected results:

if ( 0 < x < 10 )

First try to find the values (or range of values of variable x) for which the condition would be
true. Then write a sample code and verify your answer.

The correct way of writing the statement would be:

if ( 0 < x && x < 10 )

Verify!

Comparing floating point numbers for equality:


When comparing a floating-point number with a specific value caution is needed. Floating
point values are rounded off and stored in floating point data types based on their size.
Sometimes a slight change in floating point value does not affect the stored bits at all
(remember a learning in one of the previous labs).

Thus, trying to check a whether a variable f results into the value of  after some
computation as:

if ( f == 3.14159 )

would produce unexpected results if the value of f is not exactly 3.14159 or not stored as
3.14159!

Based on the precision requirements of the problem, instead of trying to match for a specific
value, check whether the value falls within a range of acceptable values or not. For example,
expecting the answer to be correct to three decimal places, the following code should be
written to check if f equals the desired value or not.

if ( f > 3.1415 && f < 3.1417 )

PF LAB NUCES, ISLAMABAD Page 5 of 7


Repetition and Flow Control Structures LAB 07
To test the concepts discussed in this lab manual write C++ code for as many of the
following tasks as possible.

Exercises

Task # 1: Code file name lab02_1.cpp

Write a C++ program that takes a year as input and uses the ternary operator to
determine and print whether it is a leap year or not. (Use ternary operator).

Task # 2: Code file name lab02_2.cpp

Write a program to ask user to enter an operator (either +, -, * or /) and then two floating
point numbers. Then based on which operator is entered by the user, output the result of the
operation. Use switch-case.
If the user enters any other char, the program outputs an error message and quits.

Task # 3: Code file name lab02_3.cpp

Write a program that take marks obtained (out of 75) by the student as an input, and
output the grade obtained by the student. The program should also display an error
message to the user when the marks entered exceeds the total marks i.e. marks
obtained should be less or equal to the 75. (Use else if)

Percentage ≥90 80-90 70-80 60-70 50-60 ≤50

Grade A+ A B C D F

Task # 4: Code file name lab02_4.cpp

Write a program that will take the Direction from user (E, W, N, S) and return the
coordinates as x and y. The program should initially request your current
coordinates i.e. value of x and y and then will ask you which direction you want to go
to. For east just increment x and for west just decrement x. for north increment y just
and vice versa for south. Use switch statement to implement this.

Task # 05: Code file name lab02_5.cpp

Write a small program to take 4 values (a, b, c and d) from user and return the
following result.
• If A is greater than B, then program will then check for values of C and D. if
C is greater than D then result= c – d or result = c +d
• If A is smaller than B, then program will again check the value of C and D. If
C is Greater than D, result = 4*C or result = D*3
Do this in single line using conditional operator.

PF LAB NUCES, ISLAMABAD Page 6 of 7


Repetition and Flow Control Structures LAB 07
Task # 6: Code file name lab2_6.cpp

#include<iomanip.h> is used for setw () manipulator. By default, output is right justified in


its field. You can left-justify text output using the manipulator setiosflags(ios::left).Use this
manipulator, along with setw(), to help generate the following output , use just 5 cout
statements:

Last name First name Street address Town State


-----------------------------------------------------------------------------------------
Jones Bernard 109 Pine Lane Littletown MI
O’Brian Coleen 42 E. 99th Ave. Bigcity NY
Wong Harry 121-A Alabama St. Lakeville IL

Hint: Use #define in the start of program for setiosflags(ios::left) and use that after every
setw () function if left justification of text is required

PF LAB NUCES, ISLAMABAD Page 7 of 7

You might also like