SlideShare a Scribd company logo
1 of 29
Control Structure
Repetition
Outlines
 Repetition Statements
 while statement
 do..while statement
 for statement
 Nested loops
 Repetition Control Structures
Repetition Statements
 Repetition statement (or loop) a block of code to be
executed for a fixed number of times or until a certain
condition is met.
 In JAVA, repetition can be done by using the
following repetition statements:
a) while
b) do…while
c) for
The while statement
 The while statement evaluates
expression/condition, which must return a boolean
value. If the expression/condition is true, the
statement(s) in the while block is/are executed.
 Syntax:
while (expression/condition)
Statement(s);
 It continues testing the expression/condition and
executing its block until the expression/condition
evaluates to false
The while statement
Output ? 1 2 3 4
Example 1
int i=1;
while (i<5){
System.out.print(i + “”);
i++;
}
Output ? SUM : 1
SUM : 7
Good Bye
Example 2
int sum=0, number =1;
while (number <= 10)
{
sum+=number;
number = number + 5;
System.out.println(“SUM :” + sum);
}
System.out.println(“Good Bye”);
The do…while statement
 It is similar to while loops except it first executes the
statement(s) inside the loop, and then evaluates the
expression/condition. If the expression is true, the
statement(s) in the do loop is/are executed again.
 Syntax
do
statement(s);
while (expression);
 It continues executing the statement until the
expression/condition becomes false.
 Note that the statement within the do loop is always
executed at least once.
The do…while statement
Output ? 0 1 2 3
Example 3
int i=0;
do{
System.out.print(i +
“”);
i++;
}while(i<=3);
Output ? SUM : 2
SUM : 9
Example 4
int sum=0, number =2;
do{
sum+=number;
number = number + 5;
System.out.println(“SUM :” + sum);
} while (number <= 10);
The for statement
 Usually used when a loop will be executed a set
number of times.
 Syntax:
for(initial statement; loop condition; update statement)
statement(s);
 The for loop executes as follow:
1) The initial statement is executed.
2) The loop expression/condition is evaluated. If it is
TRUE, the loop statement is executed followed by the
execution of the update statement
3) Repeat step 2) until the loop condition evaluates to
FALSE.
The for statement
Output ? 1 2 3 4
Example 5
for (i=1; i<5; i++)
System.out.print(i);
Output ? YAHOO ***YAHOO ***
Example 6
for (i=1; i<3; i++){
System.out.print(“YAHOO” + “”);
System.out.print(“***”);
}
Output ? YAHOO YAHOO YAHOO YAHOO YAHOO ***
Example 7
for (i=1; i<=5; i++)
System.out.print(“YAHOO”);
System.out.print(“***”);
Nested Loops
 The placing of one loop inside the body of
another loop is called nesting.
 When you "nest" two loops, the outer loop
takes control of the number of complete
repetitions of the inner loop.
 While all types of loops may be nested, the
most commonly nested loops are for loops.
Nested for Loops
 When working with nested loops, the outer loop
changes only after the inner loop is completely
finished (or is interrupted.).
Example 8
int num1, num2;
for(num2 = 0; num2 <= 2; num2++)
{
for(num1 = 0; num1 <= 1; num1++)
{
System.out.println(num2 + " " + num1);
}
}
Output ?
0 0
0 1
1 0
1 1
2 0
2 1
Infinite Loop
 By using any repetition statements, make sure that
the loop will eventually terminate.
 An infinite loop occurs when a condition always
evaluates to true and continues to execute endlessly.
int product =0;
for (product = 0;product < 10;)
{ product = product * 2;
System.out.println(product);
}
Repetition Control Structures
Repetition can be controlled by:
 Counter controlled loop
 Sentinel controlled loop
 Flag controlled loop
Exercise
Counter Controlled Loop
 Know exactly how many times a set of statements
needs to be executed.
Output ? 1 3 5 7 9
int num =1;
while (num < 10)
{
System.out.print (num);
num = num +2;
}
Example 10:
back
Sentinel Controlled Loop
 You might not know exactly how many times a set of
statements needs to be executed.
 It uses a "special" or sentinel value to indicate that the
loop is to end.
 This must be a value that doesn't occur normally in
the data.
Example 11 (complete program)
import java.util.Scanner;
class sentinelLoop {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an Integer, or -1 to stop: ");
int choice= input.nextInt();
while (choice!=-1)
{
System.out.println("INSIDE LOOPING");
System.out.print("Enter an Integer, or -1 to stop: ");
choice= input.nextInt();
}
System.out.println("Sentinel value detected. Good Bye.");
}
}
Example 11 ….
Enter an Integer, or -1 to stop: 2
INSIDE LOOPING
Enter an Integer, or -1 to stop: 5
INSIDE LOOPING
Enter an Integer, or -1 to stop: 0
INSIDE LOOPING
Enter an Integer, or -1 to stop: -1
Sentinel value detected. Good Bye.
OUTPUT?
back
Flag Controlled Loop
 Use a boolean variable to control the loop
