Lorem ipsum dolor sit amet, consectetur adipiscing elit. Test link

Control Flow Statements

A. Conditional Statements:

  1. if statement: The if statement is a conditional statement used to execute a block of code if a condition is true.

Example:

int num = 10;
if (num > 0) {
    System.out.println("Number is positive");
}
  1. switch statement: The switch statement allows a program to evaluate an expression and execute code based on the value of the expression.

Example:

int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Invalid day");
        break;
}

B. Looping Statements:

  1. for loop: The for loop is a control flow statement that allows a block of code to be executed repeatedly.

Example:

for (int i = 1; i <= 5; i++) {
    System.out.println("Count is: " + i);
}
  1. while loop: The while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.

Example:

int i = 1;
while (i <= 5) {
    System.out.println("Count is: " + i);
    i++;
}
  1. do-while loop: The do-while loop is similar to the while loop, but the block of code is executed at least once, even if the condition is false.

Example:

int i = 1;
do {
    System.out.println("Count is: " + i);
    i++;
} while (i <= 5);

C. Jump Statements:

  1. break statement: The break statement is used to terminate the current loop or switch statement.

Example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    System.out.println("Count is: " + i);
}
  1. continue statement: The continue statement is used to skip the current iteration of a loop and continue with the next iteration.

Example:

for (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.out.println("Count is: " + i);
}
  1. return statement: The return statement is used to exit a method and return a value to the caller.

Example:

public int add(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

Post a Comment