0% found this document useful (0 votes)
4 views

Topic 4 - Control - Structures-Selection

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Topic 4 - Control - Structures-Selection

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Topic 4

CONTROL
STRUCTURE
S
Selection

1
1. To learn how to
use the selection
control structure.
2. To understand
OBJECTIVE
S
various selection
structures.
3. To improve
algorithm design
skills.
3 TYPES FLOW OF
CONTROL
Sequential (we had learned in previous
topic)
• The statements in a program are executed in
sequential order

Selection
• allow the program to select one of multiple paths
of execution.
• The path is selected based on some conditional
criteria (boolean expression).

Repetition (we will learn in next topic)


FLOW OF
CONTROL
:
SEQUENTI
AL
STRUCTU
RES
FLOW
OF
CONTRO
L:
SELECTI
If the Boolean expression
ON evaluates to true, the
statement will be executed.
Otherwise, it will be
skipped.
EXAMPLE OF SELECTION IN
COMPUTER PROGRAM
MAX LOAD: 250 kg

Conditions

If do not
If exceed 250:
exceed 250:
Give warning with
Close the door and
BEEP sound
go up/down

Actions
FLOW OF There are 3 types
CONTRO of Java selection
L: structures:
SELECTI o if statement
ON o if-else statement
STRUCTU o switch statement
RES
THE IF STATEMENT

The if statement has the following syntax:


The condition must be a
Boolean expression. It must
evaluate to either true or
if is a Java
false.
reserved word

if ( condition )
statement;

If the condition is true, the statement is executed.


If it is false, the statement is skipped.
8
BOOLEAN EXPRESSIONS

A condition often uses one of Java's equality


operators or relational operators, which all
return Boolean results:

== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to

9
EXAMPLES OF BOOLEAN
EXPRESSIONS
Boolean Descriptions
Expressions
testScore < 80 returns TRUE if testScore is less than 80
a == b returns TRUE if a equals to b
numb1 != numb2 returns TRUE if numb1 not equal to
numb2
testScore * 2 > 350 returns TRUE if testScore * 2 is greater
than 350
w * (h*h) < 30 returns TRUE if w*(h*h) is less than 30
a * a <=c returns TRUE if a*a is less than or equal
to c

1
0
LOGIC OF AN IF
STATEMENT

false false
condition testScore < 40?
evaluated

true true

statement System.out.println (“You failed”);

if (testScore<40)
System.out.println(“You failed”);
THE IF STATEMENT
The condition is
evaluated first: Executed when if
is testScore less than statement is true,
40? if no, it is skipped

double testScore = 38.5;

if (testScore < 40)


System.out.println("You failed");
System.out.println("Next semester will start on 2/9/2018");

Executed either
if statement is
true / false
JAVA CODE EXAMPLE: !=
OPERATOR
public class Count
{
public static void main (String args[])
{
double y=15.0;
double x=25.0;
if (y!=x)
System.out.println("Result : y not equal x");
}
}
Output:

Result : y not equal x


Java code example: >= operator
JAVA CODE EXAMPLE: >=
OPERATOR
public class DeterminePrice
{
public static void main (String args[])
{
double totalPrice = 120;

if(totalPrice >= 100)


System.out.println("You will get 20% discount");
System.out.println("Thank you for coming to CMART");
}
}

Output:
You will get 20% discount
Thank you for coming to CMART
Java code example: <= operator
JAVA CODE EXAMPLE: <=
OPERATOR
public class DetermineResult
{
public static void main (String args[])
{
double totalMarks = 60;

if(totalMarks <=40)
System.out.println("You failed the subject!");
System.out.println("Good luck for next sem");
}
}
Output:
Good luck for next sem
THINK..

int number = 10;


if number == 10;
System.out.println("The number is" +number);

int number = 10;


if (number == 10)
System.out.println("The number is" +number);
BLOCK STATEMENTS

Several statements can be grouped together into a block


statement delimited by braces

if (testScore<40)
{
System.out.println ("You failed");
System.out.println ("Try harder next time");
}

1
7
BLOCK STATEMENTS

