Java Program Control Flow: Explained with Simple Examples
Program control flow refers to the order in which instructions in a Java program are executed. It determines the program's execution path and logic.
A. Sequence Structure
The sequence structure is the most basic structure in programming. Instructions are executed one after the other in a sequential order.
Example:
int num1 = 5;
int num2 = 10;
int sum = num1 + num2;
System.out.println('The sum is ' + sum);
In this example, the instructions are executed sequentially. First, num1 is assigned the value 5, then num2 is assigned 10. Next, the sum of num1 and num2 is calculated and stored in sum. Finally, the message 'The sum is' along with the value of sum is printed to the console.
B. Selection Structure
The selection structure allows a program to make decisions based on a condition. It uses the if statement to check a condition and execute a specific block of code if the condition is true.
Example:
int num = 10;
if (num > 5) {
System.out.println('The number is greater than 5');
}
In this example, the program checks if num is greater than 5 using the if statement. Since the condition is true (10 is greater than 5), the message 'The number is greater than 5' is printed to the console.
C. Repetition Structure
The repetition structure, also known as a loop, allows a program to repeat a block of code multiple times based on a condition. It ensures that a section of code is executed repeatedly until a specific condition is met.
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
This example uses a while loop to print numbers from 1 to 5 to the console. The loop executes as long as the value of i is less than or equal to 5. In each iteration, the value of i is incremented by 1.
D. Jump (Sequence) Structure
Jump structures allow a program to transfer control to a different part of the program, altering the normal sequential execution flow. Statements like break and continue are used to interrupt the normal flow of the program.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
In this example, the break statement is used to exit the loop when the value of i is equal to 5. This interrupts the normal flow and transfers control to the next statement after the loop. Numbers from 1 to 4 are printed to the console before the loop is interrupted.
原文地址: https://www.cveoy.top/t/topic/mpO0 著作权归作者所有。请勿转载和采集!