SlideShare a Scribd company logo
1 of 33
Chapter 4: Control
Structures I
JAVA PROGRAMMING:
FROM PROBLEM ANALYSIS TO PROGRAM DESIGN,
SECOND EDITION
2
Chapter Objectives
 Learn about control structures.
 Examine relational and logical operators.
 Explore how to form and evaluate logical
(Boolean) expressions.
 Learn how to use the selection control
structures if, if…else, and switch in
a program.
3
Control Structures
 Three methods of processing a program:
 In sequence
 Branching
 Looping
 Branch: Altering the flow of program
execution by making a selection or choice.
 Loop: Altering the flow of program
execution by repeating statements.
4
Control Structures
5
Relational Operators
 Relational operator:
 Allows you to make comparisons in a program.
 Binary operator.
 Condition is represented by a logical
expression in Java.
 Logical expression: An expression that has
a value of either true or false.
6
Relational Operators
7
Relational Operators and
Primitive Data Types
 Can be used with integral and floating-point
data types.
 Can be used with the char data type.
 Unicode Collating Sequence.
8
Relational Operators and Primitive Data Types
9
Comparing Strings
 class String
 Method compareTo
 Method equals
 Given string str1 and str2





=
>>
<<
str2str10
str2str10
str2str10
reTo(str2)str1.compa
stringifintegeran
stringtoequalisstringif
stringifintegeran
10
Comparing Strings
String str1 = "Hello";
String str2 = "Hi";
String str3 = "Air";
String str4 = "Bill";
String str5 = "Bigger";
11
Comparing Strings
12
Comparing Strings
13
Comparing Strings
14
Comparing Strings
15
Short-Circuit Evaluation
 A process in which the computer evaluates
a logical expression from left to right and
stops as soon as the value of the expression
is known.
16
Selection
 One-way selection
 Two-way selection
 Compound (block of) statements
 Multiple selections (nested if)
 Conditional operator
 switch structures
17
One-Way Selection
 Syntax:
if (expression)
statement
 Expression referred to as decision maker.
 Statement referred to as action statement.
18
Example 4-11
//Determine the absolute value of an integer
import javax.swing.JOptionPane;
public class AbsoluteValue
{
public static void main(String[] args)
{
int number;
int temp;
String numString;
numString =
JOptionPane.showInputDialog
("Enter an integer:"); //Line 1
number = Integer.parseInt(numString); //Line 2
temp = number; //Line 3
One-Way Selection
19
if (number < 0) //Line 4
number = -number; //Line 5
JOptionPane.showMessageDialog(null,
"The absolute value of " + temp
+ " is " + number,
"Absolute Value",
JOptionPane.INFORMATION_MESSAGE); //Line 6
System.exit(0);
}
One-Way Selection
20
Two-Way Selection
 Syntax:
if (expression)
statement1
else
statement2
 else statement must be paired with an if.
21
Two-Way Selection
22
Two-Way Selection
Example 4-14
if (hours > 40.0)
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0);
else
wages = hours * rate;
23
Example 4-15
if (hours > 40.0); //Line 1
wages = 40.0 * rate +
1.5 * rate * (hours - 40.0); //Line 2
else //Line 3
wages = hours * rate; //Line 4
Because a semicolon follows the closing parenthesis of the if
statement (Line 1), the else statement stands alone. The
semicolon at the end of the if statement (see Line 1) ends the
if statement, so the statement at Line 2 separates the else
clause from the if statement. That is, else is by itself.
Because there is no separate else statement in Java, this code
generates a syntax error.
Two-Way Selection
24
Compound (Block of) Statements
Syntax:
{
statement1
statement2
.
.
.
statementn
}
25
Compound (Block of) Statements
if (age > 18)
{
System.out.println("Eligible to vote.");
System.out.println("No longer a minor.");
}
else
{
System.out.println("Not eligible to vote.");
System.out.println("Still a minor.");
}
26
Multiple Selection: Nested if
 Syntax:
if (expression1)
statement1
else
if (expression2)
statement2
else
statement3
 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.
27
Conditional (? :) Operator
 Ternary operator
 Syntax:
expression1 ? expression2 :
expression3
 If expression1 = true, then the result of the
condition is expression2.
Otherwise, the result of the condition is
expression3.
28
switch Structures
 Expression is also
known as selector.
 Expression can be an
identifier.
 Value can only be
