Week 6-8 Ccc112-18 Selection Control Structures

You might also like

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

New Era University

College of Computer Studies


Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

Week 6-8

SELECTION CONTROL STRUCTURES

This module is composed of different conditional statements which is a feature of a


programming language specifically in Java which have the ability to make decisions. This
module will help you on how to program simple and complex decisions.

Learning Outcomes:
At the end of the module, the student should be able to:
1. Identify and apply different relational operators;
2. Use if statement when setting a condition;
3. Understand how if-else statement works;
4. Set a nested if on multiple conditions;
5. Combine logical operators on a condition;
6. How to use switch/case statement on multi-value variable;
7. Simulate given program and determine its output.
8. Design a program that implement different selection structures

Relational Operators
Every condition contains two values to compare. The comparison less than (<) or
greater than (>) is called relational operators. Java programming contains the following
relational operators. Let’s assume that a=5, b=1, c=3:
OPERATORS DESCRIPTION EXAMPLE RESULT
< Less than (c<a) true
> Greater than (a>b) true
<= Less than or equal (c<=3) true
>= Greater than or equal (b>=1) true
== Equality (a==5) true
!= Not equal (b!=c) true

In our previous discussion, the = operator means, assignment operator. While the
== operator denotes equality testing. For additional example, in 6==4+2 results to true
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

because we are comparing 6 to (4+2=6). For the not equal, the expression 6!=4+2 results
to false because if we compare it, 6 is the same with the (4+2) sum value.
The if Statement
The if statement execute only once the condition is true. The syntax and the
equivalent flowchart underneath is the if statement.

Syntax: Flowchart:

As you notice in syntax and flowchart the condition which must enclosed with
parenthesis, is evaluated first before executing statements. The multiple statements inside
the statement block will only be executed when the condition is true.

Consider the given code below:

1. The program above has initialized the value of num into 143.
2. The next line validates the condition. We have used if statement to test the
equality and since the value of num and the value 143 is the same, the condition
is true. Thus, it will print the string “I love you”.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

3. The last line will be executed and display the “End of Program” even the
condition is false.
Here is the output of the above program:

Let’s try the condition result is false with the program below:

1. The program above have the initial value 7 to num1 and 3 to num2.
2. We used again the if statement to test the condition num1 is less than num2.
As you have noticed, the value of num1 which is 7 is greater than the value of
num2 which is 3. Thus, the result of the condition is false. That’s why, the if
statement simply by-passed the two statements inside the curly braces and
proceed to the next line outside the statement block.
3. The line will execute and print the “End of Program” and the output is:

The if – else Statement


This is an extended version of the if statement. However, this if-else statement has
two choices. The syntax and flowchart of the if-else are as follows:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

Syntax: Flowchart:

The concept of this if-else statement is the same with the if statement. If the
condition is true, the statement block for true will be executed. However, if the condition
is not satisfied or the condition is false, the program will branch immediately to else
statement which is the statement block for false. Note that, statements under the else
should also enclosed with curly braces to show the block of statements to be executed
when the condition is set to false.

The following program will illustrate the use of if-else statement called Age:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

1. This line of statements shows the declaration of different identifiers used in this
program. This program will display and accept a user input which is the integer
age. Let’s assume that age input is 27.

2. As we mention on number 1, we entered the new value of age as 27. This line
will test our condition. As you noticed, 27 is greater than or equal 18, thus, the
expression satisfies the condition and resulted to true. Then, it will display the
“Qualified to vote” statement.
3. This line will not be executed because, again, the condition was resulted to true.
And the result is as follows:

However, if the value of age is less than 18, the result will looks like this:

Let’s have another working example that test if input is a positive or negative
number:

1. The statements in number 1 shows the declaration of identifiers such as input


which is the object name of our Scanner, variable declaration which is the number
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

that initialized to zero, Displaying and accepting the value of number. Let’s assume
that input number is -10.

2. The following statements shows the condition of the program. Since the input value
is -10, it will not satisfy the condition because -10 is less than zero. That’s why
number 3 will takes place.
3. From our previous examples, if the condition is resulted to false, the else statement
which is the statement block of false will be executed. Obviously, the output is:

