You are here: Home » Content » Selection Structures

1. OBJECTIVE

The objective of Lab 2 is to practice C++’s selection structures, such as:
  • if
  • if … else
  • switch

2. EXPERIMENT

2.1 Run the following program:
// BEEP : ‘\x07’
#include <iostream.h>
#define BEEP cout << “\a \n”
int main()
{
int num;
cout << “Please enter a number “;
cin >> num;
if (num == 1)
{ BEEP; }
else if (num == 2)
{ BEEP; BEEP; }
else if (num == 3)
{ BEEP; BEEP; BEEP; }
else if (num == 4)
{ BEEP; BEEP; BEEP; BEEP; }
else if (num == 5)
{ BEEP; BEEP; BEEP; BEEP; BEEP; }
return 0;
}
2.2 Run the following program:
#include <iostream.h>
#define BEEP cout << “\a \n”
int main()
{
int num;
cout << “Please enter a number “;
cin >> num;
switch (num)
{
case (1): { BEEP;
break; }
case (2): { BEEP; BEEP;
break; }
case (3): { BEEP; BEEP; BEEP;
break; }
case (4): { BEEP; BEEP; BEEP; BEEP;
break; }
case (5): { BEEP; BEEP; BEEP; BEEP; BEEP;
break; }
}
return 0;
}
2.3 Remove the break statements from the above program and then try it again and explain the result.
2.4 Use switch statement to rewrite the following code segment:
if (num == 1)
{cout << “Alpha”; }
else if (num == 2)
{ cout << “Beta”; }
else if (num == 3)
{ cout << “Gamma”; }
else
{ cout << “Other”; }
2.5 Write a program that inputs the integer variable n consisting of 3 digits and displays it in ascending order of digits.
Example: n = 291. It should be displayed as 129.
2.6 Write a program that inputs a date with correct month, year and day components, and then checks if the year is a leap year or not. Show the result on the screen.
2.7 Write a program that can calculate the fee for a taxi ride. The formula is as follows:
  • The first kilometer costs 5000.
  • Each next 200m costs 1000.
  • If the distance is more than 30km then each next kilometer adds 3000 to the fee.
The program has to input the total distance (in km) and calculate the charge.
  • Write a program that inputs a date consisting of day, month, and year components. Check if the date is valid or not and if it is, determine what its previous day is. Example: if the date is 01/01/2003 then its previous day is 31/12/2002.

Comments, questions, feedback, criticisms?

Send feedback