if (testScore < 40)


{
System.out.println ("You failed");
System.out.println ("Try harder next time");
}

COMPARE WITH
if (testScore < 40)
System.out.println ("You failed");
System.out.println ("Try harder next time");

1
8
LOGICAL (BOOLEAN)
OPERATION
Operators Names Descriptions

! not Returns TRUE when P is false


and returns FALSE when P is true

&& and Returns TRUE only when both P


and Q is true

|| or Returns TRUE when either P or Q


is true

P, Q: conditions
LOGICAL (BOOLEAN)
OPERATION
P, Q: conditions, e.g: if((carryMark<10) && (finalMark<20))

P Q

P Q P&&Q P||Q !P
false false false false true
false true false true true
true false false true false
true true true true false
LOGICAL OPERATORS

Expressions that use logical operators can form complex


conditions.

if ((ipuIndex < 100) && (distanceToClass < 2))


System.out.println ("Let’s walk to class");

if ((salary > expenses) || (savings > expenses))


System.out.println ("This guy have a lot of savings");

if (!(testScore <40))
System.out.println ("You passed the exam");
2
1
PRECEDENCE OF
OPERATORS
THE IF-ELSE STATEMENT (2
WAY SELECTION)
 An else clause can be added to an if statement to
make an if-else statement

if ( condition )
statement1;
else
statement2;
 If the condition is true, statement1 is executed; if the
condition is false, statement2 is executed
 One or the other will be executed, but not both

2
3
LOGIC
OF AN condition true
evaluated

IF-ELSE false

STATEM statement1 statement2

ENT
LOGIC true

OF AN testScore<40?

IF-ELSE
false System.out.pr
intln(“You
failed”);

STATEM System.out.pr
intln(“You
passed”);

ENT
IF/ELSE STATEMENT

if (testScore<40)
System.out.println("You failed");
else
System.out.println("You passed");

Purpose:
To execute a statement when a condition is true or
false
DESIGN OF INTERACTIVE
PROGRAM: PSEUDOCODE &
FLOW CHART
Example of Algorithm: if/else
Statement
Start Start

Input totalPrice
Input totalPrice
if(totalPrice > 100)
Calculate discount= 20.0/100 * False
totalPrice totalPrice>100? discount =5.0/100*totalPrice

else True

Calculate discount = 5.0/100 * discount = 20.0/100*totalPrice


totalPrice
Print “Discount given is RM” +discount Print “Discount given is
RM” +discount
End

End
SAMPLE CODE

import java.util.Scanner;

public class Discount


