SlideShare a Scribd company logo
1 of 57
Download to read offline
Computer Programming I - CSC111
Chapter 3 – Flow of Control
Dr. Mejdl Safran
mejdl@ksu.edu.sa
1
Outline
Outline
Outline
Outline
• Basic if-else statement
•Boolean expressions
•Nested if-else statements
•Multibranch if-else statements
•Case Study – Body Mass Index
•Case study – the exit method
•The switch statement
2
Flow of control
Flow of control
Flow of control
Flow of control
3
•Flow of control is the order in which a program
performs actions.
• Up to this point, the order has been sequential.
•A branching statement chooses between two or more
possible actions.
•A loop statement repeats an action until a stopping
condition occurs.
The
The
The
The if-else statement
statement
statement
statement
4
•A branching statement that chooses between two
possible actions.
•Syntax
if (Boolean_Expression)
Statement_1
else
Statement_2
Semantics of
Semantics of
Semantics of
Semantics of t
t
t
the
he
he
he if-else statement
statement
statement
statement
5
The
The
The
The if-else statement: Example
statement: Example
statement: Example
statement: Example
6
double score;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your score: ");
score = keyboard.nextDouble();
if(score >= 60)
System.out.println("You have passed!");
else
System.out.println("Sorry, you have failed, try the course again");
The
The
The
The if-else statement: Example
statement: Example
statement: Example
statement: Example
7
Please enter your score:
95
You have passed!
Please enter your score:
58
Sorry, you have failed, try the course
again
Output
The
The
The
The if-else statement: String example
statement: String example
statement: String example
statement: String example
8
The
The
The
The if-else statement: String example
statement: String example
statement: String example
statement: String example
9
Compound statements
Compound statements
Compound statements
Compound statements
• To include multiple statements
in a branch, enclose the
statements in braces.
• Syntax
{
Statement_1;
Statement_2;
…
}
• Example:
if (count < 3)
{
total = 0;
count = 0;
}
10
Omitting the
Omitting the
Omitting the
Omitting the else part
part
part
part
11
•The semantics of an if statement without an else
Boolean expressions
Boolean expressions
Boolean expressions
Boolean expressions
12
•The value of a boolean expression is either true
or false.
•Examples
time < limit
balance <= 0
Java Comparison Operators
Java Comparison Operators
Java Comparison Operators
Java Comparison Operators
13
Compound Boolean
Compound Boolean
Compound Boolean
Compound Boolean Expressions (&&)
Expressions (&&)
Expressions (&&)
Expressions (&&)
14
•Boolean expressions can be combined using the "and"
(&&) operator.
•Example
if ((score > 0) && (score <= 100))
...
•Not allowed
if (0 < score <= 100)
...
Compound Boolean
Compound Boolean
Compound Boolean
Compound Boolean Expressions (&&)
Expressions (&&)
Expressions (&&)
Expressions (&&)
15
•Syntax
(Sub_Expression_1) &&
(Sub_Expression_2)
•Parentheses often are used to enhance
readability.
•The larger expression is true only when both of
the smaller expressions are true.
Compound Boolean
Compound Boolean
Compound Boolean
Compound Boolean Expressions (||)
Expressions (||)
Expressions (||)
Expressions (||)
16
•Boolean expressions can be combined using the "or"
(||) operator.
•Example
if ((quantity > 5) || (cost < 10))
...
•Syntax
(Sub_Expression_1) || (Sub_Expression_2)
Compound Boolean
Compound Boolean
Compound Boolean
Compound Boolean Expressions (||)
Expressions (||)
Expressions (||)
Expressions (||)
17
•The larger expression is true
• When either of the smaller expressions is true
• When both of the smaller expressions are true.
•The Java version of "or" is the inclusive or which
allows either or both to be true.
• The exclusive or allows one or the other, but not both
to be true.
Negating a Boolean
Negating a Boolean
Negating a Boolean
Negating a Boolean Expression (!)
Expression (!)
Expression (!)
Expression (!)
18
•A boolean expression can be negated using the "not"
(!) operator.
•Syntax
!(Boolean_Expression)
•Example
(a || b) && !(a && b)
which is the exclusive or
Negating a Boolean
Negating a Boolean
Negating a Boolean
Negating a Boolean Expression (!)
Expression (!)
Expression (!)
Expression (!)
19
•Avoiding the negation operator
Negating a Boolean
Negating a Boolean
Negating a Boolean
Negating a Boolean Expression (!)
Expression (!)
Expression (!)
Expression (!)
20
Java logical operators
Java logical operators
Java logical operators
Java logical operators
21
Boolean operators
Boolean operators
Boolean operators
Boolean operators
22
Nested
Nested
Nested
Nested if-else statements
statements
statements
statements
23
•An if-else statement can contain any sort of
statement within it.
•In particular, it can contain another if-else
statement.
•An if-else may be nested within the "if" part.
•An if-else may be nested within the "else" part.
•An if-else may be nested within both parts.
Nested statements
Nested statements
Nested statements
Nested statements
24
• Syntax
if (Boolean_Expression_1)
if (Boolean_Expression_2)
Statement_1;
else
Statement_2;
else
if (Boolean_Expression_3)
Statement_3;
else
Statement_4;
Nested statements
Nested statements
Nested statements
Nested statements
25
•Each else is paired with the nearest unmatched if.
•If used properly, indentation communicates which if
goes with which else.
•Braces can be used like parentheses to group
statements.
Nested statements
Nested statements
Nested statements
Nested statements
26
• Subtly different forms
First Form
if (a > b)
{
if (c > d)
e = f
}
else
g = h;
Second Form
if (a > b)
if (c > d)
e = f
else
g = h;
// oops
Multibranch
Multibranch
Multibranch
Multibranch if-else statements
statements
statements
statements
27
•Syntax
if (Boolean_Expression_1)
Statement_1;
else if (Boolean_Expression_2)
Statement_2;
else if (Boolean_Expression_3)
Statement_3;
else if …
else
Default_Statement;
28
Multibranch
Multibranch
Multibranch
Multibranch
if-else
statements
statements
statements
statements
Multibranch
Multibranch
Multibranch
Multibranch if-else statements: example
statements: example
statements: example
statements: example
29
Assigning
Assigning
Assigning
Assigning
letter
letter
letter
letter
grader
grader
grader
grader
example
example
example
example
30
import java.util.Scanner;
public class Grader
{
public static void main(String[] args)
{
int score;
char grade;
System.out.println("Enter your score: ");
Scanner keyboard = new Scanner(System.in);
score = keyboard.nextInt();
if (score >= 90)
grade = 'A';
else if ((score >= 80) && (score < 90))
grade = 'B';
else if ((score >= 70) && (score < 80))
grade = 'C';
else if ((score >= 60) && (score < 70))
grade = 'D';
else
grade = 'F';
System.out.println("Score = " + score);
System.out.println("Grade = " + grade);
}
}
Assigning
Assigning
Assigning
Assigning
letter
letter
letter
letter
grader
grader
grader
grader
example
example
example
example
: equivalent
: equivalent
: equivalent
: equivalent
code
code
code
code
31
import java.util.Scanner;
public class Grader
{
public static void main(String[] args)
{
int score;
char grade;
System.out.println("Enter your score: ");
Scanner keyboard = new Scanner(System.in);
score = keyboard.nextInt();
if (score >= 90)
grade = 'A';
else if (score >= 80)
grade = 'B';
else if (score >= 70)
grade = 'C';
else if (score >= 60)
grade = 'D';
else
grade = 'F';
System.out.println("Score = " + score);
System.out.println("Grade = " + grade);
}
}
Case Study
Case Study
Case Study
Case Study –
–
–
– Body Mass Index
Body Mass Index
Body Mass Index
Body Mass Index
32
• Body Mass Index (BMI) is used to estimate the risk of weight-
related problems
• BMI = mass / height2
• Mass in kilograms, height in meters
• Health assessment if:
• BMI < 18.5 Underweight
• 18.5 ≤ BMI < 25 Normal weight
• 25 ≤ BMI < 30 Overweight
• 30 ≤ BMI Obese
Case Study
Case Study
Case Study
Case Study –
–
–
– Body Mass Index
Body Mass Index
Body Mass Index
Body Mass Index
33
•Algorithm
• Input height in feet & inches, weight in pounds
• Convert to meters and kilograms
• 1 feet = 12 inches
• 1 inch = 0.254 meters
• ((feet * 12) + inches) * 0.254
• 2.2 lb = 1 kg
• pound / 2.2
• Compute BMI
• Output health risk using if statements
34
import java.util.Scanner;
public class BMI
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int pounds, feet, inches;
double heightMeters, mass, BMI;
System.out.println("Enter your weight in pounds.");
pounds = keyboard.nextInt();
System.out.println("Enter your height in feet" +
"followed by a space" +
"then additional inches.");
feet = keyboard.nextInt();
inches = keyboard.nextInt();
heightMeters = ((feet * 12) + inches) * 0.0254;
mass = (pounds / 2.2);
BMI = mass / (heightMeters * heightMeters);
System.out.println("Your BMI is " + BMI);
System.out.print("Your risk category is ");
if (BMI < 18.5)
System.out.println("Underweight.");
else if (BMI < 25)
System.out.println("Normal weight.");
else if (BMI < 30)
System.out.println("Overweight.");
else
System.out.println("Obese.");
}
}
Challenge
Challenge
Challenge
Challenge
35
int x = 1;
int y = 2;
int z=y=x;
if(++x < x++)
x=y;
else if( (x=y) <= ++z)
x*=2;
x*= y*z/2;
System.out.println("x= " + x);
The
The
The
The exit Method
Method
Method
Method
36
•Sometimes a situation arises that makes
continuing the program pointless.
•A program can be terminated normally by
System.exit(0).
The
The
The
The exit Method
Method
Method
Method
37
•Example
if (numberOfWinners == 0)
{
System.out.println ("Error: Dividing by zero.");
System.exit(0);
}
else
{
oneShare = payoff / numberOfWinners;
System.out.println("Each winner will receive $" +
oneShare);
}
The
The
The
The type
type
type
type boolean
38
•The type boolean is a primitive type with only two
values: true and false.
•Boolean variables can make programs more readable.
if (systemsAreOK)
instead of
if((temperature <= 100) && (thrust >=
12000) && (cabinPressure > 30) && …)
Boolean
Boolean
Boolean
Boolean expressions
expressions
expressions
expressions and
and
and
and variables
variables
variables
variables
39
•Variables, constants, and expressions of type
boolean all evaluate to either true or false.
•A boolean variable can be given the value of a
boolean expression by using an assignment operator.
boolean isPositive = (number > 0);
...
if (isPositive) ...
Naming
Naming
Naming
Naming boolean
boolean
boolean
boolean variables
variables
variables
variables
40
•Choose names such as isPositive or
systemsAreOk.
•Avoid names such as numberSign or
systemStatus.
What output is produced by this code?
41
int number = 7;
boolean isPositive = (number > 0);
if (number > 0);
number = -100;
if (isPositive)
System.out.println("Positive.");
else
System.out.println("Not positive.");
System.out.println(number);
Positive.
-100
Output
Precedence r
Precedence r
Precedence r
Precedence rules
ules
ules
ules
42
• In what order are the operations performed?
score < min/2 - 10 || score > 90
score < (min/2) - 10 || score > 90
score < ((min/2) - 10) || score > 90
(score < ((min/2) - 10)) || score > 90
(score < ((min/2) - 10)) || (score > 90)
Short
Short
Short
Short-
-
-
-circuit
circuit
circuit
circuit evaluation
evaluation
evaluation
evaluation
43
•Sometimes only part of a boolean expression needs to
be evaluated to determine the value of the entire
expression.
• If the first operand associated with an || is true, the
expression is true.
• If the first operand associated with an && is false, the
expression is false.
•This is called short-circuit or lazy evaluation.
Short
Short
Short
Short-
-
-
-circuit
circuit
circuit
circuit evaluation
evaluation
evaluation
evaluation
44
•Short-circuit evaluation is not only efficient,
sometimes it is essential!
•A run-time error can result, for example, from an
attempt to divide by zero.
if ((number != 0) && (sum/number > 5))
•Complete evaluation can be achieved by substituting
& for && or | for ||.
Example
Example
Example
Example
45
int x= 10, y=20;
if(x>15 && y++<50)
x=0;
System.out.println("x= " + x + " ; y= " + y);
if(x>15 & y++<50)
x=0;
System.out.println("x= " + x + " ; y= " + y);
x= 10 ; y= 20
x= 10 ; y= 21
Output
Input and
Input and
Input and
Input and output
output
output
output of
of
of
of boolean
boolean
boolean
boolean values
values
values
values
46
boolean booleanVar = false;
System.out.println(booleanVar);
System.out.println("Enter a boolean value:");
Scanner keyboard = new Scanner(System.in);
booleanVar = keyboard.nextBoolean();
System.out.println("You entered " + booleanVar);
false
Enter a boolean value:
true
You entered true
Output
Input validation
Input validation
Input validation
Input validation
47
•You should check your input to ensure that it is within
a valid or reasonable range.
• Example:
int timeInHours;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the time in hours (24-hour clock): ");
timeInHours = keyboard.nextInt();
if(timeInHours >= 0 && timeInHours < 24)
System.out.println("Time is " + timeInHours);
else
System.out.println("Your input is out of range!");
Challenge
Challenge
Challenge
Challenge
48
int timeInHours;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the time in hours (24-hour clock): ");
timeInHours = keyboard.nextInt();
if(timeInHours >= 0 && timeInHours < 24)
System.out.println("Time is " + timeInHours);
else
System.out.println("Your input is out of range!");
•Add check for minutes
•Try to convert and output the time to the 12-hour
clock
The
The
The
The switch statement
statement
statement
statement
•The switch statement is a mutltiway branch that
makes a decision based on an integral (integer or
character) expression.
• Java 7 allows String expressions
•The switch statement begins with the keyword
switch followed by an integral expression in
parentheses and called the controlling expression.
49
The
The
The
The switch statement
statement
statement
statement
•A list of cases follows, enclosed in braces.
•Each case consists of the keyword case followed by
• A constant called the case label
• A colon
• A list of statements.
•The list is searched for a case label matching the
controlling expression.
50
The
The
The
The switch statement
statement
statement
statement
•The action associated with a matching case label is
executed.
•If no match is found, the case labeled default is
executed.
• The default case is optional, but recommended, even if
it simply prints a message.
•Repeated case labels are not allowed.
51
The
The
The
The switch statement
statement
statement
statement
• Syntax
switch(Controlling_Expression)
{
case Case_Label:
Statement(s);
break;
case Case_Label:
…
default:
…
} 52
The
The
The
The switch statement
statement
statement
statement
•The action for each case typically ends with the word
break.
•The optional break statement prevents the
consideration of other cases.
•The controlling expression can be anything that
evaluates to an integral type.
53
54
int day;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of the day: ");
day = input.nextInt();
switch(day)
{
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Wrong input!! Your input should be between 1-7");
break;
}
55
Enter the number of the day:
9
Wrong input!! Your input should be between 1-7
Enter the number of the day:
1
Sunday
Sample Output
Sample Output
Another example
Another example
Another example
Another example
• Write a program using switch statement that prints
the appropriate message according to your entered
grade.
56
Grade to enter Message to print
A Excellent grade
B Very good grade
C Good grade
D , E or F Low grade
Other grades Invalid grade
57
char grade;
Scanner input = new Scanner(System.in);
System.out.println("Enter your grade (A,B,C,D,E or F): ");
grade = input.nextLine().charAt(0);
switch (grade) {
case 'A':
System.out.println("Excellent grade");
break;
case 'B':
System.out.println("Very good grade");
break;
case 'C':
System.out.println("Good grade");
break;
case 'D':
case 'E':
case 'F':
System.out.println("Low grade");
break;
default:
System.out.println("Invalid grade");
break;
}

