Week4 Lecture 83665
Week4 Lecture 83665
Lecture 4
Sushil Paudel
erspaudel 1
LAST WEEK
erspaudel 2
TODAY’S TOPIC
• Control Statement Loop
erspaudel 3
REPEAT
erspaudel 4
CONTROL STATEMENT - LOOPS
• Loops are what makes computers interesting machines. Imagine you need to print a
sentence 50 times on your screen.
• Well, you can do it by using print statement 50 times (without using loops).
erspaudel 5
LOOP
6
TYPES OF LOOPS
• for loop
• while loop
• do-while loop
erspaudel 7
FOR LOOP
• The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
erspaudel 8
SIMPLE FOR LOOP
• Initialization: It is the initial condition which is executed once when the loop starts.
• Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false.
• Statement: Codes which are executed till the conditions are true
erspaudel 9
EXAMPLE
erspaudel 10
OUTPUT
1
2
3
4
5
6
7
8
9
10
erspaudel 11
erspaudel 12
EXAMPLE
erspaudel 13
OUTPUT
10
9
8
7
6
5
4
3
2
1
0
erspaudel 14
FOR-EACH LOOP
Syntax
erspaudel 15
FOR EACH LOOP EXAMPLE
erspaudel 16
USABLE VS REUSABLE
erspaudel 17
WHILE LOOP
Syntax
while(Boolean_expression) {
// Statements
erspaudel 18
WHILE LOOP EXAMPLE
erspaudel 19
OUTPUT
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
erspaudel 20
erspaudel 21
READ DOCUMENTATION
erspaudel 22
DO WHILE LOOP
• The Java do-while loop is executed at least once because condition is checked after
loop body.
• do while loop in Java is similar to while loop except that the condition is checked
after the statements are executed, so do while loop guarantees the loop execution
at least once.
erspaudel 23
DO WHILE SYNTAX
do{
//code to be executed
}while(condition);
erspaudel 24
DO WHILE EXAMPLE
erspaudel 25
OUTPUT
1
2
3
4
5
6
7
8
9
10
erspaudel 26
DO WHILE EXAMPLE
erspaudel 27
OUTPUT
99
erspaudel 28
WHILE VS DO WHILE
erspaudel 29
BREAK IN LOOP
• When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
erspaudel 30
BREAK IN LOOP EXAMPLE
erspaudel 31
OUTPUT
1
2
erspaudel 32
BREAK
erspaudel 33
CONTINUE
• Continue statement is mostly used inside loops.
• This is particularly useful when you want to continue the loop but do not want the
rest of the statements(after continue statement) in loop body to execute for that
particular iteration.
erspaudel 34
EXAMPLE
erspaudel 35
OUTPUT
1
3
4
9
10
erspaudel 36
CONTINUE
erspaudel 37
HEY, SOMEONE STOP THE LOOP!
erspaudel 38
END OF LECTURE 5
Any questions?
erspaudel 39