Lab Exercise
Lab Exercise
Lab Exercise
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;
#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;
default: cout<<funny<<endl;
}
system ("pause");
return 0;
}
3. Change the following series of if-then statements into a nested if-else-if structure
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;
}
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++;
}
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.