SlideShare a Scribd company logo
Chapter 5: Control StructuresChapter 5: Control Structures
IIII
JJavaava PProgramming:rogramming:
From Problem Analysis to Program Design,From Problem Analysis to Program Design,
Second EditionSecond Edition
2
Chapter Objectives
 Learn about repetition (looping) control structures.
 Explore how to construct and use count-controlled,
sentinel-controlled, flag-controlled, and EOF-
controlled repetition structures.
 Examine break and continue statements.
 Discover how to form and use nested control
structures.
3
Why Is Repetition Needed?
 There are many situations in which the same
statements need to be executed several times.
 Example:
 Formulas used to find average grades for
students in a class.
4
The while Looping (Repetition) Structure
 Syntax:
while (expression)
statement
 Expression is always true in an infinite loop.
 Statements must change value of expression to false.
5
The while Looping (Repetition) Structure
Example 5-1
i = 0; //Line 1
while (i <= 20) //Line 2
{
System.out.print(i + " "); //Line 3
i = i + 5; //Line 4
}
System.out.println(); //Line 5
Output
0 5 10 15 20
6
The while Looping (Repetition) Structure
Typically, while loops are written in the following form:
//initialize the loop control variable(s)
while (expression) //expression tests the LCV
{
.
.
.
//update the loop control variable(s)
.
.
.
}
7
Counter-Controlled while Loop
 Used when exact number of data or entry pieces is
known.
 General form:
int N = //value input by user or specified
//in program
int counter = 0;
while (counter < N)
{
.
.
.
counter++;
.
.
.
}
8
Sentinel-Controlled while Loop
 Used when exact number of entry pieces is unknown, but
last entry (special/sentinel value) is known.
 General form:
Input the first data item into variable;
while (variable != sentinel)
{
.
.
.
input a data item into variable;
.
.
.
}
9
Flag-Controlled while Loop
 Boolean value used to control loop.
 General form:
boolean found = false;
while (!found)
{
.
.
.
if (expression)
found = true;
.
.
.
}
10
EOF(End of File)-Controlled while Loop
 Used when input is from files.
 Sentinel value is not always appropriate.
 In an EOF-controlled while loop that uses the Scanner
object console to input data, console acts at the
loop control variable.
 The method hasNext, of the class Scanner,
returns true if there is an input in the input stream;
otherwise, it returns false.
 The expression console.hasNext() acts as the
loop condition.
 Expressions such as console.nextInt() update the
value of the loop condition.
11
EOF-Controlled while Loop
 A general form of the EOF-controlled while loop
that uses the Scanner object console to input
data is:
while (console.hasNext())
{
//Get the next input and store in an
//appropriate variable
//Process data
}
12
EOF-Controlled while Loop
 Suppose that inFile is a Scanner object
initialized to the input file. In this case, the EOF-
controlled while loop takes the following form:
while (inFile.hasNext())
{
//Get the next input and store in an
//appropriate variable
//Process data
}
13
Programming Example: Checking
Account Balance
 Input file: Customer’s account number, account
balance at beginning of month, transaction type
(withdrawal, deposit, interest), transaction amount.
 Output: Account number, beginning balance, ending
balance, total interest paid, total amount deposited,
number of deposits, total amount withdrawn,
number of withdrawals.
14
Programming Example: Checking
Account Balance
 Solution:
 Read data.
 EOF-controlled loop.
 switch structure of transaction types.
 Determine action (add to balance or subtract
from balance depending on transaction type).
15
Programming Example:
Fibonacci Number
 Fibonacci formula for any Fibonacci sequence:
an
= an-1
+ an-2
 Input: First two Fibonacci numbers in sequence,
position in sequence of desired Fibonacci number (n).
 int previous1 = Fibonacci number 1
 int previous2 = Fibonacci number 2
 int nthFibonacci = Position of nth Fibonacci number
 Output: nth Fibonacci number.