More Related Content

Similar to CSC111-Chap_03.pdf

Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptxssuserfb3c3e
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
Object oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsObject oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsVaibhav Khanna
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysDevaKumari Vijay
 
Chaptfffffuuer05.PPT
Chaptfffffuuer05.PPTChaptfffffuuer05.PPT
Chaptfffffuuer05.PPTsdvdsvsdvsvds
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Absolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankAbsolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankLauriewest24
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constantsTAlha MAlik
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlENGWAU TONNY
 
control statements
control statementscontrol statements
control statementsAzeem Sultan
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional StatementsIntro C# Book
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Ref Lec 4- Conditional Statement (1).pptx
Ref Lec 4- Conditional Statement (1).pptxRef Lec 4- Conditional Statement (1).pptx
Ref Lec 4- Conditional Statement (1).pptxBilalAhmad735613
 
Programming with C++
Programming with C++Programming with C++
Programming with C++ssuser802d47
 

Similar to CSC111-Chap_03.pdf (20)

Control Structures.pptx
Control Structures.pptxControl Structures.pptx
Control Structures.pptx
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
Object oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statementsObject oriented programming16 boolean expressions and selection statements
Object oriented programming16 boolean expressions and selection statements
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Chaptfffffuuer05.PPT
Chaptfffffuuer05.PPTChaptfffffuuer05.PPT
Chaptfffffuuer05.PPT
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Flow of Control
Flow of ControlFlow of Control
Flow of Control
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Absolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test BankAbsolute Java 5e Savitch Test Bank
Absolute Java 5e Savitch Test Bank
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
 
