SlideShare a Scribd company logo
Control Structures 1:
Selection
Chapter Goals
 Be able to use the selection control
structure
 Be able to solve problems involving
repetition.
 Understand the difference among
various selection & loop structures.
 Know the principles used to design
effective selection & loops (next
topic).
 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
statement1
statement2
statement3
 If the boolean expression evaluates to
true, the statement will be executed.
Otherwise, it will be skipped.
Flow of Control: Selection
Structures
 There are 3 types of Java selection
structures:
if statement
if-else statement
switch statement
Flow of Control: Selection
Structures
The if Statement
 The if statement has the following
syntax:
7
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or
false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
Logic of an if statement
condition
evaluated
statement
true
false
if Statement
if (amount <= balance)
balance = balance - amount;
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
10
The if Statement
if (total > MAX)
charge = total * MAX_RATE;
System.out.println ("The charge is " + charge);
 First the condition is evaluated -- the value of
total is either greater than the value of MAX
 If the condition is true, the assignment
statement is executed -- if it isn’t, it is skipped.
 Either way, the call to println is executed
next

Java code example
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
Block Statements
 Several statements can be grouped
together into a block statement
delimited by braces
14
if (total > MAX)
{
System.out.println ("Error!!");
errorCount++;
}
Block Statement
if (amount <= balance)
{
balance = balance - amount;
System.out.println(“Acct new balance = “ +
balance);
}
COMPARE WITH
if (amount <= balance)
balance = balance - amount;
System.out.println(“Acct new balance = “ + balance);
Logical Operators
 Expressions that use logical
operators can form complex
conditions
16
if ((income > MIN_LEVEL ) && (age <50))
System.out.println (“Can Apply Loan");
 All logical operators have lower
precedence than the relational operators
 Logical NOT has higher precedence than
logical AND and logical OR
Logical (Boolean) Operation in Java
Precedence of Operators
Logical Operators
if ((amount <= 1000.0) && (amount <= balance))
{
balance = balance - amount;
System.out.println(“Acct new balance = “ +
balance);
}
EXAMPLE:
New withdrawal condition:
Withdrawal amount of more than RM1000.00 is not allowed.
The if-else Statement (2 way selection)
 An else clause can be added to an if
statement to make an if-else
statement
20
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
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
if/else Statement
if/else Statement
if (amount <= balance)
balance = balance - amount;
else
balance = balance - OVERDRAFT_PENALTY;
Purpose:
To execute a statement when a condition is true
or false
Block Statement
if (amount <= balance)
{
balance = balance - amount;
System.out.println(“Acct new balance = “ + balance);
}
else
{
balance = balance - OVERDRAFT_PENALTY;
System.out.println(“TRANSACTION NOT ALLOWED”);
}
Combine with Boolean operators
if ((age >= 25) && (age <= 50))
{
System.out.println(“You are qualified to apply”);
}
else
{
System.out.println(“You are NOT qualified to apply”);
}
EXAMPLE:
Loan Processing. Can apply if age is between 25 to 50.
Multiple Selection (nested if)
Syntax:
if (expression1)
statement1
else
if (expression2)
statement2
else
statement3
Java code (multiple selection)
if (a>=1)
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the positive number");
}
else if (a<0)
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the negative number");
}
else
{
System.out.println ("The number you enter is :" + a);
System.out.println ("You enter the zero number");
}
Output
Enter the number : 15
The number you enter is :15
You enter the positive number
Enter the number : -15
The number you enter is :-15
You enter the negative number
Enter the number : 0
The number you enter is :0
You enter the zero number
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
Multiple Selections
if (mark >= 90)
grade = ‘A’;
else if (mark >= 80)
grade = ‘B’;
else if (mark >= 70)
grade = ‘C’;
else if (mark >= 60)
grade = ‘D’;
else
grade = ‘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’;
switch Structures (multiple
selection)
switch (expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
}
Expression is also
known as selector.
Value can only be
integral.
If expression
matches value2,
control jumps
to here
switch Structures
The switch Statement
 Often a break statement is used as