16
Programming Example: Fibonacci Number (Solution)
if (nthFibonacci == 1)
current = previous1;
else if (nthFibonacci == 2)
current = previous2;
else
{
counter = 3;
while (counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
}
17
The for Looping (Repetition) Structure
 Specialized form of while loop.
 Simplifies the writing of count-controlled loops.
 Syntax:
for (initial statement; loop condition;
update statement)
statement
18
The for Looping (Repetition) Structure
 Execution:
 Initial statement executes.
 Loop condition is evaluated.
 If loop condition evaluates to true, execute for
loop statement and execute update statement.
 Repeat until loop condition is false.
19
The for Looping (Repetition) Structure
Example 5-8
The following for loop prints the first 10
nonnegative integers:
for (i = 0; i < 10; i++)
System.out.print(i + " ");
System.out.println();
20
The for Looping (Repetition) Structure
Example 5-9
1. The following for loop outputs the word Hello and a star (on
separate lines) five times:
for (i = 1; i <= 5; i++)
{
System.out.println("Hello");
System.out.println("*");
}
2. The following for loop outputs the word Hello five times and the
star only once:
for (i = 1; i <= 5; i++)
System.out.println("Hello");
System.out.println("*");
21
The for Looping (Repetition) Structure
 Does not execute if initial condition is false.
 Update expression changes value of loop control
variable, eventually making it false.
 If loop condition is always true, result is an infinite
loop.
 Infinite loop can be specified by omitting all three
control statements.
 If loop condition is omitted, it is assumed to be
true.
 for statement ending in semicolon is empty.
22
Programming Example: Classify
Numbers
 Input: N integers (positive, negative, and zeros).
int N = 20; //N easily modified
 Output: Number of 0s, number of even integers,
number of odd integers.
23
Programming Example: Classify Numbers
(Solution)
for (counter = 1; counter <= N; counter++)
{
number = console.nextInt();
System.out.print(number + " ");
switch (number % 2)
{
case 0: evens++;
if (number == 0)
zeros++;
break;
case 1:
case -1: odds++;
} //end switch
} //end for loop
24
The do…while Loop (Repetition)
Structure
 Syntax:
do
statement
while (expression);
 Statements are executed first and then expression is
evaluated.
 Statements are executed at least once and then
continued if expression is true.
25
do…while Loop (Post-Test Loop)
26
break Statements
 Used to exit early from a loop.
 Used to skip remainder of switch structure.
 Can be placed within if statement of a loop.
 If condition is met, loop is exited immediately.
27
continue Statements
 Used in while, for, and do...while structures.
 When executed in a loop, the remaining statements
in the loop are skipped; proceeds with the next
iteration of the loop.
 When executed in a while/do…while structure,
expression is evaluated immediately after continue
statement.
 In a for structure, the update statement is executed
after the continue statement; the loop condition
then executes.
28
Nested Control Structures
 Provides new power, subtlety, and complexity.
 if, if…else, and switch structures can be
placed within while loops.
 for loops can be found within other for loops.
29
Nested Control Structures (Example)
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= i; j++)
System.out.print(" *");
System.out.println();
}
Output:
*
**
***
****
*****
30
Chapter Summary
 Looping mechanisms:
 Counter-controlled while loop
 Sentinel-controlled while loop
 Flag-controlled while loop
 EOF-controlled while loop
 for loop
 do…while loop
 break statements
 continue statements
 Nested control structures

More Related Content

What's hot

Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
Andy Juan Sarango Veliz
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
rajshreemuthiah
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
It Academy
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
Nurul Zakiah Zamri Tan
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
Ravi_Kant_Sahu
 
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
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
SHRIRANG PINJARKAR
 
Control statements
Control statementsControl statements
Control statements
Kanwalpreet Kaur
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
Kuppusamy P
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
Jayfee Ramos
 
Flow of control ppt
Flow of control pptFlow of control ppt
M C6java6
M C6java6M C6java6
M C6java6
mbruggen
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
Saad Sheikh
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
Tushar Jain
 