{
public static void main (String[] args)
{
double totalPrice, discount;
Scanner scan = new Scanner (System.in);

System.out.println ("Enter total price:");


totalPrice = scan.nextDouble();

if(totalPrice > 100)


discount = 20.0 / 100 * totalPrice;
else
discount = 5.0 / 100 * totalPrice;
System.out.printf("Discount given is RM %.2f“,discount);
}
}
OUTPUT

Sample Run
Enter total price:
90
Discount given is RM 4.50
BLOCK STATEMENT

if (testScore<40)
{
System.out.println ("You failed");
System.out.println ("Try harder next
time");
}
else
{
System.out.println ("You passed");
System.out.println ("Keep it up!");
}
FLOW CHART FOR IF ELSE
STATEMENT: WITH BLOCK
Start

Input testScore

true
testScore<40?

false Print “You failed”


Print “Try harder”

Print “You passed”


Print “Keep it up!”

End
PSEUDO CODE FOR IF ELSE
STATEMENT: WITH BLOCK
Start

Input testScore

if (testScore<40)
Print "You failed"
Print "Try harder"

else
Print "You passed"
Print "Keep it up!"

End
COMBINATION OF BLOCK
STATEMENT AND LOGICAL
OPERATORS
EXAMPLE:
Determine Grade, if testScore is higher or equal to
85%, the achieved grade is A
if ((testScore >=85) && (testScore<=100 ))
{
System.out.println("Congrats! Your grade is A.");
System.out.println("Keep it up!");
}

else
{
System.out.println("Sorry, you did not get A.");
System.out.println("Try again next time.");
}
Syntax:
MULTIPL if (expression1)
E statement1

SELECTI else if (expression2)


statement2

ON else
statement3
FLOW CHART FOR
MULTIPLE SELECTION
Start

Input testScore

true
testScore>90? Print “Very high grade”
Print “Keep it up!”
false

testScore>50 true Print “Moderate”


&& testScore<60? Print “Can improve”

false

Print “Not very high or moderate”

End
MULTIPLE SELECTION
if (testScore>90)
{
System.out.println ("Very high grade");
System.out.println ("Keep it up!");
}
else if (testScore>50 && testScore <60)
{
System.out.println ("Moderate");
System.out.println ("Can improve");
}
else
{
System.out.println ("Not very high or moderate");

}
JAVA CODE (MULTIPLE
SELECTION)
int a;
System.out.println("Enter the number:");
a = scan.nextInt();

if (a>=1)
{
System.out.println ("The number you entered is :" +
a);
System.out.println ("You entered a positive number");
}
else if (a<0)
{
System.out.println ("The number you entered is :" +
a);
System.out.println ("You entered a negative number");
}
else
{
System.out.println ("The number you entered is :" +
a);
System.out.println ("You entered zero");
}
Sample Run
Output1
Enter the number : 15
The number you entered is :15
You entered a positive number
Output2
Enter the number : -15
The number you entered is :-15
You entered a negative number
Output3
Enter the number : 0
The number you entered is :0
You entered zero
MULTIPLE SELECTIONS

Example
The grading scheme for a course is given as below:
Mark Grade
90 - 100 A
80 – 89 B
70 – 79 C
60 – 69 D
0 - 59 F
Read a mark & determine the grade.
MULTIPLE SELECTIONS

if ((mark >= 90) && (mark <=100))


grade = ‘A’;
else if ((mark >= 80) && (mark <= 89))
grade = ‘B’;
else if ((mark >= 70) && (mark <= 79))
grade = ‘C’;
else if ((mark >= 60) && (mark <= 69))
grade = ‘D’;
else
grade = ‘F’;
MULTIPLE SELECTIONS
if (mark >= 90) if ((mark >= 90) && (mark <=100))
grade = ‘A’; grade = ‘A’;
else if (mark >= 80) if ((mark >= 80) && (mark <= 89))
grade = ‘B’; grade = ‘B’;
else if (mark >= 70) if ((mark >= 70) && (mark <= 79))
grade = ‘C’; grade = ‘C’;
else if (mark >= 60) if ((mark >= 60) && (mark <= 69))
grade = ‘D’; grade = ‘D’;
else if ((mark >= 0) && (mark <= 59))
grade = ‘F’; grade = ‘F’;
Equivalent code with series of if statements
EXERCISE
• Write a program that asks an integer number from user
as input.
• The program will determine the type of entered number,
whether it is an odd or even number.
• Then it will display the type of the number.

Sample run:

Enter an integer number:35


The number is odd
Enter an integer number:20
The number is even
MULTIPLE SELECTION
(NESTED IF)

public class TestNestedIf {


public static void main(String args[]) {
int a = 50; int b = 10;

if( a == 50 ) {
if( b <= 10 ) {
System.out.print("a = 50 and b <= 10");
}
}
}//main
} //class
MULTIPLE SELECTION
(NESTED IF)
Example
int numb = 50;
if(numb%2 == 0)
{
if(numb >0)
{
System.out.println("The even number is a positive number");
}
}
else
{
System.out.println("The number is odd");
}
MULTIPLE SELECTION
(NESTED IF)
double balance = 90.00, penalty=10.00;
int interestRate = 2;

if(balance>=50.00)
{
if(interestRate>=0)
balance = balance + ((interestRate * balance)/12);
else
System.out.println("Cannot have negative interest");
}
else
balance = balance - penalty;

System.out.println("The balance is "+balance);

The balance is 105.0


TODAY’S TAKE AWAY

 Selection control
structure.
 Various selection
structures.

46

You might also like