Lab 2
Lab 2
Lab 2
Control structures
In this lab, we will learn about control structures which include conditional and loop statements.
Instruction
1. Conditional Statements
Conditional statements allow the program to make decisions based on conditions (selectively).
Below are some common conditional statements in C/C++.
• if-else statement (two-way selection): Executes a block of code if the condition is true,
otherwise executes another block of code.
1 if ( condition )
2 {
3 // Code
4 }
5 else
6 {
7 // Code
8 }
• switch statement: An alternative to if-else when there are multiple conditions based on
the value of a single variable.
1 switch ( variable )
2 {
3 case < first value >:
4 // statements here
5 break ; // Prevents fall - through to subsequent cases
6 case < second value >:
7 // statements here
8 break ;
9 default :
10 // statements here
11 }
2. Loop Statements
Loop statements allow executing a block of code repeatedly. C/C++ provides three types of loops:
• do-while loop: Executes the code at least once and then continues if the condition is true.
1 int i = 1;
2 do
3 {
4 cout << " Number : " << i << endl ;
5 i ++;
6 } while ( i <= 10) ;
Exercises
Exercise 1. Letter grade scale
Write a program to input a score on the ten-point scale and convert it to the letter grade scale.
The conversion method is defined in the table below.
Ten-point scale Letter grade scale
8.0 ≤ x ≤ 10 A
6.0 ≤ x < 8.0 B
5.0 ≤ x < 6.0 C
3.0 ≤ x < 5.0 D
x < 3.0 F
Example:
Input Output
9.2 A
Input Output
7 Seven
-10 Unknown
• Not a triangle: If the sum of any two sides is not greater than the third side.
Example:
Input Output
3 3 3 Equilateral triangle
Exercise 5: Tomorrow
Write a program to input three values: day, month, and year. The program should determine and
output tomorrow’s date. There are some information:
Example:
Input Output
31 12 2023 1 1 2024
28 2 2024 29 2 2024
28 2 2023 1 3 2023
29 2 2023 Not a valid date
Exercise 6. Approximate ex
Write a program to approximate the value of ex using the Maclaurin expansion up to k terms.
The formula for ex is:
x x2 x3 xk
ex = 1 + + + + ··· +
1! 2! 3! k!
Your program should input two values: a float x and an integer k (the number of terms).
Example:
Input Output
1 5 2.71667
0.5 10 1.64872
-1 15 0.367879
Input Output
2 Prime
3 Prime
4 Not Prime
Input Output
6 Perfect
28 Perfect
12 Not Perfect
15 Not Perfect
Submission
Your source code must be contributed in the form of a compressed file and named your submission
according to the format StudentID.zip. Here is a detail of the directory organization:
StudentID
Exercise 1.cpp
Exercise 2.cpp
Exercise 3.cpp
Exercise 4.cpp
Exercise 5.cpp
Exercise 6.cpp
Exercise 7.cpp
Exercise 8.cpp
Exercise 9.cpp
Exercise 10.cpp
The end.