07 flow control
07   flow control07   flow control
07 flow control
dhrubo kayal
 
Program control statements in c#
Program control statements in c#Program control statements in c#
Program control statements in c#
Dr.Neeraj Kumar Pandey
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
Sokngim Sa
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
Sumit Satam
 

What's hot (20)

Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Control and conditional statements
Control and conditional statementsControl and conditional statements
Control and conditional statements
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
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++
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Control statements
Control statementsControl statements
Control statements
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
M C6java6
M C6java6M C6java6
M C6java6
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
07 flow control
07   flow control07   flow control
07 flow control
 
Program control statements in c#
Program control statements in c#Program control statements in c#
Program control statements in c#
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 

Viewers also liked

Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSE
Dominic Storey
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
Ahmad Idrees
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
Mohamed Loey
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
Ahmad Idrees
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
Ahmad Idrees
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
Ahmad Idrees
 
What is business
What is businessWhat is business
What is business
Ahmad 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
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
David Ware
 
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
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
Ahmad Idrees
 
C++ ppt
C++ pptC++ ppt
C++ ppt
Aneesh Gupta
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
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
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
Brian Thorne
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
MarkTaylorIBM
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
KurdGul
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
harman kaur
 

Viewers also liked (20)

Whats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSEWhats new in IIB v9 + Open Beta v10 GSE
Whats new in IIB v9 + Open Beta v10 GSE
 
Basic characteristics of business
Basic characteristics of businessBasic characteristics of business
Basic characteristics of business
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
System outputs - Computer System
System outputs - Computer SystemSystem outputs - Computer System
System outputs - Computer System
 
Effective writing, tips for Bloggers
Effective writing, tips for BloggersEffective writing, tips for Bloggers
Effective writing, tips for Bloggers
 
Principle of marketing
Principle of marketing Principle of marketing
Principle of marketing
 
What is business
What is businessWhat is business
What is 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
 
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CDWhats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
Whats new in IBM MQ; V9 LTS, V9.0.1 CD and V9.0.2 CD
 
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
 
Basic qualities of a good businessman
Basic qualities of a good businessmanBasic qualities of a good businessman
Basic qualities of a good businessman
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
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
 
Python in Computer Vision
Python in Computer VisionPython in Computer Vision
Python in Computer Vision
 
IBM MQ V9 Overview
IBM MQ V9 OverviewIBM MQ V9 Overview
IBM MQ V9 Overview
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 

Similar to Control structures ii

Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
Neeru Mittal
 
Chap05
Chap05Chap05
Chap05
Terry Yoast
 
Loops c++
Loops c++Loops c++
Loops c++
Shivani Singh
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
06.Loops
06.Loops06.Loops
06.Loops
Intro C# Book
 
PM1
PM1PM1
PM1
ra na
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
Sriman Sawarthia
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
Tanmay Modi
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
tanmaymodi4
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
JayBhavsar68
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
KirubelWondwoson1
 
06 Loops
06 Loops06 Loops
06 Loops
maznabili
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
Student
 
04a intro while
04a intro while04a intro while
04a intro while
hasfaa1017
 
Looping statements
Looping statementsLooping statements
Looping statements
Jaya Kumari
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
bluejayjunior
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
Jayfee Ramos
 
Ch05
Ch05Ch05
9781439035665 ppt ch05
9781439035665 ppt ch059781439035665 ppt ch05
9781439035665 ppt ch05
Terry Yoast
 

Similar to Control structures ii (20)

Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Chap05
Chap05Chap05
Chap05
 
Loops c++
Loops c++Loops c++
Loops c++
 
Iteration
IterationIteration
Iteration
 
06.Loops
06.Loops06.Loops
06.Loops
 
PM1
PM1PM1
PM1
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
 
06 Loops
06 Loops06 Loops
06 Loops
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
04a intro while
04a intro while04a intro while
04a intro while
 