the last statement in each case's
statement list
 A break statement causes control to
transfer to the end of the switch
statement
 If a break statement is not used, the
flow of control will continue into the
next case
Control flow of switch statement with and
without the break statements
Switch/Break Examples
int m = 2;
switch (m)
{
case 1 :
System.out.println(“m=1”);
break;
case 2 :
System.out.println(“m=2”);
break;
case 3 :
System.out.println(“m=3”);
break;
default:
System.out.println(“default”);}
int m = 2;
switch (m)
{
case 1 :
System.out.println(“m=1”);
break;
case 2 :
System.out.println(“m=2”);
break;
case 3 :
System.out.println(“m=3”);
break;
default:
System.out.println(“default”);}
Output: m=2
char ch = ‘b’;
switch (ch)
{
case ‘a’ :
System.out.println(“ch=a”);
case ‘b’ :
System.out.println(“ch=b”);
case ‘c’ :
System.out.println(“ch=c”);
default:
System.out.println(“default”);
}
char ch = ‘b’;
switch (ch)
{
case ‘a’ :
System.out.println(“ch=a”);
case ‘b’ :
System.out.println(“ch=b”);
case ‘c’ :
System.out.println(“ch=c”);
default:
System.out.println(“default”);
}
Output: ch=b
             ch=c
             default

More Related Content

What's hot

While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
Abhishek Choksi
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladder
Moni Adhikary
 
Lecture: Automata
Lecture: AutomataLecture: Automata
Lecture: Automata
Marina Santini
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
Muthuselvam RS
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
Rajendran
 
Looping statement
Looping statementLooping statement
Looping statement
ilakkiya
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
Harshita Yadav
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
Prem Kumar Badri
 
While loop
While loopWhile loop
While loop
Feras_83
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Kamal Acharya
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
Koganti Ravikumar
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
sneha2494
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
serializability in dbms
serializability in dbmsserializability in dbms
serializability in dbms
Saranya Natarajan
 
File in c
File in cFile in c
File in c
Prabhu Govind
 

What's hot (20)

While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Simple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladderSimple if else statement,nesting of if else statement &amp; else if ladder
Simple if else statement,nesting of if else statement &amp; else if ladder
 
Lecture: Automata
Lecture: AutomataLecture: Automata
Lecture: Automata
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Intro automata theory
Intro automata theory Intro automata theory
Intro automata theory
 
Looping statement
Looping statementLooping statement
Looping statement
 
Control Structures
Control StructuresControl Structures
Control Structures
 
data types in C programming
data types in C programmingdata types in C programming
data types in C programming
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
 
While loop
While loopWhile loop
While loop
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
 
Preprocessors
PreprocessorsPreprocessors
Preprocessors
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
serializability in dbms
serializability in dbmsserializability in dbms
serializability in dbms
 
File in c
File in cFile in c
File in c
 

Viewers also liked

One Dimentional Array
One Dimentional ArrayOne Dimentional Array
One Dimentional Array
Sonya Akter Rupa
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
Online
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
Hattori Sidek
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
sandhya yadav
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
EngineerBabu
 
Array in c language
Array in c languageArray in c language
Array in c language
home
 

Viewers also liked (6)

One Dimentional Array
One Dimentional ArrayOne Dimentional Array
One Dimentional Array
 
Control structures selection
Control structures   selectionControl structures   selection
Control structures selection
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Introduction to Array ppt
Introduction to Array pptIntroduction to Array ppt
Introduction to Array ppt
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Array in c language
Array in c languageArray in c language
Array in c language
 

Similar to Selection Control Structures

Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1
sotlsoc
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
Khirulnizam Abd Rahman
 
03a control structures
03a   control structures03a   control structures
03a control structures
Manzoor ALam
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
Khirulnizam Abd Rahman
 
