Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Statements (Loop)
structure
“I will do my
homework!!”
Input example: 2 3 4 5 6
Output example: 20
TMK 3102-Chap 8: Control 5
Statement (Loop)
Why we need loop? (2)
start ..
..
Input n1 .
Input n2 n1 = in.nextInt();
n2 = in.nextInt();
Input n3 n3 = in.nextInt);
n4 = in.nextInt();
input n4
n5 = in.nextInt();
input n5 sum = n1+n2+n3+n4+n5
System.out.println(“
sum ← n1+n2+n3+n4+n5 Sum=“+sum);
output sum
end
6
TMK 3102-Chap 8: Control 6
Statement (Loop)
Why we need loop? (2)
start ..
..
Input n1 .
Input n2 n1 = in.nextInt();
n2 = in.nextInt();
Input n3 n3 = in.nextInt);
n4 = in.nextInt();
input n4
n5 = in.nextInt();
input n5 sum = n1+n2+n3+n4+n5
System.out.println(“
sum ← n1+n2+n3+n4+n5 Sum=“+sum);
HOW if number of
output sum input is more than
1000?
end
7
TMK 3102-Chap 8: Control 7
Statement (Loop)
loop statements
Change the program flow by execute a
block of statements repeatedly
while loop
for loop
do.while loop
Loop Flow Control : break and continue
while (condition)
statement; false
condition
or true
ctr = 0;
while (ctr == 5){
System.out.printf(“ctr : %d”,ctr);
ctr++;
}
OR
for (initial value ; condition; update counter) {
statement;
statement;
}
increase counter
increase counter
int sum=0;
int val = 0; Initial value
for (i=1; i<=3; i++){
System.out.print(“Value false
“+i +”:”);
condition
val = in.nextInt();
sum=sum+val; true
} Statement(s)
System.out.println(“Sum
:”+ sum);
increase counter
num =0;
for (i=0;i>10;i++){
num += i;
System.out.println(i + “ “
+ num);
}
num =0;
for (i=9;i>=0;i--) {
num = num + 10 * (i -1)
System.out.print(num + “ “);
}
System.out.println();
*
**
***
****
*****
whileloop: // label
while( condition) {
forloop: //label
for(i=0;i<10;i++)
}
TMK 3102-Chap 8: Control 40
40 Statement (Loop)
continue and break with label
import java.util.Scanner;
public class labelexample {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
whileloop:
while (true){
forloop:
for(int i = 0; i < 100; i++) {
int c = console.nextInt();
if (c == 1)
continue whileloop;
else if ( c == 2)
break forloop;
else
System.out.println(c);
}
System.out.println(">");
}
}
} TMK 3102-Chap 8: Control 41
Statement (Loop)
Thank You