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.
42
Conditional
Statements
4.2.1
The if-else Statement
Format:
if ( expression )
statement1;
else statement2;
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 ({}).
The above format is represented as:
False
expression
True
statement1
statement2
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.
43
Chapter
4
START
get Grade
False
Grade
>= 60
True
display
display
“Sorry!”
“Congratulations!”
display
display
“You passed.”
“You failed.”
END
main()
{
double
dGrade;
scanf( “%lf”, &dGrade );
if ( dGrade >= 60 )
{
printf(
“Congratulations!”
);
printf( “You passed.” );
}
else
{
printf(
“Sorry.”
);
printf( “You failed.” );
}
}
If-else
statements
may be
nested (i.e., used inside another if-else statement).
44
Conditional
Statements
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.
START
display “Enter
the Grade:”
get Grade
Grade
False
>= 90
True
Grade
False
>= 80
L_grade = ‘A’
True
Grade
False
>= 70
L_grade = ‘B’
True
L_grade = ‘C’
L_grade = ‘D’
display
L_grade
END
45
Chapter
4
main()
{
double
dGrade;
char
cLGrade;
printf( “Enter the grade: “ );
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”, cLGrade );
}
An else is always paired with the nearest preceding unpaired if. Compare
the different diagrams to see the behavior of the various cases.
Case
1: The else at number 3 is paired with the if at number 2.
1.
if ( expression1 )
2.
if ( expression2 )
statement1;
False
expression1
3.
else
statement2;
True
False
expression2
True
statement1
statement2
46
Conditional
Statements
Case
2: The else at number 5 is paired with the if at number 1.
1.
if ( expression1 )
2. {
3.
if ( expression2 )
False
statement1;
expression1
4. }
5. else
statement2;
True
False
expression2
True
statement1
statement2
Case
3: The else at number 4 is paired with the if at number 1.
1. if
(
expression1
)
2. {
statement1;
False
3. }
expression1
4. else
5.
if ( expression2 )
statement2;
True
statement1
False
expression2
True
statement2
47
Chapter
4
Example. Draw a flowchart and write the corresponding
program that reads in three numbers A, B, and C and determines the largest
number.
START
display “Enter
3 numbers
get A, B, C
False
True
A > B
B > C
True
False
False
A > C
True
display “A
display “C
display “B
is largest”
is largest”
is largest”
END
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.” );
else
printf( “C is the largest.” );
48
Conditional
Statements
else if ( nB > nC )
printf( “B is the largest.” );
else printf( “C is the largest.” );
}
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.’
START
main()
{
double dGrade;
display “Enter
Grade”
printf( “Enter the grade: “ );
scanf( “%lf”, &dGrade );
if ( dGrade >= 0 && dGrade
<=100 )
get Grade
printf( “Grade is valid.” );
else
printf( “Grade is invalid.” );
}
Grade >= 0 &&
Grade <= 100
False
True
display
display
“Grade is
“Grade is
valid”
invalid”
END
49
Chapter
4
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.
Format:
switch ( expression )
{ case
label1 :
statement1; [break;]
:
:
case
labeln :
statementn; [break;]
[default : statement;]
}
where:
expression
an expression whose value is being
tested; only expressions that evaluate to character or integer types are
allowed
label
i
value that the expression is checked
against
statement i
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
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:
50
Conditional
Statements
False
expression
= label1
True
statement1
False
expression
= label2
True
statement2
False
expression
= labeln
True
statementn
statement
51
Chapter
4
The flowchart for a switch statement
that contains break statements look like this:
False
expression
= label1
True
statement1
False
expression
= label2
True
statement2
False
expression
= labeln
True
statementn
52
Conditional
Statements
The flowchart for a switch statement
that does not have a default statement looks like the following:
False
expression
= label1
True
statement1
False
expression
= label2
True
statement2
False
expression
= labeln
True
statementn
statement
53
Chapter
4
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 );
}
54
Conditional
Statements
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: “);
scanf(“%c”,
&Grade);
switch
(Grade)
{
case ‘A’ : printf(“V.Good!”); break;
case
‘B’
:
case ‘C’ : printf(“Good!”); break;
case ‘D’ : printf(“Fair!); break;
default : printf(“Poor!”);
}
}
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.”);
case ‘C’ : printf(“I will do
better!”);
case ‘A’ : printf(“I love COMPRO1”);
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
55
Chapter
4
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;
56
Conditional
Statements
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(“”);
if (nValue1 >= 0 &&
nValue1 <= 100)
if (nValue2 < 0 || nValue2 >
100)
printf(“One”);
else
printf(“Two”);
else if (nValue2 >= 0 &&
nValue2 <= 100)
printf(“One”);
else
printf(“Zero”);
}
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”,
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.
57
Chapter
4
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:
>=
94
4.0
>=
89
3.5
>=
83
3.0
>=
78
2.5
>=72
2.0
>=
66
1.5
>=
60
1.0
below
60
0.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 58
Conditional
Statements
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+”);
else if (X >= 70)
if
(X
>=80)
if
(X
>=
90)
printf(“A”);
else
if
(X
>=
85)
printf(“B+”);
else printf(“B”);
else
if
(X
>=
75)
printf(“C+”);
else printf(“C”);
else printf(“D”);
else printf(“You\u8217?re playing
hard to get!!!”);
}
59
Chapter
4
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”,x,y,z);
if (y == z) printf(“x%d”, y);
else if (y > z) printf(“z%d”,x);
else printf(“y%d”,z);
if (x > 10)
{
y = x * 2 - z;
if (y > 5)
{
printf(“xyz”);
printf(“”);
printf(“%d”, y);
x
=
x
+
y;
if (x < y) printf(“today”);
else
printf(“tomorrow”);
}
else
printf(“hi”);
z = z + 3;
}
else if ( x > y) printf(“%d”,x);
if (z == y)
{
z = 1; y = 2;
}
else if (x != y) z = z +2;
printf(“%d
%d
%d”,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”,
i
+
j);
else printf(“%d”, i - j);
printf(“%d”,
i);
}
60
Conditional
Statements
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 > 45
Bonus 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
service
Bonus
1
1%
of
salary
2 to 3
2% of salary
4 to 10
5% 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.
61
Chapter
4
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.
ex.
0000
12:00 a.m.
0900
9:00 a.m.
1200
12:00 p.m.
1430
2:30 p.m.
2359
11:59 a.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 P/3000.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?
62