M C6java5
M C6java5M C6java5
M C6java5
mbruggen
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
alish sha
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2
sotlsoc
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
Karwan Mustafa Kareem
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
Mehul Desai
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
Hassaan Rahman
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
Huda Alameen
 
Chapter 4.3
Chapter 4.3Chapter 4.3
Chapter 4.3
sotlsoc
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
Neeru Mittal
 
Ch05.pdf
Ch05.pdfCh05.pdf
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
Hossain Md Shakhawat
 
Data structures
Data structuresData structures
Data structures
Khalid Bana
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
Abou Bakr Ashraf
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
Prashant Sharma
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 

Similar to Selection Control Structures (20)

Chapter 4.1
Chapter 4.1Chapter 4.1
Chapter 4.1
 
Chapter 1 nested control structures
Chapter 1 nested control structuresChapter 1 nested control structures
Chapter 1 nested control structures
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Chapter 1 Nested Control Structures
Chapter 1 Nested Control StructuresChapter 1 Nested Control Structures
Chapter 1 Nested Control Structures
 
M C6java5
M C6java5M C6java5
M C6java5
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Dti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selectionDti2143 chap 4 control structures aka_selection
Dti2143 chap 4 control structures aka_selection
 
Chapter 4.2
Chapter 4.2Chapter 4.2
Chapter 4.2
 
Java Programmin: Selections
Java Programmin: SelectionsJava Programmin: Selections
Java Programmin: Selections
 
CH-4 (1).pptx
CH-4 (1).pptxCH-4 (1).pptx
CH-4 (1).pptx
 
ICP - Lecture 7 and 8
ICP - Lecture 7 and 8ICP - Lecture 7 and 8
ICP - Lecture 7 and 8
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Chapter 4.3
Chapter 4.3Chapter 4.3
Chapter 4.3
 
Introduction to Selection control structures in C++
Introduction to Selection control structures in C++ Introduction to Selection control structures in C++
Introduction to Selection control structures in C++
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Data structures
Data structuresData structures
Data structures
 
Visula C# Programming Lecture 3
Visula C# Programming Lecture 3Visula C# Programming Lecture 3
Visula C# Programming Lecture 3
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 

More from PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Exception Handling
Exception HandlingException Handling
Exception Handling
PRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Array
ArrayArray
Array
PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
PRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
PRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
PRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
PRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
PRN USM
 

More from PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Class & Object - Intro
Class & Object - IntroClass & Object - Intro
Class & Object - Intro
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Recently uploaded

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 

Recently uploaded (20)

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 