control statements
control statementscontrol statements
control statements
 
05. Conditional Statements
05. Conditional Statements05. Conditional Statements
05. Conditional Statements
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Control structure
Control structureControl structure
Control structure
 
Control structures i
Control structures i Control structures i
Control structures i
 
Ref Lec 4- Conditional Statement (1).pptx
Ref Lec 4- Conditional Statement (1).pptxRef Lec 4- Conditional Statement (1).pptx
Ref Lec 4- Conditional Statement (1).pptx
 
Programming with C++
Programming with C++Programming with C++
Programming with C++
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

CSC111-Chap_03.pdf

  • 1. Computer Programming I - CSC111 Chapter 3 – Flow of Control Dr. Mejdl Safran mejdl@ksu.edu.sa 1
  • 2. Outline Outline Outline Outline • Basic if-else statement •Boolean expressions •Nested if-else statements •Multibranch if-else statements •Case Study – Body Mass Index •Case study – the exit method •The switch statement 2
  • 3. Flow of control Flow of control Flow of control Flow of control 3 •Flow of control is the order in which a program performs actions. • Up to this point, the order has been sequential. •A branching statement chooses between two or more possible actions. •A loop statement repeats an action until a stopping condition occurs.
  • 4. The The The The if-else statement statement statement statement 4 •A branching statement that chooses between two possible actions. •Syntax if (Boolean_Expression) Statement_1 else Statement_2
  • 5. Semantics of Semantics of Semantics of Semantics of t t t the he he he if-else statement statement statement statement 5
  • 6. The The The The if-else statement: Example statement: Example statement: Example statement: Example 6 double score; Scanner keyboard = new Scanner(System.in); System.out.println("Please enter your score: "); score = keyboard.nextDouble(); if(score >= 60) System.out.println("You have passed!"); else System.out.println("Sorry, you have failed, try the course again");
  • 7. The The The The if-else statement: Example statement: Example statement: Example statement: Example 7 Please enter your score: 95 You have passed! Please enter your score: 58 Sorry, you have failed, try the course again Output
  • 8. The The The The if-else statement: String example statement: String example statement: String example statement: String example 8
  • 9. The The The The if-else statement: String example statement: String example statement: String example statement: String example 9
  • 10. Compound statements Compound statements Compound statements Compound statements • To include multiple statements in a branch, enclose the statements in braces. • Syntax { Statement_1; Statement_2; … } • Example: if (count < 3) { total = 0; count = 0; } 10
  • 11. Omitting the Omitting the Omitting the Omitting the else part part part part 11 •The semantics of an if statement without an else
  • 12. Boolean expressions Boolean expressions Boolean expressions Boolean expressions 12 •The value of a boolean expression is either true or false. •Examples time < limit balance <= 0
  • 13. Java Comparison Operators Java Comparison Operators Java Comparison Operators Java Comparison Operators 13
  • 14. Compound Boolean Compound Boolean Compound Boolean Compound Boolean Expressions (&&) Expressions (&&) Expressions (&&) Expressions (&&) 14 •Boolean expressions can be combined using the "and" (&&) operator. •Example if ((score > 0) && (score <= 100)) ... •Not allowed if (0 < score <= 100) ...
  • 15. Compound Boolean Compound Boolean Compound Boolean Compound Boolean Expressions (&&) Expressions (&&) Expressions (&&) Expressions (&&) 15 •Syntax (Sub_Expression_1) && (Sub_Expression_2) •Parentheses often are used to enhance readability. •The larger expression is true only when both of the smaller expressions are true.
  • 16. Compound Boolean Compound Boolean Compound Boolean Compound Boolean Expressions (||) Expressions (||) Expressions (||) Expressions (||) 16 •Boolean expressions can be combined using the "or" (||) operator. •Example if ((quantity > 5) || (cost < 10)) ... •Syntax (Sub_Expression_1) || (Sub_Expression_2)
  • 17. Compound Boolean Compound Boolean Compound Boolean Compound Boolean Expressions (||) Expressions (||) Expressions (||) Expressions (||) 17 •The larger expression is true • When either of the smaller expressions is true • When both of the smaller expressions are true. •The Java version of "or" is the inclusive or which allows either or both to be true. • The exclusive or allows one or the other, but not both to be true.
  • 18. Negating a Boolean Negating a Boolean Negating a Boolean Negating a Boolean Expression (!) Expression (!) Expression (!) Expression (!) 18 •A boolean expression can be negated using the "not" (!) operator. •Syntax !(Boolean_Expression) •Example (a || b) && !(a && b) which is the exclusive or
  • 19. Negating a Boolean Negating a Boolean Negating a Boolean Negating a Boolean Expression (!) Expression (!) Expression (!) Expression (!) 19 •Avoiding the negation operator
  • 20. Negating a Boolean Negating a Boolean Negating a Boolean Negating a Boolean Expression (!) Expression (!) Expression (!) Expression (!) 20
  • 21. Java logical operators Java logical operators Java logical operators Java logical operators 21
  • 22. Boolean operators Boolean operators Boolean operators Boolean operators 22
  • 23. Nested Nested Nested Nested if-else statements statements statements statements 23 •An if-else statement can contain any sort of statement within it. •In particular, it can contain another if-else statement. •An if-else may be nested within the "if" part. •An if-else may be nested within the "else" part. •An if-else may be nested within both parts.
  • 24. Nested statements Nested statements Nested statements Nested statements 24 • Syntax if (Boolean_Expression_1) if (Boolean_Expression_2) Statement_1; else Statement_2; else if (Boolean_Expression_3) Statement_3; else Statement_4;
  • 25. Nested statements Nested statements Nested statements Nested statements 25 •Each else is paired with the nearest unmatched if. •If used properly, indentation communicates which if goes with which else. •Braces can be used like parentheses to group statements.
  • 26. Nested statements Nested statements Nested statements Nested statements 26 • Subtly different forms First Form if (a > b) { if (c > d) e = f } else g = h; Second Form if (a > b) if (c > d) e = f else g = h; // oops
  • 27. Multibranch Multibranch Multibranch Multibranch if-else statements statements statements statements 27 •Syntax if (Boolean_Expression_1) Statement_1; else if (Boolean_Expression_2) Statement_2; else if (Boolean_Expression_3) Statement_3; else if … else Default_Statement;
  • 29. Multibranch Multibranch Multibranch Multibranch if-else statements: example statements: example statements: example statements: example 29
  • 30. Assigning Assigning Assigning Assigning letter letter letter letter grader grader grader grader example example example example 30 import java.util.Scanner; public class Grader { public static void main(String[] args) { int score; char grade; System.out.println("Enter your score: "); Scanner keyboard = new Scanner(System.in); score = keyboard.nextInt(); if (score >= 90) grade = 'A'; else if ((score >= 80) && (score < 90)) grade = 'B'; else if ((score >= 70) && (score < 80)) grade = 'C'; else if ((score >= 60) && (score < 70)) grade = 'D'; else grade = 'F'; System.out.println("Score = " + score); System.out.println("Grade = " + grade); } }
  • 31. Assigning Assigning Assigning Assigning letter letter letter letter grader grader grader grader example example example example : equivalent : equivalent : equivalent : equivalent code code code code 31 import java.util.Scanner; public class Grader { public static void main(String[] args) { int score; char grade; System.out.println("Enter your score: "); Scanner keyboard = new Scanner(System.in); score = keyboard.nextInt(); if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; System.out.println("Score = " + score); System.out.println("Grade = " + grade); } }
  • 32. Case Study Case Study Case Study Case Study – – – – Body Mass Index Body Mass Index Body Mass Index Body Mass Index 32 • Body Mass Index (BMI) is used to estimate the risk of weight- related problems • BMI = mass / height2 • Mass in kilograms, height in meters • Health assessment if: • BMI < 18.5 Underweight • 18.5 ≤ BMI < 25 Normal weight • 25 ≤ BMI < 30 Overweight • 30 ≤ BMI Obese
  • 33. Case Study Case Study Case Study Case Study – – – – Body Mass Index Body Mass Index Body Mass Index Body Mass Index 33 •Algorithm • Input height in feet & inches, weight in pounds • Convert to meters and kilograms • 1 feet = 12 inches • 1 inch = 0.254 meters • ((feet * 12) + inches) * 0.254 • 2.2 lb = 1 kg • pound / 2.2 • Compute BMI • Output health risk using if statements
  • 34. 34 import java.util.Scanner; public class BMI { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); int pounds, feet, inches; double heightMeters, mass, BMI; System.out.println("Enter your weight in pounds."); pounds = keyboard.nextInt(); System.out.println("Enter your height in feet" + "followed by a space" + "then additional inches."); feet = keyboard.nextInt(); inches = keyboard.nextInt(); heightMeters = ((feet * 12) + inches) * 0.0254; mass = (pounds / 2.2); BMI = mass / (heightMeters * heightMeters); System.out.println("Your BMI is " + BMI); System.out.print("Your risk category is "); if (BMI < 18.5) System.out.println("Underweight."); else if (BMI < 25) System.out.println("Normal weight."); else if (BMI < 30) System.out.println("Overweight."); else System.out.println("Obese."); } }
  • 35. Challenge Challenge Challenge Challenge 35 int x = 1; int y = 2; int z=y=x; if(++x < x++) x=y; else if( (x=y) <= ++z) x*=2; x*= y*z/2; System.out.println("x= " + x);
  • 36. The The The The exit Method Method Method Method 36 •Sometimes a situation arises that makes continuing the program pointless. •A program can be terminated normally by System.exit(0).
  • 37. The The The The exit Method Method Method Method 37 •Example if (numberOfWinners == 0) { System.out.println ("Error: Dividing by zero."); System.exit(0); } else { oneShare = payoff / numberOfWinners; System.out.println("Each winner will receive $" + oneShare); }
  • 38. The The The The type type type type boolean 38 •The type boolean is a primitive type with only two values: true and false. •Boolean variables can make programs more readable. if (systemsAreOK) instead of if((temperature <= 100) && (thrust >= 12000) && (cabinPressure > 30) && …)
  • 39. Boolean Boolean Boolean Boolean expressions expressions expressions expressions and and and and variables variables variables variables 39 •Variables, constants, and expressions of type boolean all evaluate to either true or false. •A boolean variable can be given the value of a boolean expression by using an assignment operator. boolean isPositive = (number > 0); ... if (isPositive) ...
  • 40. Naming Naming Naming Naming boolean boolean boolean boolean variables variables variables variables 40 •Choose names such as isPositive or systemsAreOk. •Avoid names such as numberSign or systemStatus.
  • 41. What output is produced by this code? 41 int number = 7; boolean isPositive = (number > 0); if (number > 0); number = -100; if (isPositive) System.out.println("Positive."); else System.out.println("Not positive."); System.out.println(number); Positive. -100 Output
  • 42. Precedence r Precedence r Precedence r Precedence rules ules ules ules 42 • In what order are the operations performed? score < min/2 - 10 || score > 90 score < (min/2) - 10 || score > 90 score < ((min/2) - 10) || score > 90 (score < ((min/2) - 10)) || score > 90 (score < ((min/2) - 10)) || (score > 90)
  • 43. Short Short Short Short- - - -circuit circuit circuit circuit evaluation evaluation evaluation evaluation 43 •Sometimes only part of a boolean expression needs to be evaluated to determine the value of the entire expression. • If the first operand associated with an || is true, the expression is true. • If the first operand associated with an && is false, the expression is false. •This is called short-circuit or lazy evaluation.
  • 44. Short Short Short Short- - - -circuit circuit circuit circuit evaluation evaluation evaluation evaluation 44 •Short-circuit evaluation is not only efficient, sometimes it is essential! •A run-time error can result, for example, from an attempt to divide by zero. if ((number != 0) && (sum/number > 5)) •Complete evaluation can be achieved by substituting & for && or | for ||.
  • 45. Example Example Example Example 45 int x= 10, y=20; if(x>15 && y++<50) x=0; System.out.println("x= " + x + " ; y= " + y); if(x>15 & y++<50) x=0; System.out.println("x= " + x + " ; y= " + y); x= 10 ; y= 20 x= 10 ; y= 21 Output
  • 46. Input and Input and Input and Input and output output output output of of of of boolean boolean boolean boolean values values values values 46 boolean booleanVar = false; System.out.println(booleanVar); System.out.println("Enter a boolean value:"); Scanner keyboard = new Scanner(System.in); booleanVar = keyboard.nextBoolean(); System.out.println("You entered " + booleanVar); false Enter a boolean value: true You entered true Output
  • 47. Input validation Input validation Input validation Input validation 47 •You should check your input to ensure that it is within a valid or reasonable range. • Example: int timeInHours; Scanner keyboard = new Scanner(System.in); System.out.println("Enter the time in hours (24-hour clock): "); timeInHours = keyboard.nextInt(); if(timeInHours >= 0 && timeInHours < 24) System.out.println("Time is " + timeInHours); else System.out.println("Your input is out of range!");
  • 48. Challenge Challenge Challenge Challenge 48 int timeInHours; Scanner keyboard = new Scanner(System.in); System.out.println("Enter the time in hours (24-hour clock): "); timeInHours = keyboard.nextInt(); if(timeInHours >= 0 && timeInHours < 24) System.out.println("Time is " + timeInHours); else System.out.println("Your input is out of range!"); •Add check for minutes •Try to convert and output the time to the 12-hour clock
  • 49. The The The The switch statement statement statement statement •The switch statement is a mutltiway branch that makes a decision based on an integral (integer or character) expression. • Java 7 allows String expressions •The switch statement begins with the keyword switch followed by an integral expression in parentheses and called the controlling expression. 49
  • 50. The The The The switch statement statement statement statement •A list of cases follows, enclosed in braces. •Each case consists of the keyword case followed by • A constant called the case label • A colon • A list of statements. •The list is searched for a case label matching the controlling expression. 50
  • 51. The The The The switch statement statement statement statement •The action associated with a matching case label is executed. •If no match is found, the case labeled default is executed. • The default case is optional, but recommended, even if it simply prints a message. •Repeated case labels are not allowed. 51
  • 52. The The The The switch statement statement statement statement • Syntax switch(Controlling_Expression) { case Case_Label: Statement(s); break; case Case_Label: … default: … } 52
  • 53. The The The The switch statement statement statement statement •The action for each case typically ends with the word break. •The optional break statement prevents the consideration of other cases. •The controlling expression can be anything that evaluates to an integral type. 53
  • 54. 54 int day; Scanner input = new Scanner(System.in); System.out.println("Enter the number of the day: "); day = input.nextInt(); switch(day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("Wrong input!! Your input should be between 1-7"); break; }
  • 55. 55 Enter the number of the day: 9 Wrong input!! Your input should be between 1-7 Enter the number of the day: 1 Sunday Sample Output Sample Output
  • 56. Another example Another example Another example Another example • Write a program using switch statement that prints the appropriate message according to your entered grade. 56 Grade to enter Message to print A Excellent grade B Very good grade C Good grade D , E or F Low grade Other grades Invalid grade
  • 57. 57 char grade; Scanner input = new Scanner(System.in); System.out.println("Enter your grade (A,B,C,D,E or F): "); grade = input.nextLine().charAt(0); switch (grade) { case 'A': System.out.println("Excellent grade"); break; case 'B': System.out.println("Very good grade"); break; case 'C': System.out.println("Good grade"); break; case 'D': case 'E': case 'F': System.out.println("Low grade"); break; default: System.out.println("Invalid grade"); break; }