Looping statements
Looping statementsLooping statements
Looping statements
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 
Ch05
Ch05Ch05
Ch05
 
9781439035665 ppt ch05
9781439035665 ppt ch059781439035665 ppt ch05
9781439035665 ppt ch05
 

More from 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
 
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
Ahmad Idrees
 

More from Ahmad Idrees (6)

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
 
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

B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
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
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
Krassimira Luka
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
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
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
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
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
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
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
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
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 

Recently uploaded (20)

B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
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
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Temple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation resultsTemple of Asclepius in Thrace. Excavation results
Temple of Asclepius in Thrace. Excavation results
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
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
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
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
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
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
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .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
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 

Control structures ii

  • 1. Chapter 5: Control StructuresChapter 5: Control Structures IIII JJavaava PProgramming:rogramming: From Problem Analysis to Program Design,From Problem Analysis to Program Design, Second EditionSecond Edition
  • 2. 2 Chapter Objectives  Learn about repetition (looping) control structures.  Explore how to construct and use count-controlled, sentinel-controlled, flag-controlled, and EOF- controlled repetition structures.  Examine break and continue statements.  Discover how to form and use nested control structures.
  • 3. 3 Why Is Repetition Needed?  There are many situations in which the same statements need to be executed several times.  Example:  Formulas used to find average grades for students in a class.
  • 4. 4 The while Looping (Repetition) Structure  Syntax: while (expression) statement  Expression is always true in an infinite loop.  Statements must change value of expression to false.
  • 5. 5 The while Looping (Repetition) Structure Example 5-1 i = 0; //Line 1 while (i <= 20) //Line 2 { System.out.print(i + " "); //Line 3 i = i + 5; //Line 4 } System.out.println(); //Line 5 Output 0 5 10 15 20
  • 6. 6 The while Looping (Repetition) Structure Typically, while loops are written in the following form: //initialize the loop control variable(s) while (expression) //expression tests the LCV { . . . //update the loop control variable(s) . . . }
  • 7. 7 Counter-Controlled while Loop  Used when exact number of data or entry pieces is known.  General form: int N = //value input by user or specified //in program int counter = 0; while (counter < N) { . . . counter++; . . . }
  • 8. 8 Sentinel-Controlled while Loop  Used when exact number of entry pieces is unknown, but last entry (special/sentinel value) is known.  General form: Input the first data item into variable; while (variable != sentinel) { . . . input a data item into variable; . . . }
  • 9. 9 Flag-Controlled while Loop  Boolean value used to control loop.  General form: boolean found = false; while (!found) { . . . if (expression) found = true; . . . }
  • 10. 10 EOF(End of File)-Controlled while Loop  Used when input is from files.  Sentinel value is not always appropriate.  In an EOF-controlled while loop that uses the Scanner object console to input data, console acts at the loop control variable.  The method hasNext, of the class Scanner, returns true if there is an input in the input stream; otherwise, it returns false.  The expression console.hasNext() acts as the loop condition.  Expressions such as console.nextInt() update the value of the loop condition.
  • 11. 11 EOF-Controlled while Loop  A general form of the EOF-controlled while loop that uses the Scanner object console to input data is: while (console.hasNext()) { //Get the next input and store in an //appropriate variable //Process data }
  • 12. 12 EOF-Controlled while Loop  Suppose that inFile is a Scanner object initialized to the input file. In this case, the EOF- controlled while loop takes the following form: while (inFile.hasNext()) { //Get the next input and store in an //appropriate variable //Process data }
  • 13. 13 Programming Example: Checking Account Balance  Input file: Customer’s account number, account balance at beginning of month, transaction type (withdrawal, deposit, interest), transaction amount.  Output: Account number, beginning balance, ending balance, total interest paid, total amount deposited, number of deposits, total amount withdrawn, number of withdrawals.
  • 14. 14 Programming Example: Checking Account Balance  Solution:  Read data.  EOF-controlled loop.  switch structure of transaction types.  Determine action (add to balance or subtract from balance depending on transaction type).
  • 15. 15 Programming Example: Fibonacci Number  Fibonacci formula for any Fibonacci sequence: an = an-1 + an-2  Input: First two Fibonacci numbers in sequence, position in sequence of desired Fibonacci number (n).  int previous1 = Fibonacci number 1  int previous2 = Fibonacci number 2  int nthFibonacci = Position of nth Fibonacci number  Output: nth Fibonacci number.
  • 16. 16 Programming Example: Fibonacci Number (Solution) if (nthFibonacci == 1) current = previous1; else if (nthFibonacci == 2) current = previous2; else { counter = 3; while (counter <= nthFibonacci) { current = previous2 + previous1; previous1 = previous2; previous2 = current; counter++; } }
  • 17. 17 The for Looping (Repetition) Structure  Specialized form of while loop.  Simplifies the writing of count-controlled loops.  Syntax: for (initial statement; loop condition; update statement) statement
  • 18. 18 The for Looping (Repetition) Structure  Execution:  Initial statement executes.  Loop condition is evaluated.  If loop condition evaluates to true, execute for loop statement and execute update statement.  Repeat until loop condition is false.
  • 19. 19 The for Looping (Repetition) Structure Example 5-8 The following for loop prints the first 10 nonnegative integers: for (i = 0; i < 10; i++) System.out.print(i + " "); System.out.println();
  • 20. 20 The for Looping (Repetition) Structure Example 5-9 1. The following for loop outputs the word Hello and a star (on separate lines) five times: for (i = 1; i <= 5; i++) { System.out.println("Hello"); System.out.println("*"); } 2. The following for loop outputs the word Hello five times and the star only once: for (i = 1; i <= 5; i++) System.out.println("Hello"); System.out.println("*");
  • 21. 21 The for Looping (Repetition) Structure  Does not execute if initial condition is false.  Update expression changes value of loop control variable, eventually making it false.  If loop condition is always true, result is an infinite loop.  Infinite loop can be specified by omitting all three control statements.  If loop condition is omitted, it is assumed to be true.  for statement ending in semicolon is empty.
  • 22. 22 Programming Example: Classify Numbers  Input: N integers (positive, negative, and zeros). int N = 20; //N easily modified  Output: Number of 0s, number of even integers, number of odd integers.
  • 23. 23 Programming Example: Classify Numbers (Solution) for (counter = 1; counter <= N; counter++) { number = console.nextInt(); System.out.print(number + " "); switch (number % 2) { case 0: evens++; if (number == 0) zeros++; break; case 1: case -1: odds++; } //end switch } //end for loop
  • 24. 24 The do…while Loop (Repetition) Structure  Syntax: do statement while (expression);  Statements are executed first and then expression is evaluated.  Statements are executed at least once and then continued if expression is true.
  • 26. 26 break Statements  Used to exit early from a loop.  Used to skip remainder of switch structure.  Can be placed within if statement of a loop.  If condition is met, loop is exited immediately.
  • 27. 27 continue Statements  Used in while, for, and do...while structures.  When executed in a loop, the remaining statements in the loop are skipped; proceeds with the next iteration of the loop.  When executed in a while/do…while structure, expression is evaluated immediately after continue statement.  In a for structure, the update statement is executed after the continue statement; the loop condition then executes.
  • 28. 28 Nested Control Structures  Provides new power, subtlety, and complexity.  if, if…else, and switch structures can be placed within while loops.  for loops can be found within other for loops.
  • 29. 29 Nested Control Structures (Example) for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) System.out.print(" *"); System.out.println(); } Output: * ** *** **** *****
  • 30. 30 Chapter Summary  Looping mechanisms:  Counter-controlled while loop  Sentinel-controlled while loop  Flag-controlled while loop  EOF-controlled while loop  for loop  do…while loop  break statements  continue statements  Nested control structures