integral.
switch (expression)
{
case value1: statements1
break;
case value2: statements2
break;
...
case valuen: statementsn
break;
default: statements
}
29
switch Structures
30
Example 4-24
switch (grade)
{
case 'A': System.out.println("The grade is A.");
break;
case 'B': System.out.println("The grade is B.");
break;
case 'C': System.out.println("The grade is C.");
break;
case 'D': System.out.println("The grade is D.");
break;
case 'F': System.out.println("The grade is F.");
break;
default: System.out.println("The grade is
invalid.");
}
switch Structures
31
Programming Example:
Cable Company Billing
 Input: Customer’s account number,
customer code, number of premium
channels to which customer subscribes,
number of basic service connections (in the
case of business customers).
 Output: Customer’s account number and the
billing amount.
32
Programming Example:
Cable Company Billing
Solution:
1. Prompt user for information.
2. Use switch statements based on customer’s
type.
3. Use an if statement nested within a switch
statement to determine the amount due by
each customer.
33
Chapter Summary
 Control structures are used to process programs.
 Logical expressions and order of precedence of
operators are used in expressions.
 Compare strings.
 If statements.
 if…else statements.
 switch structures.
 Proper syntax for using control statements.

More Related Content

What's hot

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vishal Patil
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.netilakkiya
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C ProgrammingSonya Akter Rupa
 
Java Data Types
Java Data TypesJava Data Types
Java Data TypesSpotle.ai
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 

What's hot (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Java program structure
Java program structureJava program structure
Java program structure
 
Data types in java
Data types in javaData types in java
Data types in java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control statements
Control statementsControl statements
Control statements
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.net
 
Branching in C
Branching in CBranching in C
Branching in C
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C Programming
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
 

Viewers also liked

Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in JavaJin Castor
 
Control Structures
Control StructuresControl Structures
Control StructuresGhaffar Khan
 
Flowchart Diagram Templates by Creately
Flowchart Diagram Templates by CreatelyFlowchart Diagram Templates by Creately
Flowchart Diagram Templates by CreatelyCreately
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing Ahmad Idrees
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer VisionBrian Thorne
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for BloggersAhmad Idrees
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer SystemAhmad Idrees
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of businessAhmad Idrees
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing Ahmad Idrees
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement Ahmad Idrees
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java Ahmad Idrees
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 

Viewers also liked (20)

Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
 
Control Structures
Control StructuresControl Structures
Control Structures
 
Flowchart Diagram Templates by Creately
Flowchart Diagram Templates by CreatelyFlowchart Diagram Templates by Creately
Flowchart Diagram Templates by Creately
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
What is business
What is businessWhat is business
What is business
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
What is computer Introduction to Computing
What is computer Introduction  to Computing What is computer Introduction  to Computing
What is computer Introduction to Computing
 
Strategic planning and mission statement
Strategic planning and mission statement Strategic planning and mission statement
Strategic planning and mission statement
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 

Similar to Control structures i

Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfComputer Programmer
 
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
 
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
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner Huda Alameen
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
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
 
PE1 Module 3.ppt
PE1 Module 3.pptPE1 Module 3.ppt
PE1 Module 3.pptbalewayalew
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio) rnkhan
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)rnkhan
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdfKirubelWondwoson1
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsLovelitJose
 

Similar to Control structures i (20)

Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
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
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Ch04
Ch04Ch04
Ch04
 
Java input Scanner
Java input Scanner Java input Scanner
Java input Scanner
 
Ch05-converted.pptx
Ch05-converted.pptxCh05-converted.pptx
Ch05-converted.pptx
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
Operators
OperatorsOperators
Operators
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
PE1 Module 3.ppt
PE1 Module 3.pptPE1 Module 3.ppt
PE1 Module 3.ppt
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
 
slides03.ppt
slides03.pptslides03.ppt
slides03.ppt
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
 
Programming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-ExpressionsProgramming in java - Concepts- Operators- Control statements-Expressions
Programming in java - Concepts- Operators- Control statements-Expressions
 

More from Ahmad Idrees

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages Ahmad Idrees
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer Ahmad Idrees
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's Ahmad Idrees
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information Ahmad Idrees
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle Ahmad Idrees
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures Ahmad Idrees
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessmanAhmad Idrees
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutAhmad Idrees
 

More from Ahmad Idrees (8)

An overview of computers and programming languages
An overview of computers and programming languages An overview of computers and programming languages
An overview of computers and programming languages
 
Marketing research links consumer
Marketing research links consumer Marketing research links consumer
Marketing research links consumer
 
Marketing mix and 4 p's
Marketing mix and 4 p's Marketing mix and 4 p's
Marketing mix and 4 p's
 
Managing marketing information
Managing marketing information Managing marketing information
Managing marketing information
 
Swot analysis Marketing Principle
Swot analysis Marketing Principle Swot analysis Marketing Principle
Swot analysis Marketing Principle
 
C++ programming program design including data structures
C++ programming program design including data structures C++ programming program design including data structures
C++ programming program design including data structures
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
Top 40 seo myths everyone should know about
Top 40 seo myths everyone should know aboutTop 40 seo myths everyone should know about
Top 40 seo myths everyone should know about
 

Recently uploaded

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 

