Part 03 - Java Basics 3 - Flow Control_2025
Part 03 - Java Basics 3 - Flow Control_2025
do {
statement(s)
} while (expression);
statement
condition
true
true false
condition
statement
false
GCD( a − b, b), if a b
GCD( a, b) = GCD( a, b − a ), if a b
a, if a = b
int a = 15;
int b = 6;
while (a != b){
if (a > b) a = a - b;
else if (a < b) b = b - a;
}
System.out.println("GCD is " + a);
// 3
forInit forInit;
while ( condition )
condition {
statement;
true false forUpdate;
statement
}
int n = 10;
long s = 1;
for (int i = 1; i <= n; i++){
s *= i;
}
System.out.println("Factorial is " + s);
condition condition
if (expression) {
statement1(s)
if (expression) {
} else {
statement(s)
statement2(s)
}
}
Khoa CNTT – Trường ĐH Nông Lâm TP. HCM
Example for if-else statement
public class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
int max;
if (x > y) {
max = x; VS. max = (x > y) ? x : y;
} else {
max = y;
}
21
Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 21/48
Switch statement
switch ( value )
{
case value_1 :
statement_list_1
case value_2 :
statement_list_2
case value_3 :
statement_list_3
default: ...
}
Use the switch statement to conditionally perform
statements based on an integer expression or
enumerated type (byte, short, char, and int
primitive data types )
switch (month) {
case JANUARY:
case MARCH:
case MAY:
case JULY:
case AUGUST:
case OCTOBER:
case DECEMBER:
numDays = 31;
break;
Java Basic Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2016 29 29/48
The break Statements
The break statement has two forms:
◼ unlabeled form: The unlabeled form of the break
statement was used with switch earlier. As noted
there, an unlabeled break terminates the enclosing
switch statement, and flow of control transfers to the
statement immediately following the switch. That is
mean unlabeled break terminates the enclosing loop.
The unlabeled form of the break statement is used to
terminate the innermost switch, for, while, or do-
while statement;
◼ labeled form: the labeled form terminates an outer
statement, which is identified by the label specified in
the break statement.
//process p's
numPs++;
searchMe.setCharAt(i, 'P');
}
System.out.println("Found " + numPs
+ " p's in the string.");
System.out.println(searchMe);
}
Khoa CNTT – Trường ĐH Nông Lâm TP. HCM
The result of mentioned example
peter piper picked a peck of pickled peppers
Found 9 p's in the string.
Peter PiPer Picked a Peck of Pickled PePPers