If Statements and Loops in Java
If statements and loops are fundamental control structures in Java that allow you to control the flow of your program.
If Statements
An if statement lets you execute a block of code only if a specified condition is true.
Syntax:
``java`
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Loops
Loops allow you to repeat a block of code multiple times. The most common types are for loops and while loops.
- For loop: Used when you know how many times to repeat.
- While loop: Used when you want to repeat as long as a condition is true.
- The loop variable $i$ starts at 1 and increases by 1 until it reaches 10.
- The condition $i % 2 == 0$ checks if $i$ is divisible by 2 (even).
- If true, $i$ is printed.
- If statements execute code only when a condition is true.
- Loops repeat code multiple times, either for a set number of iterations (for loop) or while a condition holds (while loop).
- Combining if statements and loops allows for powerful, flexible program logic.
For loop syntax:
`java`
for (initialization; condition; update) {
// code to repeat
}
While loop syntax:
`java`
while (condition) {
// code to repeat
}
Worked Example
Problem: Print all even numbers from 1 to 10.
Step 1: Use a for loop to iterate from 1 to 10.
Step 2: Use an if statement to check if the number is even.
Java code:
`java``
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
Explanation: