Lab Exercise

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

[LAB 4 EXERCISE, WEEK 7]

LAB 04 KMK1093 BASIC PROGRAMMING


EXERCISE 4.0

1. Explain why you cannot convert the following if/else if statement into a switch statement

if (temp == 100)
x = 0;
else if (population > 1000)
x = 1;
else if (rate < 0.1)
x = -1;

2. What will the following source code display :

#include<iostream>
using namespace std;
int main()
{
int funny = 7, serious = 15;
funny = serious * 2;

switch (funny)
{
case 0 : cout<<"This is funny \n";
break;

case 30: cout<<"This is serious \n";

case 32: cout<<"This is seriously funny \n";

default: cout<<funny<<endl;
}

system ("pause");
return 0;
}

3. Change the following series of if-then statements into a nested if-else-if structure

if (weight >= 100)


cout<<”Very heavy.”;
if (weight >= 50 && weight <= 99.9)
cout<<”Heavy.”;
if (weight >= 10 && weight <= 49.9)
cout<<”Slightly Heavy.”;
if (weight >= 0.1 && weight >= 9.9)
cout<<”Light.”;
if (weight < 0)
cout<<”Wrong input.”;

1 KMK1093 Basic Programming | [ FCSHD ]


[LAB 4 EXERCISE, WEEK 7]

4. Rewrite the following program. Use a switch statement instead of the if/else if statement.

#include<iostream>
using namespace std;
int main( )
{
int selection;
cout<<”Which formula do you want to see ?\n\n”;
cout<<”1. Area of a circle \n”;
cout<<”2. Area of a rectangle \n”;
cout<<”3. Area of a cyclinder \n”;
cout<<”4. None of them \n”;
cin >> selection;
if (selection == 1)
cout<<”Pi times radius squared\n”;
else if (selection == 2)
cout<<”Length times width \n”;
else if (selection == 3)
cout<<”Pi times radius squared times height\n”;
else if (selection == 4)
cout<<”Well okay then, good bye!\n”;
else
cout<<”Not good with numbers.\n”;
return 0;
}

5. Identify the output of the following c++ statements :

a. count = 1;
y = 100;
while (count<100)
{
y = y - 1;
count++;
}

b. int i = 0;
while(i < 8)
{
if (i%2 ==0) cout << i + 1 << endl;
else if (i%3 == 0) cout << i*i << endl;
else if (i%5 == 0) cout << 2*i - 1 << endl;
else
cout << i << endl;
i++;
}

2 KMK1093 Basic Programming | [ FCSHD ]


[LAB 4 EXERCISE, WEEK 7]

c. int x,y,z;
x = 4; y = 5;
z = y + 6;
while (( (z-x) % 4) != 0)
{
cout << z << “ “;
z = z + 7;

}
cout<<endl;

6. The FCSHD Golf Club which currently charges RM6,830 per year for membership, has announced it will increase
its membership fee by 5% each year for the next 5 years. Write a complete program that uses a loop (while)
to display the projected rates for the next 5 years.

7. Write a complete program that allows students to enter a mark for a test. Calculate the total and average of the
marks. If the mark is less than 0 or greater than 100, the program should display the text ‘invalid mark’. The
process will continue until the user requests the program to stop.

3 KMK1093 Basic Programming | [ FCSHD ]

You might also like