Selection Control Structures

  • 2. Chapter Goals  Be able to use the selection control structure  Be able to solve problems involving repetition.  Understand the difference among various selection & loop structures.  Know the principles used to design effective selection & loops (next topic).  Improve algorithm design skills.
  • 3. 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)
  • 4. Flow of Control: Sequential Structures statement1 statement2 statement3
  • 5.  If the boolean expression evaluates to true, the statement will be executed. Otherwise, it will be skipped. Flow of Control: Selection Structures
  • 6.  There are 3 types of Java selection structures: if statement if-else statement switch statement Flow of Control: Selection Structures
  • 7. The if Statement  The if statement has the following syntax: 7 if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
  • 8. Logic of an if statement condition evaluated statement true false
  • 9. if Statement if (amount <= balance) balance = balance - amount;
  • 10. 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 10
  • 11. The if Statement if (total > MAX) charge = total * MAX_RATE; System.out.println ("The charge is " + charge);  First the condition is evaluated -- the value of total is either greater than the value of MAX  If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped.  Either way, the call to println is executed next 
  • 12. Java code example 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"); } }
  • 13. Output Result : y not equal x
  • 14. Block Statements  Several statements can be grouped together into a block statement delimited by braces 14 if (total > MAX) { System.out.println ("Error!!"); errorCount++; }
  • 15. Block Statement if (amount <= balance) { balance = balance - amount; System.out.println(“Acct new balance = “ + balance); } COMPARE WITH if (amount <= balance) balance = balance - amount; System.out.println(“Acct new balance = “ + balance);
  • 16. Logical Operators  Expressions that use logical operators can form complex conditions 16 if ((income > MIN_LEVEL ) && (age <50)) System.out.println (“Can Apply Loan");  All logical operators have lower precedence than the relational operators  Logical NOT has higher precedence than logical AND and logical OR
  • 19. Logical Operators if ((amount <= 1000.0) && (amount <= balance)) { balance = balance - amount; System.out.println(“Acct new balance = “ + balance); } EXAMPLE: New withdrawal condition: Withdrawal amount of more than RM1000.00 is not allowed.
  • 20. The if-else Statement (2 way selection)  An else clause can be added to an if statement to make an if-else statement 20 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
  • 21. Logic of an if-else statement condition evaluated statement1 true false statement2
  • 23. if/else Statement if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Purpose: To execute a statement when a condition is true or false
  • 24. Block Statement if (amount <= balance) { balance = balance - amount; System.out.println(“Acct new balance = “ + balance); } else { balance = balance - OVERDRAFT_PENALTY; System.out.println(“TRANSACTION NOT ALLOWED”); }
  • 25. Combine with Boolean operators if ((age >= 25) && (age <= 50)) { System.out.println(“You are qualified to apply”); } else { System.out.println(“You are NOT qualified to apply”); } EXAMPLE: Loan Processing. Can apply if age is between 25 to 50.
  • 26. Multiple Selection (nested if) Syntax: if (expression1) statement1 else if (expression2) statement2 else statement3
  • 27. Java code (multiple selection) if (a>=1) { System.out.println ("The number you enter is :" + a); System.out.println ("You enter the positive number"); } else if (a<0) { System.out.println ("The number you enter is :" + a); System.out.println ("You enter the negative number"); } else { System.out.println ("The number you enter is :" + a); System.out.println ("You enter the zero number"); }
  • 28. Output Enter the number : 15 The number you enter is :15 You enter the positive number Enter the number : -15 The number you enter is :-15 You enter the negative number Enter the number : 0 The number you enter is :0 You enter the zero number
  • 29. 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
  • 30. Multiple Selections if (mark >= 90) grade = ‘A’; else if (mark >= 80) grade = ‘B’; else if (mark >= 70) grade = ‘C’; else if (mark >= 60) grade = ‘D’; else grade = ‘F’;
  • 31. 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’;
  • 32. switch Structures (multiple selection) switch (expression) { case value1: statements1 break; case value2: statements2 break; ... case valuen: statementsn break; default: statements } Expression is also known as selector. Value can only be integral. If expression matches value2, control jumps to here
  • 34. The switch Statement  Often a break statement is used as the last statement in each case's statement list  A break statement causes control to transfer to the end of the switch statement  If a break statement is not used, the flow of control will continue into the next case
  • 35. Control flow of switch statement with and without the break statements
  • 36. Switch/Break Examples int m = 2; switch (m) { case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);} int m = 2; switch (m) { case 1 : System.out.println(“m=1”); break; case 2 : System.out.println(“m=2”); break; case 3 : System.out.println(“m=3”); break; default: System.out.println(“default”);} Output: m=2 char ch = ‘b’; switch (ch) { case ‘a’ : System.out.println(“ch=a”); case ‘b’ : System.out.println(“ch=b”); case ‘c’ : System.out.println(“ch=c”); default: System.out.println(“default”); } char ch = ‘b’; switch (ch) { case ‘a’ : System.out.println(“ch=a”); case ‘b’ : System.out.println(“ch=b”); case ‘c’ : System.out.println(“ch=c”); default: System.out.println(“default”); } Output: ch=b              ch=c              default

Editor's Notes

  1. Else is associated with the most recent incomplete if. Multiple if statements can be used in place of if…else statements. May take longer to evaluate.
  2. Utk aturcara lengkap, sila rujuk h/out (java code no 4)