Conditional statements are statements that check certain conditions (boolean expressions) before executing certain statements. Graphical representation using flowcharts (refer to Appendix A) will be used as a tool in helping us follow the flow of execution in single and multiple selection statements.
4.1 Single Selection Statement
“To be or not to be, that is the question.” Or in terms of the single selection statement, we should rephrase it to “To execute or not to execute, that is the question.” In C, the if statement is used for single selection. The statement will be executed if and only if the expression evaluates to true. If more than one statement needs to be executed, these statements must be enclosed within braces ({}). These statements are called compound statements.
Example. Write a program segment that asks for a price from the user and displays the strings ‘Expensive!’ and ‘Can’t Afford!’ if the price is greater than or equal to 1000.
To help us solve the program, let’s first construct our flowchart.
Translating our flowchart, we can come up with the following program segment.
main()
{
float fPrice;
scanf( “%f”, &fPrice );
if ( fPrice >= 1000 )
{
printf( “Expensive!\n” );
printf( “Can’t Afford!” );
}
}
4.2 Multiple Selection Statement
Selection statements are branching mechanisms in programming languages. These branching mechanisms allow us to choose among alternatives. In C, the if-else and the switch statements facilitate our branching.
4.2.1 The if-else Statement
Statement1 will be executed if and only if expression evaluates to true; otherwise, statement2 will be executed. Again, if more than one statement is to be executed in either case, these statements must be enclosed within braces ({}).
Example. Create a flowchart and its corresponding program segment that will ask for a grade from the user and display the strings “Congratulations!” and “You passed.” if the grade is greater than or equal to 60 and displays “Sorry.” and “You failed.” if otherwise.
main()
{
double dGrade;
|
scanf( “%lf”, &dGrade );
if ( dGrade >= 60 )
{
printf(
“Congratulations!\n” );
printf( “You passed.”
);
}
else
{
printf( “Sorry.\n” );
printf( “You failed.”
);
}
|
Example. Create a flowchart and program segment that asks for a grade from the user. Display ‘A’ if the grade entered is greater than or equal to 90, ‘B’ if the grade entered is greater than or equal to 80 but less than 90, ‘C’ is the grade entered is greater than or equal to 70 but less than 80, ‘D’ otherwise.
main()
{
double dGrade;
char cLGrade;
printf( “Enter the grade: \n“ );
scanf( “%lf”, &dGrade );
if ( dGrade >= 90 )
cLGrade = ‘A’;
else if ( dGrade >= 80 )
cLGrade = ‘B’;
else if ( dGrade >= 70 )
cLGrade = ‘C’;
else cLGrade = ‘D’;
printf( “Your equivalent grade is %c\n”, cLGrade );
An else is always paired with the nearest preceding unpaired if. Compare the different diagrams to see the behavior of the various cases.
Example. Draw a flowchart and write the corresponding program that reads in three numbers A, B, and C and determines the largest number.
main()
{int nA, nB, nC;
|
printf( “Enter 3 numbers: “ );
scanf( “%d%d%d”, &nA, &nB, &nC );
if ( nA > nB )
if ( nA > nC )
printf( “A is
the largest.\n” );
else
printf( “C is the largest.\n” );
|
Compound conditions may also be used with the if-else statements.
Example. Create a flowchart and program segment that asks for a grade from the user and checks if the value entered ranges from 0 to 100 (inclusive). If it is, display ‘Grade is valid.’; otherwise, display ‘Grade is invalid.’
main()
{
double dGrade;
printf( “Enter the grade: “ );
scanf( “%lf”, &dGrade );
if ( dGrade >= 0 && dGrade <=100 )
printf( “Grade is valid.\n” );
else
printf( “Grade is invalid.\n” );
}
4.2.2 The switch Statement
Switch statements are useful if there are a lot of alternatives to choose from. However, switch statements can only check equality relationships.
where:
an expression whose value is being tested; only expressions that evaluate to character or integer types are allowed label if value that the expression is checked against statement if the statement that will be executed if the <expression> is equal to the value in the <label i> break;prevents the execution of the next statements; exits from the switch statement default the counterpart of an else statement expression
Once a value applies, the statements associated to the value will be executed. If the break statement is not found after these statements, the next statements will still be executed until the break statement is encountered. Once the break is encountered, the control will proceed to the statement immediately after the close brace (}) of the switch statement. On the other hand, if no values applies, the statement corresponding to the default will be executed. The flowchart for a switch statement that does not contain any break statements look like this:
Example. Write a program segment that will read a date (month, day, and year) in integer form and display the date in the standard format.
main()
{
int nMonth, nDay, nYr;
printf( “Enter month, day, year: “ );
scanf( “%d%d%d”, &nMonth, &nDay, &nYr );
switch ( nMonth )
{
case 1 : printf( “January” );
break;
case 2 : printf( “February” );
break;
case 3 : printf( “March” );
break;
case 4 : printf( “April” );
break;
case 5 : printf( “May” );
break;
case 6 : printf( “June” );
break;
case 7 : printf( “July” );
break;
case 8 : printf( “August” );
break;
case 9 : printf( “September” );
break;
case 10:printf( “October ” );
break;
case 11:printf( “November ” );
break;
case 12:printf( “December ” );
}
printf( “ %d, %d”, nDay, nYr );
}
Example. Write a program segment that reads in the letter grade and displays ‘V. Good!’ if the letter grade is ‘A’, ‘Good!’ if the letter grade is ‘B’ or ‘C’, ‘Fair!’ if the letter grade is ‘D’, and ‘Poor!’ otherwise.
main()
{
char Grade;
printf(“Enter the grade: \n“);
scanf(“%c”, &Grade);
switch (Grade)
{
case ‘A’ : printf(“V.Good!\n”); break;
case ‘B’ :
case ‘C’ : printf(“Good!\n”); break;
case ‘D’ : printf(“Fair!\n); break;
default : printf(“Poor!\n”);
}
}
Example. Write a program segment that reads in the letter grade and displays some messages.
main()
{
char c;
scanf(“%c”, &c);
switch (c)
{
case ‘B’ : printf(“It can be better.\n”);
case ‘C’ : printf(“I will do better!\n\n”);
case ‘A’ : printf(“I love COMPRO1\n”); break;
default : printf(“%s%s%s”, “I shall strive “,
“to be a Christian achiever “,
“for God and country!”);
}
Note that in the example, if the user inputs B, the output will be the following, since the break statement is found after the third printf statement.
It can be better.
I will do better!
I love COMPRO1
Common Programming Errors
1. The if statement does not include the word then. For this reason, it is an error to write
if ( condition ) then
statement;
2. The condition must be enclosed in parenthesis, thus it is wrong to write
if condition
statement;
3. In the if statement, there should be a semicolon at the end of the statement even if it is followed by the else statement. Therefore, it is wrong to write
if ( condition )
statement1
else statement2;
4. No semicolon should follow the word else. For this reason, it might be a logical error to write
if ( condition)
statement1;
else ;
statement2;
5. Using a single equal sign = when a double equal sign == is intended is a logical error. It is syntactically correct to write the following, but the way the system interprets this command is usually not what the user intended.
if (x = 1)
statement1;
6. In the switch construct, the expression that follows the switch must be enclosed in parenthesis. It is wrong to write
switch i
{. . .
. . .
}
7. The term following the case should be an integer or character literal (and not a variable). Therefore, it is wrong to write
case i :
statement;
Self Evaluation Exercises
1. Give the screen output of the program segment below if the respective values entered for nValue1 and nValue 2 are the following:
a.) 90, 80
b.) 0, -1
c.) 1000, 1
d.) -1, 200
main()
{
int nValue1, nValue2;
printf(“Enter two values: “);
scanf(“%d%d”,&nValue1, &nValue2);
printf(“\n”);
if (nValue1 >= 0 && nValue1 <= 100)
if (nValue2 < 0 || nValue2 > 100)
printf(“One\n”);
else printf(“Two\n”);
else if (nValue2 >= 0 && nValue2 <= 100)
printf(“One\n”);
else printf(“Zero\n”);
}
2. What does the program segment do?
main()
{
int num,w,x,y,z;
printf(“Enter a 4-digit number: “);
scanf(“%d”,&num);
w = num % 10;
x = (num / 10) % 10;
y = (num /100) %10;
z = num / 1000;
printf(“%d%d%d%d\n”, w,x,y,z);
}
3. Write a program that displays “ODD” if the input value is an odd number, otherwise display “EVEN”.
4. Write a program that accepts four numbers from the user and displays the highest and the lowest. Assume that there are no duplicate values.
5. Write a program that computes for the total weekly salary, given the number of hours and hourly rate:
total weekly salary = basic salary + bonus
where: basic salary = # of hours x hourly rate
# of hours> 45: bonus of 100
> 40 and <= 45: bonus of 50
> 35 and <= 40: bonus of 35
6. Write a program that will ask the user if he wants to compute the perimeter or the area of a triangle. If the perimeter is wanted, ask the measures of the three sides and compute for the perimeter. If the area is wanted, ask for the measures of the base and height of the triangle and compute for the area. Display the computed value.
7. Write a program that determines the equivalent grade point using the following:
>= 944.0
>= 893.5
>= 833.0
>= 782.5
>=722.0
>= 661.5
>= 601.0
below 600.0
8. Write a program that asks for the salary of an employee and compute for the income tax to be paid based on the given salary. Use the following scheme:
2% : for the first 1000 pesos
7% : for the next 2000 pesos
11% : for the remaining value
9. Company A processes loan applications based on four items namely: monthly salary, monthly deduction, status (regular or casual), and years of service to the current employer. The company's policy in granting loans is summarized as follows:
The amount being applied for a loan is:
"Approved' if all of the following conditions are met:
a) the amount of loan is not greater than twice the monthly salary
b) the monthly deduction is not greater than 1/3 of the monthly salary
c) the loan applicant is a regular employee or the years of service to the current employer is 3 years or more
"Disapproved' if at least one of the following conditions exist:
a) the amount of loan is greater than 3 times the monthly salary
b) the monthly deduction is greater than 1/2 of the monthly salary
Applications neither approved nor
disapproved will be subjected to 'Review' by a loan
committee for final disposition.
|
Write a program segment which will accept
the necessary data of a loan applicant and
automatically determine the disposition as
'Credit Accepted', 'Credit Rejected', or
'Review Required'. Use the following
variables
Amt - amount of loan being applied for)
Ms- monthly salary
Md- monthly deduction
Stat - status (R if regular, C otherwise)
Yrs- years of service on the current job
|
10. Write a program that displays the day of the week in words given a number from 1 to 7. Assume that 1 is Monday and 7 is Sunday.
Chapter Exercises
|
1. Give the screen output of the program segment below if the respective values were entered for X:
a.) 90.1
b.) 80
c.) 70
d.) 67.7
e.) -10
|
main()
{double X;
|
printf(“Enter a value: “);
scanf(“%lf”, &X);
if (X >= 0 && X <= 100)
if (X > 95)
printf(“A+\n”);
else if (X >= 70)
if (X >=80)
if (X >=
90)
printf(“A\n”);
else if (X
>= 85)
printf(“B+\n”);
else printf(“B\n”);
else if (X >=
75)
printf(“C+\n”);
else
printf(“C\n”);
else
printf(“D\n”);
else printf(“You\’re playing hard to get!!!\n”);
|
}
|
2. Show the screen output of the given program segment.
main()
{int
x,y,z;
x = 5; y = 5; z = 5;
x = 2; y = 3;
x = x * y + z; printf(“%d%d%d\n”,x,y,z);
if (y == z) printf(“x%d\n”, y);
else if (y > z) printf(“z%d\n”,x);
else printf(“y%d\n”,z);
if (x > 10)
{
y = x * 2 - z;
if (y > 5)
{
printf(“xyz”);
printf(“\n”);
printf(“%d”, y);
x = x + y;
if (x < y) printf(“today\n”);
else printf(“tomorrow\n”);
}
else printf(“hi\n”);
z = z + 3;
}
if (z == y)
{
z = 1; y = 2;
}
else if (x != y) z = z +2;
printf(“%d %d %d\n”,x,y,z);
}
3. What is the screen output of the following:
main()
{int i =7, j = 7;
if ( i == 1)
if (j == 2)
printf(“%d\n”, i + j);
else printf(“%d\n”, i - j);
printf(“%d\n”, i);
}
4. Write a program that will display ‘V.Good!’ and ‘Keep it up!’ if the grade of a student is 4.0.
5. Construct a program that computes the state income tax according to the following formula:
Net income is gross income minus deductions (both given as input); tax is:
3% on each peso of net income up to 8000
5% on each peso of net income from 8001 to 15000
8% on each peso of net income over 15000
6. Ask the user for the hours worked for the week and the hourly rate. The basic salary is computed as:
hours worked * hourly rate
Bonuses are given:
No. of hours > 45Bonus of 100 pesos
No. of hours > 40 and <= 45 Bonus of 50 pesos
No. of hours > 35 and <=40 Bonus of 25 pesos
Display the basic salary, bonus, and total salary (basic salary + bonus) for the week.
7. Marcos Group of Companies gives year-end bonus to its employees based on their number of years of service and their salary, using the following:
Years of serviceBonus
11% of salary
2 to 32% of salary
4 to 105% of salary
10+10% of salary
Write a program that will compute for the bonus using the specifications stated.
8. Write a program that accepts three numbers from the user and displays the values from the highest to the lowest. There are no duplicate values.
9. Write a program that will display ‘IT’S COLD!’ if the given temperature is less than 20, ‘IT’S HOT!’ if the given temperature is greater than 30, ‘COOL CLIMATE!’ otherwise.
10. Write a program that displays ‘QUALIFIED!’ if a female applicant is single and her age ranges from 16 to 25 (inclusive); otherwise display ‘SORRY! NOT QUALIFIED!’.
11. Write a program that gives a discount of 100 pesos if the shirt bought is XL and the price is greater than 500; and a discount of 50 pesos if the shirt bought is L and the price is greater than 600.
12. Construct a program that accepts time in 24-hour notation (assume input is from 0 to 2359 only) and output them in 12-hour notation.
Example000012:00a.m.
13. Construct a program that will accept a number from 1 - 999 and produce the equivalent Roman numeral for the given number.
14. A bicycle salesperson is offered a choice of wage plans: (1) a straight salary of $300 per week; (2) $3.50 per hour for 40 hours plus a 10% commission on sales; (3) a straight 15% commission on sales with no other salary. Write a program that takes as input the salesperson's expected weekly sales and outputs the wages paid under each plan in increasing order.
15. Write a program that will determine the additional state tax owed by an employee. The state charges a 4% tax on net income. Net income is determined by subtracting a P3000.00 for each dependent on gross income. Your program segment will read/gross income, number of dependents, and tax amount already deducted. It will then compute the actual tax owed and print the difference between tax owed and tax deducted followed by the message 'SEND CHECK' or 'REFUND' depending on whether this difference is positive or negative.
16. The New Telephone Company has the following rate structure for long-distance calls:
a) Any call started after 6:00 P.M. gets a 50% discount.
b) Any call started after 8:00 A.M. is charged full price.
c) All calls are subject to a 4% tax.
d) The regular rate for a call is P5.00 per minute./
e) Any call longer than 60 minutes receives a 15% discount on its cost(after any other discount is taken but before tax is added).
Write a program that processes several calls by reading the start time for each call and the length of each call. The gross cost (before any discounts or tax) should be printed followed by the net cost (after discounts are deducted and tax is added).
17. A circular racetrack is composed of four portions: concrete, mud, sand, and asphalt. Sly Slick’s car takes 30 seconds to cross the concrete, 55 seconds to cross the mud, 47 seconds to cross the sand, and 38 seconds to cross the asphalt. Make a program segment that will ask for a positive TIME value in seconds and output WHERE in the track Sly’s car is. Assume that the race starts at the beginning of the concrete portion. Hint: Where is his car after 50 seconds? After 200 seconds? After 1634 seconds?