You are on page 1of 44

Week 4

Selection Control
Structures

STIA1014 : Introduction To
Programming

Lecture Outlines

Creating Condition
Describing Relational Operators
Describing Logical Operators
Describing Order of Precedence
Describing Logical Expressions
Implementing if Statements
Implementing Nested if Statements
Implementing Multiple Selections (ifelse
and switchcase)

Learning Objectives
To implement a selection control using if
statements
To implement a selection control using switch
statements
To write boolean expressions using relational
and boolean expressions
To evaluate given boolean expressions
correctly
To nest an if statement inside another if
statement

Control Structures
All programming languages have statements that
allow you to make decisions to determine what to do
next.
A computer can process a program in one of three
ways:Sequence
Follows the statements in order.

Branching/Selection
Altering the flow of program execution by making a
selection or choice
Depending on certain condition (s)

Looping/Iteration/Repetition
Altering the flow of program execution by repeating
particular statements in certain number of times
depending on certain condition (s)

Control Structures Flow


of Execution/control
The order in which statements are executed in a running
program is called the flow of control

Relational Operator
To make decisions, you must be able to
express conditions and make comparisons.
Relational operator:
Allows you to make comparisons in a program
Binary operator

Condition is represented by logical/boolean


expression in Java
Logical expression: An expression that has a
value of either true or false (or logical values)

Java Equality and


Relational Operators
Operators that allow you to make comparisons in a
program.

Java Logical Operators


Operators that enable you to combine logical expressions
Take only logical values as operands
Produce Boolean results

Truth Table (!(not)


Operator)
A logical expression can be described by a truth table that
list all possible combinations of values for the variables
involved in the expression.
Reverse the value of logical expression.

Truth Table (&&(and)


Operator)
Is true if and only both expressions are true, otherwise it
is false.

Truth Table (||(or)


Operator)
Is true if and only if at least one of the expression is true,
otherwise it is false.

Precedence Order of
Operators

Selection
Two types of selection
if statements
One-way selection
Two-way selection
Multiple selections
Nested-if statement

switch statement

One-way Selection
Syntax:
if (boolean expression)
statement for true case

Expression referred to as decision maker.


Statement referred to as action statement.

One-way Selection
Output:
double y=15.0;
Result : y !=x
double x=25.0;
if (y!=x)
System.out.println("Result : y!=x");

if (testScore >= 95)


System.out.println("You are an honor student");

Two-way Selection
Syntax:
if (boolean expression)
statement(s) for true case
else
statement(s) for false case

else statement must be paired with an if.


must choose between two alternatives.