Control structures i

  • 1. Chapter 4: Control Structures I JAVA PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN, SECOND EDITION
  • 2. 2 Chapter Objectives  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate logical (Boolean) expressions.  Learn how to use the selection control structures if, if…else, and switch in a program.
  • 3. 3 Control Structures  Three methods of processing a program:  In sequence  Branching  Looping  Branch: Altering the flow of program execution by making a selection or choice.  Loop: Altering the flow of program execution by repeating statements.
  • 5. 5 Relational Operators  Relational operator:  Allows you to make comparisons in a program.  Binary operator.  Condition is represented by a logical expression in Java.  Logical expression: An expression that has a value of either true or false.
  • 7. 7 Relational Operators and Primitive Data Types  Can be used with integral and floating-point data types.  Can be used with the char data type.  Unicode Collating Sequence.
  • 8. 8 Relational Operators and Primitive Data Types
  • 9. 9 Comparing Strings  class String  Method compareTo  Method equals  Given string str1 and str2      = >> << str2str10 str2str10 str2str10 reTo(str2)str1.compa stringifintegeran stringtoequalisstringif stringifintegeran
  • 10. 10 Comparing Strings String str1 = "Hello"; String str2 = "Hi"; String str3 = "Air"; String str4 = "Bill"; String str5 = "Bigger";
  • 15. 15 Short-Circuit Evaluation  A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known.
  • 16. 16 Selection  One-way selection  Two-way selection  Compound (block of) statements  Multiple selections (nested if)  Conditional operator  switch structures
  • 17. 17 One-Way Selection  Syntax: if (expression) statement  Expression referred to as decision maker.  Statement referred to as action statement.
  • 18. 18 Example 4-11 //Determine the absolute value of an integer import javax.swing.JOptionPane; public class AbsoluteValue { public static void main(String[] args) { int number; int temp; String numString; numString = JOptionPane.showInputDialog ("Enter an integer:"); //Line 1 number = Integer.parseInt(numString); //Line 2 temp = number; //Line 3 One-Way Selection
  • 19. 19 if (number < 0) //Line 4 number = -number; //Line 5 JOptionPane.showMessageDialog(null, "The absolute value of " + temp + " is " + number, "Absolute Value", JOptionPane.INFORMATION_MESSAGE); //Line 6 System.exit(0); } One-Way Selection
  • 20. 20 Two-Way Selection  Syntax: if (expression) statement1 else statement2  else statement must be paired with an if.
  • 22. 22 Two-Way Selection Example 4-14 if (hours > 40.0) wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); else wages = hours * rate;
  • 23. 23 Example 4-15 if (hours > 40.0); //Line 1 wages = 40.0 * rate + 1.5 * rate * (hours - 40.0); //Line 2 else //Line 3 wages = hours * rate; //Line 4 Because a semicolon follows the closing parenthesis of the if statement (Line 1), the else statement stands alone. The semicolon at the end of the if statement (see Line 1) ends the if statement, so the statement at Line 2 separates the else clause from the if statement. That is, else is by itself. Because there is no separate else statement in Java, this code generates a syntax error. Two-Way Selection
  • 24. 24 Compound (Block of) Statements Syntax: { statement1 statement2 . . . statementn }
  • 25. 25 Compound (Block of) Statements if (age > 18) { System.out.println("Eligible to vote."); System.out.println("No longer a minor."); } else { System.out.println("Not eligible to vote."); System.out.println("Still a minor."); }
  • 26. 26 Multiple Selection: Nested if  Syntax: if (expression1) statement1 else if (expression2) statement2 else statement3  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.
  • 27. 27 Conditional (? :) Operator  Ternary operator  Syntax: expression1 ? expression2 : expression3  If expression1 = true, then the result of the condition is expression2. Otherwise, the result of the condition is expression3.
  • 28. 28 switch Structures  Expression is also known as selector.  Expression can be an identifier.  Value can only be integral. switch (expression) { case value1: statements1 break; case value2: statements2 break; ... case valuen: statementsn break; default: statements }
  • 30. 30 Example 4-24 switch (grade) { case 'A': System.out.println("The grade is A."); break; case 'B': System.out.println("The grade is B."); break; case 'C': System.out.println("The grade is C."); break; case 'D': System.out.println("The grade is D."); break; case 'F': System.out.println("The grade is F."); break; default: System.out.println("The grade is invalid."); } switch Structures
  • 31. 31 Programming Example: Cable Company Billing  Input: Customer’s account number, customer code, number of premium channels to which customer subscribes, number of basic service connections (in the case of business customers).  Output: Customer’s account number and the billing amount.
  • 32. 32 Programming Example: Cable Company Billing Solution: 1. Prompt user for information. 2. Use switch statements based on customer’s type. 3. Use an if statement nested within a switch statement to determine the amount due by each customer.
  • 33. 33 Chapter Summary  Control structures are used to process programs.  Logical expressions and order of precedence of operators are used in expressions.  Compare strings.  If statements.  if…else statements.  switch structures.  Proper syntax for using control statements.