However, if the input value is greater than zero, the output will looks like this:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

Let’s try to simulate and determine the output of the given code below:

int a=5, b=2, c=4, r=0; //Line 1


if(a>3) //Line 2
{ //Line 3
if(b<=a) //Line 4
{ //Line 5
r=b++ - --a + c--; //Line 6
if(r%2==0) //Line 7
{ //Line 8
r++; //Line 9
c++; //Line 10
} //Line 11
else //Line 12
{ //Line 13
--r; //Line 14
b+=c++; //Line 15
} //Line 16
} //Line 17
System.out.println("The value of r="+ ++r); //Line 18
} //Line 19
System.out.println("The value of r=" + r); //Line 20
System.out.println("The value of c=" + c); //Line 21
System.out.println("The value of b=" + b); //Line 22

The program code above is a combination of an if and if-else statements. To identify


the result, you should know how to read other programs. This will help programmers to
decode what the other programmers approach in solving the problem.
In reading and simulating a program, we should identify the statement blocks.
Based on the line numbers, Line 2 up to Line 19, it shows that these line of statements are
included in the outer if condition (a>3). Note that you will only evaluate the inner statements
if the condition (a>3) is true. Next are the Line 4 up to Line 17, this line can only be
evaluated once the condition of (b<=a) turns to true. Now, we already identified the
statement blocks. Let’s start.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

Line 1 are the declaration of our identifiers/variables. Line 2 sets the condition (a>3).
This represents the (5>3) and it turns out true result. This means all statements under this
condition may be evaluated. Next line is the inner condition, (b<=a) or (2<=5) result is true.
This will open the statement block from line 5 to line 17. As you have notice, the equation
r=b++ - --a + c--; was set. The present value of b=2, c=4 and a=5. We will add 1 to
b and decrease by 1 to c after we identify the value of r, while the a should be decrease
by 1 before evaluating the entire expression. This would be evaluated like this r=2 – 4 + 4
resulted to r=2, b=3, a=4, c=3.
We know already the value of r which is 2 that will be used in the another inner
condition (r%2==0). The result of this condition is true because, 2 modulus to 2 resulted
to zero, and satisfy the condition if(0==0). This means that we can now evaluate the
statements under this condition. The present value of r (r++) will become 3 and c (c++)
will become 4. The compiler will no longer execute the else because condition is already
satisfied.
After the execution of line 7 to 11, the program will proceed to line 18 which is to
display the value of r. Note that the present value of r=3 then before it will display, the r
will increment by one resulted to 4 as the new value.
Line 20-22 will print all present value of r, c, b. The result looks like this:

Here is simulation on how we get the result (t represent true in the condition lines):

Accumulator/counter: Output:
a b c r
t5 t2 4 0 The value of r=4
4 3 3 t2 The value of r=4
4 3 The value of c=4
4 The value of b=3
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

The if–else if-else Statement


This statement is useful when your program is to check multiple condition.
Syntax:

Flowchart:

This structure is also known as the nested else-if statement, which the condition
will be evaluated from the top. The first condition that evaluated as true will be the first
statements to be executed even if the condition is at the very least part of the program.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

The previous program tells if the input number is Positive or Negative. The next
program will identify if the user entered zero.
This is the modified program:

1. The statements in number 1 shows the declaration of identifiers such as input


which is the object name of our Scanner, variable declaration which is the number
that initialized to zero, Displaying and accepting the value of number;
2. The following statements shows the first condition of the program. Since the input
value is 0, it will not satisfy the condition because 0 is not greater than zero and it
turns out false. That’s why it will proceed to the next condition;
3. The second condition number is less than zero turns out false also because it will
not satisfy the condition.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

4. This process will continue until it reach all conditions. If all conditions turns out false,
it will proceed to else and executes all statement under the else. It will also print
the last statement outside the conditions. See the output below:

Implementing Logical Operators

