Control Statements
Control statements are used to control the flow of execution in a
program based on conditions or loops. These are mainly divided into:
1. Selection Statements
Used to select and execute one block of code among multiple options.
🔹 if Statement
Definition: Executes a block of code if the given condition is true.
Syntax:
if (condition) {
// statements
}
Example:
int num = 10;
if (num > 5) {
[Link]("Number is greater than 5");
}
🔹 if-else Statement
Definition: Executes one block if the condition is true, another block
if false.
Syntax:
if (condition) {
// true block
} else {
// false block
}
Example:
int num = 3;
if (num % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}
🔹 nested if-else Statement
Definition: An if-else inside another if-else.
Syntax:
if (condition1) {
// block 1
} else {
if (condition2) {
// block 2
} else {
// block 3
}
}
Example:
int marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else {
if (marks >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
}
2. Iteration Statements (Loops)
Used to execute a block repeatedly.
🔹 while Loop
Definition: Executes as long as the condition is true. Condition is
checked before the loop.
Syntax:
while (condition) {
// loop body
}
Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
🔹 do-while Loop
Definition: Similar to while, but checks the condition after executing
the loop at least once.
Syntax:
do {
// loop body
} while (condition);
Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
🔹 for Loop
Definition: Used when the number of iterations is known.
Syntax:
for (initialization; condition; update) {
// loop body
}
Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}
🔹 for-each Loop
Definition: Used to iterate over elements in arrays or collections.
Syntax:
for (type var : array) {
// loop body
}
Example:
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
[Link](num);
}
3. Jump Statements
🔹 break Statement
Definition: Terminates the loop or switch statement prematurely.
Syntax:
break;
Example:
java
CopyEdit
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
[Link](i);
}
// Output: 1 2
🔹 continue Statement
Definition: Skips the current iteration and continues with the next
iteration of the loop.
Syntax:
continue;
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
[Link](i);
}
// Output: 1 2 4 5