boolean found = false;
while (!found){
:
:
if(expression)
found = true;
}
back
Exercise 1:
What is the output of the following program?
public class LoopExercise1
{
public static void main (String args[])
{
int choice=1, total=0;
while (choice <4){
total = choice++;
System.out.print(total); }
}
}
Exercise 2:
What is the output of the following program?
public class LoopExercise2
{
public static void main (String args[]){
for (int number =2; number <20; number++)
{
number = number *2;
if (number <15)
System.out.println(number);}
}
}
Exercise 3:
How many times is the following loop body repeated?
public class LoopExercise3 {
public static void main (String args[])
{
int i=1;
do {
if ((i % 2)== 0)
System.out.print(i);
i++;
} while(i<5);
}
}

More Related Content

What's hot

10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While LoopAbhishek Choksi
 
Conditional Statement in C#
Conditional Statement in C#Conditional Statement in C#
Conditional Statement in C#Simplilearn
 
Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++amber chaudary
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Control statements
Control statementsControl statements
Control statementsraksharao
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#Prasanna Kumar SM
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c languagetanmaymodi4
 
If else statement in c++
If else statement in c++If else statement in c++
If else statement in c++Bishal Sharma
 
TOC(CS-501) (19-49).pdf
TOC(CS-501) (19-49).pdfTOC(CS-501) (19-49).pdf
TOC(CS-501) (19-49).pdfRajJain516913
 

What's hot (20)

10. switch case
10. switch case10. switch case
10. switch case
 
While , For , Do-While Loop
While , For , Do-While LoopWhile , For , Do-While Loop
While , For , Do-While Loop
 
Conditional Statement in C#
Conditional Statement in C#Conditional Statement in C#
Conditional Statement in C#
 
Loops in C
Loops in CLoops in C
Loops in C
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Interface
InterfaceInterface
Interface
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Control statements
Control statementsControl statements
Control statements
 
Control structure
Control structureControl structure
Control structure
 
Decision making and loop in C#
Decision making and loop in C#Decision making and loop in C#
Decision making and loop in C#
 
Switch statement
Switch statementSwitch statement
Switch statement
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Decision statements in c language
Decision statements in c languageDecision statements in c language
Decision statements in c language
 
If else statement in c++
If else statement in c++If else statement in c++
If else statement in c++
 
TOC(CS-501) (19-49).pdf
TOC(CS-501) (19-49).pdfTOC(CS-501) (19-49).pdf
TOC(CS-501) (19-49).pdf
 

Similar to Repetition Structure

control statements
control statementscontrol statements
control statementsAzeem Sultan
 
Chapter 5.2
Chapter 5.2Chapter 5.2
Chapter 5.2sotlsoc
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingPathomchon Sriwilairit
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statementmanish kumar
 
Chapter 5.3
Chapter 5.3Chapter 5.3
Chapter 5.3sotlsoc
 
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 workingNeeru Mittal
 
Chapter 5.1
Chapter 5.1Chapter 5.1
Chapter 5.1sotlsoc
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 

Similar to Repetition Structure (20)

07 flow control
07   flow control07   flow control
07 flow control
 
control statements
control statementscontrol statements
control statements
 
Chapter 5.2
Chapter 5.2Chapter 5.2
Chapter 5.2
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
C++ loop
C++ loop C++ loop
C++ loop
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Loops
LoopsLoops
Loops
 
Chapter 5.3
Chapter 5.3Chapter 5.3
Chapter 5.3
 
M C6java6
M C6java6M C6java6
M C6java6
 
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
 
Chapter 5.1
Chapter 5.1Chapter 5.1
Chapter 5.1
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Control structures
Control structuresControl structures
Control structures
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 

More from PRN USM

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

More from PRN USM (19)

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

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
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
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
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
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 