Logical operators are used to identify the logic of two or more condition before
executing a given statement. The different logical operators used by Java are as follows:
1. Logical AND
This operator returns true if both conditions are true. We used double
ampersand (&&) to represent logical AND operator. The table shows the exact
result of the given conditions using logical AND operator.
CONDITION 1 CONDITION2 RESULT
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE FALSE

2. Logical OR
This operator turns entire condition to true if one of the condition is true. We
used double pipe (||) to represent logical OR operator. The table shows the
exact result of the logical OR operator.
CONDITION 1 CONDITION2 RESULT
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

3. Logical NOT
This operator returns the value in reverse result. It will return true if the result
is false. Logical NOT used (!) symbol.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

CONDITION RESULT
TRUE FALSE
FALSE TRUE

Let’s consider the following code and assume the input value of test1score=85 and
test2score=81:

package JavaActivity;
import java.util.Scanner;
public class EmployeeTest
{
public static void main (String[] args)
{
Scanner input=new Scanner (System.in);
int test1score=0, test2score=0;
System.out.println("Enter test 1 score: ");//input number 85
test1score =input.nextInt();
System.out.println("Enter test 2 score: ");//input number 81
test2score =input.nextInt();

if((test1score>90)&&(test2score>90))
{
System.out.println("Make employee manager"); 1
}

else if((test1score>90)||(test2score>90))
{ 2
System.out.println("Make employee supervisor");
}

else if(!(test1score>90))
{
System.out.println("Make employee agent"); 3
}
}
}

1. The condition of this line will be evaluated first. Since the value of test1score is 85
and 85 is less than 90 the result of the first condition turns out to false AND
test2score value is 81 and obviously result is also false. Based on our table, false
AND false conditions resulted to FALSE of the entire condition. The compiler will
move to the next condition to test.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

2. This line turns out to FALSE the entire condition because 85(test1score) is less
than 90 OR even the 81(test2Score) is less than 90. So, this line will not evaluate
the statements.
3. The compiler will move again to the next available condition. Since this line satisfies
the condition, which is the reverse of the result FALSE in 85 (test1score) is greater
than 90 that resulted to entire condition TRUE. The output of the program is :

The switch/case Statement


An alternative conditional statement that will be used when executing series of
statements or when you have number of choices that needs to perform task if the condition
is true.
The syntax of switch statements is as follows:
intVarName>;
switch(<intVarName>)
{
case <first value of intVarName>:
<statement 1>;
<statement 2>;
<statement n>;
break;
case < n value of intVarName> :
<statement 1>;
<statement 2>;
<statement n>;
break;

default: <statement 1>:


<statement 2>;
<statement n>;
break;
}

The switch/case statement works only on integer and character data type; the use of it in
float, double data type is not allowed. It is mostly used with break statement.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

Here’s the simple switch/case example: Design java program AirFare that imposes
a discount fare to student and senior citizen on an airline company. Student gets 10%
discount; senior citizen gets 20%; ordinary customer gets no discount.

Sample Input/Output:
Enter fare amount: 100.00
Enter customer code [0=Ordinary, 1=Student, 2=Senior] : 1
Customer is student
Discount is 10.00 dollars

Net Fare is 90.00 dollars

Before we write our program, let’s identify first the variables that we’re able to use
with this program:
Expected Value Variable Name Description Data type
100.00 fare Air fare double
0,1,2 custCode Customer Code int
student customer Customer String
10% discRate Discount Rate double
90.00 netFare Net Fare double
10.00 discount Discount double

Let’s start our program by importing packages such as DecimalFormat and


Scanner class.

1. This part are the declaration of our identifiers/variables. The fare declared as
double because it handles entry with decimal value, discRate, netFare, and
discount are also declared as double with initial value of 0.0. While custCode is
also declared as integer value because based on our problem, it handles 0,1,2
which is considered as whole number and this will be used to test on our
switch/case statement. And the customer variable set as String that handles the
string Ordinary, Student, and Senior with initial value of null.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

2. The statements in this lines will display and accept the amount to be entered and
store it in fare variable. Also, it will display the “Enter customer code 0=Ordinary,
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

