Learning Outcome D.2 - TheSelection
Learning Outcome D.2 - TheSelection
(PPA115D/TRO115D)
Compiled by
V. Booi
and
V. Memani
1 Learning outcome: D.2. Implementing selection control structures in
programs
Selection control structures are used to select one set of instructions over others for
execution depending on the evaluation outcome of a condition statement. In this
chapter we are going to look in detail at specific types of selection control structures.
Create an application that greets only people who are above 18 years.
Solution
We will use our established problem solving approach. We will create an IPO chart,
followed by a flowchart and then implement the flowchart using code.
IPO chart
I P O
Age 1. Prompt for the user’s age greeting
2. Store age
3. Determine if age is greater than 18
4. Display a greeting if age is greater than 18
Flowchart
Start
age
FALSE TRUE
”Hello”
End
Solution
Open Notepad or Notepad++
Click on “File”, select “Open Containing Folder”, and then select cmd. The
command prompt will open in the directory where your file is saved.
Compile your application class by typing the following command: javac
AgeGreeter.java
Run your application class by typing the following command: java AgeGreeter
Alternatively
Step1
Open the command line
Step2
Compile AgeGreeter.java
Check again the contents of the folder.
Step 3
Run AgeGreeter class
1. Enter a value that is above 18.
Below are five tasks based on the if statement. For each task, create an IPO chart,
followed by a flowchart, then the actual code implementation of the flowchart.
Task #1
Create an application that will allow a student to enter an integer percentage mark
obtained in a test. If the mark is above 49, display the message “Passed”, otherwise
nothing.
Task #2
Create an application that will allow a user to enter a character representing the gender
of a person. If the user enters an ‘F’, the application must display the message “You
are female”, otherwise nothing.
Task #3
Create an application that will allow a computer to randomly generate either a 1 or 2.
A user must guess the number. If the guess is correct, display “You’ve won”,
otherwise display nothing.
Task #4
Create an application that will greet only females who are 18 and above.
Task #5
Mulumba is a numbers person. He loves working with numbers, and the patterns that
they present fascinate him. Now with his introduction to programming, his life of
numbers is made even more interesting. As a start, he wants to create an application
that will help him determine if a number is a palindrome. A palindrome is a number
that remains the same even when put in reverse. For example, 121 is a palindrome
because even when put in reverse, it remains the same. But 123 is not a palindrome
because when put in reverse, it becomes a totally different number, 321.
Since Mulumba is new into programming, he enlists your services. The program must
allow him to enter a 3-digit number and thereafter display the message “Palindrome”
if the number is indeed a palindrome.
The if…else statement is used when we have two sets of different instructions that we
want to execute depending on the outcome of the test condition. If the condition
evaluates to TRUE we execute one set, otherwise the other.
We can also use code format to represent the if…else statement as follows:
In both representations, we can see that the execution of the different instructions sets
is dependent upon the evaluation outcome of the condition. If the condition evaluates
to TRUE, block A statements are executed, otherwise block B statements are
executed.
Create an application that allows a user to enter an applicant’s APS. If the score is at
least 26, display “Admission granted”, otherwise “Admission refused”.
Solution
We will continue with our problem solving approach of creating an IPO chart, followed
by a flowchart, and then implementing the flowchart in a code.
IPO chart
I P O
aps 1. Prompt for the applicant’s aps. outcome
2. Store the aps.
3. Determine if the aps is greater than or less than 26.
4. Display an admission message if the aps is greater than or less than
26.
5. Display a declining message if the aps does not meet the condition.
Flowchart
Start
aps
”Admission refused”
TRUE
”Admission granted”
End
Program
Open Notepad or Notepad++
Edit the source code.
Alternatively
Step 1
Open the command line
Run AdmissionApp.class
1. Enter a value that is 26 or above.
2. Enter a value that is below 26.
Below are three tasks based on the if…else statement. For each task, you must create
an IPO chart, followed by a flowchart, then the actual code implementation.
Task #1
Create an application that will allow a student to enter an integer percentage mark
obtained in a test. If the mark is above 49, display “Passed”, otherwise “Failed”.
Task #2
Create an application that will allow a user to enter a character representing the gender
of a person. If the user enters an ‘F’, the application must display the message “You
are female”, otherwise “Male”.
Task #3
Create an application that will allow a computer to randomly generate either a 1 or 2.
A user must guess the number. If the guess is correct, display “You’ve won”,
otherwise “The computer has won”.
Task #4
Create an application that will greet only females who are 18 and above. If the
condition is met, the program must display “Hello”, otherwise it must display “Sorry”.
Task #5
Mulumba is a numbers person. He loves working with numbers, and the patterns that
they present fascinate him. Now with his introduction to programming, his life of
numbers is made even more interesting. As a start, he wants to create an application
that will help him determine if a number is a palindrome. A palindrome is a number
that remains the same even when put in reverse. For example, 121 is a palindrome
because even when put in reverse, it remains the same. But 123 is not a palindrome
because when put in reverse, it becomes a totally different number, 321.
Since Mulumba is new into programming, he enlists your services. The program must
allow him to enter a 3-digit number and thereafter display the message “Palindrome”
if the number is indeed a palindrome. If it is not, program must display “Not
palindrome”.
1.3 The if..else if…else statement
The if…else if …else statement is used to test multiple conditions. When a condition
is met or satisfied, the set of instructions applicable to that condition is executed,
otherwise the next condition is tested. The last set of instructions is set aside as
default, when all others have failed.
Figure 5 below shows the flowchart representation the if…else if …else statement.
Create an application that classifies a person according to their age according to the
table below.
Age Description
1 – 14 Child
15 – 35 Youth
36 – 64 Adult
65+ Elderly
Solution
We will continue with our problem solving approach of creating an IPO chart, followed
by a flowchart, and then implementing the flowchart in a code.
IPO chart
I P O
Age 1. Prompt for the user’s age. message
2. Store age.
3. Determine the description of the person based on their
age.
4. Display appropriate message.
Flowchart
Start
”Please enter your age:”
age
”Elderly”
FALSE
”Adult”
FALSE
”Youth”
FALSE
”Child”
End
Program
Open Notepad or Notepad++
Alternatively
Step1
Open the command line
Step 3
Run PersonClassifier.class
1. Enter -1
2. Enter 12
3. Enter 30
4. Enter 50
5. Enter 70
We have four tasks for you based on the if…else if…else statement. For each task,
create an IPO chart, followed by a flowchart, then the actual code implementation of
the flowchart.
Task #1
Create an application that will allow a student to enter an integer percentage mark
obtained in a test. Display the message “Failed” if the mark is below 50, “Passed” if
the mark is between 50 and 74, both values inclusive, and “Passed with distinction”
if the mark is above 74.
Task #2
Create an application that will allow a user to enter a character representing their
gender. If the user enters an ‘F’, the application must display the message “You are
female”, if an “M”, display “You are male”, otherwise display “Please enter either
an M or F”.
Task #3
People from old school are used to standards, not grades. Create an application that
will convert grades into standards for the convenience of the older generation. If a user
enters a grade, an equivalent standard must be determined and displayed. Use table
2 below to successfully complete the task.
Grade Standard
3 1
4 2
5 3
6 4
7 5
8 6
9 7
10 8
11 9
12 10
Task #4
Thato is running a dry cleaning business in Sosh. Her business is offering the following
services to customers:
Wash Only.
Wash and Dry.
Wash, Dry and Iron.
Thato needs an application that will help her run the business. First the application
must display a service menu as shown in table 1. The application must allow Thato to
enter the service code corresponding to the service requested by a customer. A
service code that equals to ‘Z’ or ‘z’ must end the program.
If the user enters an invalid service code (not equal to O/o, D/d or I/i or Z/z), the
application must display an error message and thereafter come to an end. If a valid
service code is entered, the user must be allowed to enter the weight of the clothes in
kilograms and thereafter determine and display the amount due.
After displaying the amount due, the application must allow user to enter the payment
amount made by the user. If the payment amount is insufficient, an error message
must be displayed and the program should come to an end. If sufficient amount is
provide, change must be determined and displayed before the program comes to an
end.
The literal meaning of the term nested is “to be found inside something”.
Consequently, nested if statements are if statements that are found inside other if
statements, we are nesting if statements. We use nested if statements when we have
a set of instructions whose execution is dependent upon a set of conditions evaluating
to TRUE.
From the two representations we can see that condition 1 is tested first, if it evaluates
to TRUE, condition 2 is then tested. If condition 2 evaluates to a TRUE, the set of
instructions id executed. The first if statement is the main one and the second is the
nested if statement.
Nested if statements simply have the main parent if statement with children statements
that have sub-children. So you have a nest of if statements.
Nested if statements can also be written using one if statement containing a list of all
the conditions. The list of conditions form what is called compound conditions.
Let’s take an example to show how to use nested if statements and compound
statements.
Solution
In the next pages, we are going to provide two solutions, one using nested if
statements and the other using one if statement with compound conditions. We will
continue with our problem solving approach of creating an IPO chart, followed by a
flowchart and then code implementation of the design.
IPO chart
I P O
gender 1. Prompt for user’s gender. outcome
age 2. Store gender.
3. Prompt for user’s age.
4. Store age.
5. Display bursary outcome based on the user’s
gender and age.
Flowchart
Start
gender
age
studyField
Is gender == ’F’?
FALSE ||
gender ==’f’?
TRUE
TRUE
Is studyField
FALSE
==”ICT”?
TRUE
End
Program
Open Notepad or Notepad++
Edit the source code.
Step 1
Open the command line
Step 2
Compile BursaryManagerApp.java
Check again the contents of the folder.
Step 3
Run BursaryManagerApp.class
1. Enter data that will disqualify the applicant
Start
gender
age
studyField
Program
Open Notepad or Notepad++
Step1
Open the command line
Step 2
Compile BursaryManagerApp2.java
Check again the contents of the folder.
Step 3
Run BursaryManagerApp2.class
1. Enter data that will disqualify the applicant
Task #1
Soccer team ABC wants to start a new division of under 15 male players. The players
must be between the ages of 10 and 14, both values inclusive. They must weigh
between 25 and 45 kilograms, both values inclusive, and have a height between 1 and
1.5 meters, again both values inclusive. Create an application that will allow
prospective players to check if they qualify to become part of the team or not.
Task #2
2024 is national government elections in South African. Parties are expected to
register their candidates with the IEC (Independent Electoral Commission). The IEC
requires parties to submit their lists of candidates meeting the following basic
requirements:
Candidates must be South African.
Candidates must be 18 years or older.
Create an application that will allow parties to see if their prospective candidates meet
the IEC requirements.
Task #3
In the past two years the world was under attack by COVID-19. The pandemic
drastically changed the way people led their lives. Suddenly people were expected to
wear face masks in public, sanitise their hands and practice social distancing. Entry to
public institutions such as schools also required people to have their temperatures
checked. Temperatures above 38 degrees Celsius resulted in people being refused
entry into public buildings and advised to seek medical help.
Though the pandemic has immensely subsided, and as a result regulations have been
done away with, some private institutions still require people to observe the COVID-
19 prevention protocols. People are expected to wear their face masks, hands are
sanitised and temperatures are taken.
Create an application for private institution XYZ that will allow access into the premises
of XYZ if a person is wearing a face mask, is willing to sanitise hands, and is having a
temperature value not more than 38 degrees Celsius. If a person is not meeting these
requirements, access must be denied. The reason for denying access must be clearly
spelt out.
Using = instead of ==
If (mark = 50) this will results in a syntax error as an integer cannot
be converted to Boolean
Message = “You have passed”;
The switch statement works the same way as the if…else if …else statement.
The only difference is that a switch statement cannot be used to test decimal and string
values. It only works with numeral values in the form of characters and integers. So
when decisions have to be made based on numerical values, the switch statement
can be used. Again another condition for usage of switch statement is that the
numerical values must not be about ranges, they must just be exact values.
The switch statements works the same as the if…else if…else statement. A numerical
value is compared against each case. If a match is found, the matching case is
executed and the statement comes to end. If none of the statements match the
numerical value, code under the default statement is executed.
Create an application that will determine and display the marital status of a person
given the marital code. Table 1 below shows codes with corresponding description.
Code Description
S or s Single
M or m Married
D or d Divorced
IPO chart
I P O
maritalCode 1. Prompt for user’s marital code. status
2. Store maritalCode.
3. Determine marital status.
4. Display status.
Flowchart Start
maritalCode
End
Program
Open Notepad or Notepad++
Edit the source code.
Step1
Open the command line
Step 2
Compile MaritalStatusApp.java
Check again the contents of the folder.
Step 3
Run MaritalStatusApp.class
1. Enter invalid code
Task #1
Create an application that will allow a user to enter a character representing the gender
of a person. If the user enters an ‘F’ or ‘f’, the application must display the message
“You are female”, if an “M” or ‘m’, the application must display “You are male”,
otherwise “Please enter either an M/m or F/f”.
Task #2
There are 26 letters in the English alphabet. The letters are divided into vowels and
consonants. The letters a, e, i, o and u are called vowels, and the rest are
consonants. Create an application that will determine whether a given letter is a vowel
or consonant. Display appropriate messages.
Task #3
Muvhango runs a small Fruits and Vegetables sphaza shop. She sells oranges,
bananas, apples, spinach and potatoes. Table 2 below shows the pricelist of her items.
a apples 1.50
b bananas 2.00
o oranges 2.50
p potatoes 6.00
s spinach 10.00
1.6 Conclusion
In the next chapter we are going to look at control structures, the structures that
determine the flow of our programs. Thank you very much for having taken time to go
through this chapter. Enjoy the rest of the day and God bless you.