Repetition Structure

  • 2. Outlines  Repetition Statements  while statement  do..while statement  for statement  Nested loops  Repetition Control Structures
  • 3. Repetition Statements  Repetition statement (or loop) a block of code to be executed for a fixed number of times or until a certain condition is met.  In JAVA, repetition can be done by using the following repetition statements: a) while b) do…while c) for
  • 4. The while statement  The while statement evaluates expression/condition, which must return a boolean value. If the expression/condition is true, the statement(s) in the while block is/are executed.  Syntax: while (expression/condition) Statement(s);  It continues testing the expression/condition and executing its block until the expression/condition evaluates to false
  • 6. Output ? 1 2 3 4 Example 1 int i=1; while (i<5){ System.out.print(i + “”); i++; }
  • 7. Output ? SUM : 1 SUM : 7 Good Bye Example 2 int sum=0, number =1; while (number <= 10) { sum+=number; number = number + 5; System.out.println(“SUM :” + sum); } System.out.println(“Good Bye”);
  • 8. The do…while statement  It is similar to while loops except it first executes the statement(s) inside the loop, and then evaluates the expression/condition. If the expression is true, the statement(s) in the do loop is/are executed again.  Syntax do statement(s); while (expression);  It continues executing the statement until the expression/condition becomes false.  Note that the statement within the do loop is always executed at least once.
  • 10. Output ? 0 1 2 3 Example 3 int i=0; do{ System.out.print(i + “”); i++; }while(i<=3);
  • 11. Output ? SUM : 2 SUM : 9 Example 4 int sum=0, number =2; do{ sum+=number; number = number + 5; System.out.println(“SUM :” + sum); } while (number <= 10);
  • 12. The for statement  Usually used when a loop will be executed a set number of times.  Syntax: for(initial statement; loop condition; update statement) statement(s);  The for loop executes as follow: 1) The initial statement is executed. 2) The loop expression/condition is evaluated. If it is TRUE, the loop statement is executed followed by the execution of the update statement 3) Repeat step 2) until the loop condition evaluates to FALSE.
  • 14. Output ? 1 2 3 4 Example 5 for (i=1; i<5; i++) System.out.print(i);
  • 15. Output ? YAHOO ***YAHOO *** Example 6 for (i=1; i<3; i++){ System.out.print(“YAHOO” + “”); System.out.print(“***”); }
  • 16. Output ? YAHOO YAHOO YAHOO YAHOO YAHOO *** Example 7 for (i=1; i<=5; i++) System.out.print(“YAHOO”); System.out.print(“***”);
  • 17. Nested Loops  The placing of one loop inside the body of another loop is called nesting.  When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop.  While all types of loops may be nested, the most commonly nested loops are for loops.
  • 18. Nested for Loops  When working with nested loops, the outer loop changes only after the inner loop is completely finished (or is interrupted.).
  • 19. Example 8 int num1, num2; for(num2 = 0; num2 <= 2; num2++) { for(num1 = 0; num1 <= 1; num1++) { System.out.println(num2 + " " + num1); } } Output ? 0 0 0 1 1 0 1 1 2 0 2 1
  • 20. Infinite Loop  By using any repetition statements, make sure that the loop will eventually terminate.  An infinite loop occurs when a condition always evaluates to true and continues to execute endlessly. int product =0; for (product = 0;product < 10;) { product = product * 2; System.out.println(product); }
  • 21. Repetition Control Structures Repetition can be controlled by:  Counter controlled loop  Sentinel controlled loop  Flag controlled loop Exercise
  • 22. Counter Controlled Loop  Know exactly how many times a set of statements needs to be executed. Output ? 1 3 5 7 9 int num =1; while (num < 10) { System.out.print (num); num = num +2; } Example 10: back
  • 23. Sentinel Controlled Loop  You might not know exactly how many times a set of statements needs to be executed.  It uses a "special" or sentinel value to indicate that the loop is to end.  This must be a value that doesn't occur normally in the data.
  • 24. Example 11 (complete program) import java.util.Scanner; class sentinelLoop { public static void main (String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an Integer, or -1 to stop: "); int choice= input.nextInt(); while (choice!=-1) { System.out.println("INSIDE LOOPING"); System.out.print("Enter an Integer, or -1 to stop: "); choice= input.nextInt(); } System.out.println("Sentinel value detected. Good Bye."); } }
  • 25. Example 11 …. Enter an Integer, or -1 to stop: 2 INSIDE LOOPING Enter an Integer, or -1 to stop: 5 INSIDE LOOPING Enter an Integer, or -1 to stop: 0 INSIDE LOOPING Enter an Integer, or -1 to stop: -1 Sentinel value detected. Good Bye. OUTPUT? back
  • 26. Flag Controlled Loop  Use a boolean variable to control the loop boolean found = false; while (!found){ : : if(expression) found = true; } back
  • 27. Exercise 1: What is the output of the following program? public class LoopExercise1 { public static void main (String args[]) { int choice=1, total=0; while (choice <4){ total = choice++; System.out.print(total); } } }
  • 28. Exercise 2: What is the output of the following program? public class LoopExercise2 { public static void main (String args[]){ for (int number =2; number <20; number++) { number = number *2; if (number <15) System.out.println(number);} } }
  • 29. Exercise 3: How many times is the following loop body repeated? public class LoopExercise3 { public static void main (String args[]) { int i=1; do { if ((i % 2)== 0) System.out.print(i); i++; } while(i<5); } }