1=Student, 2=Senior”. Once the user decided what customer code and type in, it
will store in custCode. This will be used by the switch/case to choose.
3. Based on the input value of custCode, the program will display Ordinary, Student,
and Senior which also imposes a discount of 0% for ordinary, 10% for student and
20% for senior. Within the switch/case, if the custCode value is 0, customer
variable is set to “Ordinary” with discRate (Discount rate) of 0.0 or no discount. If
the custCode value is 1, customer variable is set to “Student” with discRate
(Discount rate) of 0.1. Lastly, if the custCode value is 2, customer variable is set
to “Senior” with discRate (Discount rate) of 0.2. However, if the user input is not on
the case, it will proceed to default and print the text “Invalid code”. As you have
noticed, every case contain a break statement that terminates the switch. In
absence of the break statement, it continuously read the case in your switch until it
reach the default statement.
4. This part are the computations of discount by getting the product of fare and
discRate. And also, for the netFare, we get it by deducting the value of fare to
discount. This part also displays the necessary output with 2 decimal formats. Take
a look at this output:

What about if a user wants a character to be entered instead of number as a


customer code:
Sample Input/Output:
Enter fare amount: 100.00
Enter customer code [O=Ordinary, S=Student, R=Senior] : r
Customer is student
Discount is 20.00 dollars

Net Fare is 80.00 dollars


New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

With the same set of code, just change in the declaration of variables the custCode
data type from int to char.
char custCode;
To accept character in our program, just revise the code from
custCode=input.nextInt(); to:
custCode=input.next().charAt(0);
All inputs from keyboard considered as String. To read a character in a program, the next()
method returns the next word in the input as String and charAt(0) method returns the first
character in the text. For example, if your input text is Java, the j character is at position
0. If you use charAt(1), returning character is a. However, there is a possibility that the
user will enter a lower case letter. The code below will convert the lower case character to
upper case format.
custCode=Character.toUpperCase(custCode);
Lastly, in our switch statement, change all integer in case into desired character
then enclosed it with single quote.
switch(custCode)
{
case 'O': customer= "ordinary";
discRate=0.0;
break;
case 'S': customer="student";
discRate=0.1;
break;
case 'R': customer="senior citizen";
discRate=0.2;
break;
default:
customer="Invalid code";
}
Here are the output and complete program code in accepting character:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

package JavaActivity;
import java.util.Scanner;
import java.text.DecimalFormat;
public class AirFare2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("###,###.00");
//Declare input variables
double fare=0.0;
char custCode;
String customer="";
double discRate=0.0;
double netFare=0.0, discount=0.0;
// Accepts the inputs of the program
System.out.print("Enter fare amount: ");
fare=input.nextDouble();
System.out.print("Enter customer"+
"code [O=Ordinary, S=Student, R=Senior]: ");
custCode=input.next().charAt(0);
custCode=Character.toUpperCase(custCode);
switch(custCode)
{
case 'O': customer= "ordinary";
discRate=0.0;
break;
case 'S': customer="student";
discRate=0.1;
break;
case 'R': customer="senior citizen";
discRate=0.2;
break;
default:
customer="Invalid code";
}
//Compute discount and net fare
discount=fare*discRate;
netFare=fare-discount;
System.out.println("\nCustomer is " + customer);
System.out.println("Discount is " + df.format(discount) + " dollars");
System.out.println("\nNet fare is " + df.format(netFare) + " dollars");
}
}
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: computerstudies@neu.edu.ph

References:
C. S. Horstmann, Brief Java: Early Objects, Enhanced, 9th Edition, Wiley Global
Education US, 2019

C. S. Horstmann, Big Java: Early Objects, Enhanced, Interactive Edition, Wiley Global
Education US, 2015

https://press.rebus.community/programmingfundamentals/chapter/selection-control-
structures/

https://www.guru99.com/c-if-else-statement.html
https://www.w3schools.com/java/java_operators.asp
https://tutorialspoint.dev/language/java/gfact-51-java-scanner-nextchar

You might also like