Two-way Selection
Scanner input=new Scanner(System.in);
System.out.print ("Enter the number : ");
int number = input.nextInt();
if (number>=1)
System.out.println ("You enter the positive
number");
else
System.out.println ("You enter the negative
number");

Two-way Selection
OUTPUT #1:
Enterthenumber:10
Youenterthenegativenumber
OUTPUT #2:
Enterthenumber:10
Youenterthepositivenumber

Two-way Selection
int testScore;
testScore = //get test score input
if (testScore < 70)
System.out.println("You did not pass" );

This
Thisstatement
statementisis
executed
executedififthe
thetestScore
testScore
isisless
than
70.
less than 70.

else
System.out.println("You did pass" );

This
Thisstatement
statementisis
executed
executedififthe
thetestScore
testScore
isis70
or
higher.
70 or higher.

Compound (block of)


Statement
Use braces if the <then> or <else> block has multiple
statements.
Syntax:
if ( <boolean expression> ) {
statement1
statement2
.
statementn
}

if ( <boolean expression> ) {
statement1
statement2
.
statementn
}
else {
statement1
statement2
.
statementn
}

Compound (block of)


Statement
int a = 7;
if (a>=1){
System.out.println
System.out.println
}
else{
System.out.println
System.out.println
}

("The number you enter is :" + a);


("You enter the positive number");
("The number you enter is :" + a);
("You enter the negative number");

Compound (block of)


Statement
Output #1
Enterthenumber:12
Thenumberyouenteris:12
Youenterthepositive
number

Output #2
Enterthenumber:12
Thenumberyouenteris:
12

Multiple Selection
Syntax:
if (boolean expression1)
statement1
else if (boolean expression2)
statement2
.
.
else
statementN

Multiple Selection
if (a>=1)
{
System.out.println
System.out.println
}
else if (a<0)
{
System.out.println
System.out.println
}
else if (a==0)
{
System.out.println
System.out.println
}

("The number you enter is :" + a);


("You enter the positive number");

("The number you enter is :" + a);


("You enter the negative number");

("The number you enter is :" + a);


("You enter the zero number");

Multiple Selection
Output #1
Enterthenumber:15
Thenumberyouenteris:15
Youenterthepositivenumber
Output #2
Enterthenumber:15
Thenumberyouenteris:15
Youenterthenegativenumber
Output #3
Enterthenumber:0
Thenumberyouenteris:0
Youenterthezeronumber

Multiple Selection
if (score >= 90)
System.out.print("Your grade is A");

TestScore

Grade

90 score

80 score 90

B
C
D

70 score 80
60 score 70
score 60

else if (score >= 80)


System.out.print("Your grade is B");
else if (score >= 70)
System.out.print("Your grade is C");
else if (score >= 60)
System.out.print("Your grade is D");
else
System.out.print("Your grade is F");

Equivalent code with


series of if statements
if ((mark >= 90) && (mark <=100))
grade = A;
if ((mark >= 80) && (mark >= 89))
grade = B;
if ((mark >= 70) && (mark >= 79))
grade = C;
if ((mark >= 60) && (mark >= 69))
grade = D;
if ((mark >= 0) && (mark >= 59))
grade = F;

The Nested-if Statement


The then and else block of an if statement can
contain any valid statements, including other if
statements. An if statement containing another if
statement is called a nested-if statement.
if (testScore >= 70) {
if (studentAge < 10) {
System.out.println("You did a great job");
} else {
System.out.println("You did pass"); //test score >=
70
}
//and age >= 10
} else { //test score < 70
System.out.println("You did not pass");
}

Writing a Proper if Control


if (num1 < 0)
if (num2 < 0)
if (num3 < 0)
negativeCount
else
negativeCount
else
if (num3 < 0)
negativeCount
else
negativeCount
else
if (num2 < 0)
if (num3 < 0)
negativeCount
else
negativeCount
else
if (num3 < 0)
negativeCount
else
negativeCount

negativeCount = 0;
= 3;
= 2;

= 2;
= 1;

if (num1 < 0)
negativeCount++;
if (num2 < 0)
negativeCount++;
if (num3 < 0)
negativeCount++;

= 2;
= 1;

= 1;
= 0;

The
Thestatement
statement
negativeCount++;
negativeCount++;
increments
incrementsthe
thevariable
variableby
byone
one

Matching Else
Are

A
B different?
A and B
A
A

if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");

B
B

if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");

Both

A
B means
A and B

if (x < y) {
if (x < z) {
System.out.print("Hello");
} else {
System.out.print("Good
bye");
}
}

Matching Else
Are

A
B different?
A and B
A
A

if (x < y){
if (x < z)
System.out.print("Hello");
}
else
System.out.print("Good bye");

B
B

if (x < y)
if (x < z)
System.out.print("Hello");
else
System.out.print("Good bye");

switchStructure
switch (expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
}

Expression must
yield a value of
char, byte, short or
int type.
Expression can be
an identifier.
Value can only be
integral (char,byte,
short or int).

switchStructure

switchStructure
switch (grade)
{
case 'A': System.out.println("The
break;
case 'B': System.out.println("The
break;
case 'C': System.out.println("The
break;
case 'D': System.out.println("The
break;
case 'F': System.out.println("The
break;
default: System.out.println("The
}

grade is A.");
grade is B.");
grade is C.");
grade is D.");
grade is F.");
grade is invalid.");

switchStructure
switch(num)
{
case 0:System.out.println("The number you entered
break;
case 1:System.out.println("The number you entered
break;
case 2:System.out.println("The number you entered
break;
case 3:System.out.println("The number you entered
break;
case 4:System.out.println("The number you entered
break;
case 5:System.out.println("The number you entered
break;
default:System.out.println("Your choice is not in
}

is 0");
is 1");
is 2");
is 3");
is 4");
is 5" );
the list");

switchStructure
Output #1
Enteranintegerbetween0and5:0
Thenumberyouenteredis0

Output #2
Enteranintegerbetween0and5:1
Thenumberyouenteredis1
Output #3
Enteranintegerbetween0and5:5
Thenumberyouenteredis5

Output #4
Enteranintegerbetween0and5:6
Yourchoiceisnotinthelist

switchStructure
switch (ranking) {
case 10:
case 9:
case 8: System.out.print("Master");
break;
case
case

7:
6: System.out.print("Journeyman");
break;

case
case

5:
4: System.out.print("Apprentice");
break;

default: System.out.print("Input error: Invalid Data");


break;
}

breakbreak
Statement
Statement
Used to skip remainder of switch
structure
If NO break statement is specified,
statements in the remaining cases will
be executed also.
Can be placed within if statement of a
loop
If condition is met, the flow of control
immediately exit the loop
Used to exit early from a loop

Control flow of switch statement with


and without the break statements

defaultcase
You may include a default case that will
always be executed if there is no matching
case (to allow defensive programming).
There can be at most ONE default case.
If NO default case is specified, the execution
continues to the next statement after the
switch structure/block.

Exercise #1
Identify the syntax error in the following
statement:
if (x > 25.0)
{
y = x - 25.0;
else
y = x;
}

Exercise #2
What value is assigned to fee by the nested if
statement on the left and right when speed is 75?
Which is correct?
if (speed > 35)
fee = 20.00;
else
if (speed > 50)
fee = 40.00;
else
if (speed > 75)
fee = 60.00;

if (speed > 75)


fee = 60.00;
else
if (speed > 50)
fee = 40.00;
else
if (speed > 35)
fee = 20.00;

Exercise #3
What output is displayed by the following

statements when grade is F? When grade is


B? When grade is a?
switch (grade){
case A: points = 4; break;
case B: points = 3; break;
case C: points = 2; break;
case D: points = 1; break;
case E: case F:
points = 0; break;
default: System.out.println (Bad Grade);
}//end switch
if ((A <=grade) && (grade<=D))
System.out.println(Passed, points earned = + points);
else
System.out.println(Failed, no points earned);

Conclusion
Q & A Session

You might also like