In low level design, control structures like loops and conditionals are crucial for managing the flow of execution in a program.
Loops: Loops are used to repeat a set of instructions multiple times. They allow us to iterate over a collection of elements or perform a specific action until a certain condition is met. In Java, one common loop structure is the for
loop. Here's an example of a for
loop that prints numbers from 1 to 100:
1for(int i = 1; i <= 100; i++) {
2 System.out.println(i);
3}
Conditionals: Conditionals are used to execute different blocks of code based on certain conditions. They allow us to make decisions and control the flow of execution. In Java, one common conditional structure is the if-else
statement. Here's an example of an if-else
statement that checks if a number is divisible by 3, 5, or both and prints the corresponding message:
1int num = 15;
2
3if (num % 3 == 0 && num % 5 == 0) {
4 System.out.println("FizzBuzz");
5} else if (num % 3 == 0) {
6 System.out.println("Fizz");
7} else if (num % 5 == 0) {
8 System.out.println("Buzz");
9} else {
10 System.out.println(num);
11}
By effectively designing control structures, you can create programs that execute the desired actions and produce the expected results.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
// replace with your Java logic here
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if(i % 3 == 0) {
System.out.println("Fizz");
} else if(i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
}