[go: up one dir, main page]

0% found this document useful (0 votes)
32 views45 pages

Week 5 6 7 - Selection - Control - Structures Updated

The document discusses selection control structures in programming. It describes three types of selection structures: if statements, if-else statements, and switch statements. If statements allow a program to select one of multiple paths of execution based on a boolean conditional criteria. If-else statements add an else clause to execute an alternative statement if the condition is false. Examples are provided to illustrate calculating discounts using if and if-else statements. Logical operators like &&, ||, and ! are also described for combining complex conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views45 pages

Week 5 6 7 - Selection - Control - Structures Updated

The document discusses selection control structures in programming. It describes three types of selection structures: if statements, if-else statements, and switch statements. If statements allow a program to select one of multiple paths of execution based on a boolean conditional criteria. If-else statements add an else clause to execute an alternative statement if the condition is false. Examples are provided to illustrate calculating discounts using if and if-else statements. Logical operators like &&, ||, and ! are also described for combining complex conditions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Compan

y
LOGO
Control Structures

Selection
Objectives

1. To learn how to use the selection control


structure.
2. To understand various selection
structures.
3. To improve algorithm design skills.
3 Types Flow of Control

Sequential (we had learn 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: Sequential Structures

Sequence

statement1

statement2

statement3
Flow of Control: Selection Structures

If the boolean expression evaluates to true,


the statement will be executed. Otherwise,
it will be skipped.
Example of Selection in Computer Program

MAX LOAD: 250 kg

If exceed 250: If do not exceed 250: Conditions

Give warning with Close the door and Actions


BEEP sound go up/down
Flow of Control: Selection Structures

There are 3 types of Java selection


structures:
 if statement
 if-else statement
 switch statement
The if Statement

The if statement has the following syntax:


The condition must be a
boolean expression. It must
if is a Java evaluate to either true or 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 Expressions Descriptions

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

10
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
Executed when if
evaluated first:
statement is true,
is testScore less
if no, it is skipped
than 40?

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

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

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");
}

17
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");
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");

21
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

23
Logic of an if-else statement

condition true
evaluated

false

statement1 statement2
Logic of an if-else statement

true
testScore<40?

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

System.out.println(“You passed”);
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
Example of Algorithm:
if/else Statement
DESIGN OF INTERACTIVE
PROGRAM: PSEUDOCODE & FLOW
Start

Start
CHART Input totalPrice

Input totalPrice
if(totalPrice > 100) False
totalPrice>100? discount =5.0/100*totalPrice
Calculate discount= 20.0/100 * totalPrice
else True
Calculate discount = 5.0/100 * totalPrice
Print “Discount given is RM” +discount discount = 20.0/100*totalPrice

End
Print “Discount given is
RM” +discount

End
Code: if/else Statement

SAMPLE
Start

import java.util.Scanner; CODE


Input totalPrice

public class Discount


{ False
totalPrice>100? discount =5.0/100*totalPrice
public static void main (String[] args)
{ True
double totalPrice, discount;
Scanner scan = new Scanner (System.in); discount = 20.0/100*totalPrice

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


Print “Discount given is
totalPrice = scan.nextDouble(); RM” +discount

if(totalPrice > 100)


discount = 20.0 / 100 * totalPrice; End
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.");
}
Multiple Selection

Syntax:

if (expression1)
statement1
else if (expression2)
statement2
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 Enter an integer number:20


The number is odd 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

You might also like