Day 3 and 4
Day 3 and 4
Control structures allow you to dictate the flow of execution in a program. Java provides
various control structures to help make decisions, iterate through data, and manage
conditions.
The if statement allows a block of code to be executed only if a specific condition is true.
Syntax:
if (condition) {
Example:
if-else Statement
The if-else statement executes one block of code if the condition is true, and another block
if it is false.
Syntax:
if (condition) {
} else {
}
Example:
} else {
else-if Ladder
Syntax:
if (condition1) {
} else if (condition2) {
} else {
Example:
System.out.println("Grade A");
System.out.println("Grade B");
System.out.println("Grade C");
} else {
System.out.println("Grade D");
}
switch Statement
The switch statement tests a variable against a set of values (called cases) and executes the
block of code corresponding to the matching case.
Syntax:
switch (variable) {
case value1:
break;
case value2:
break;
default:
Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
3. Loops in Java
for Loop
The for loop is used when the number of iterations is known beforehand.
Syntax:
// code to be executed
Example:
System.out.println(i); // Outputs 1 2 3 4 5
Explanation:
while Loop
The while loop repeats the block of code as long as the condition is true. It is used when the
number of iterations is not known beforehand.
Syntax:
while (condition) {
// code to be executed
Example:
int i = 1;
while (i <= 5) {
System.out.println(i); // Outputs 1 2 3 4 5
i++;
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the code block will be
executed at least once, even if the condition is false.
Syntax:
do {
// code to be executed
} while (condition);
Example:
int i = 1;
do {
System.out.println(i); // Outputs 1 2 3 4 5
i++;
The break statement is used to exit a loop or switch statement immediately, even if the
loop's condition has not been met.
Example:
if (i == 6) {
}
System.out.println(i); // Outputs 1 2 3 4 5
continue Statement
The continue statement is used to skip the current iteration of a loop and move on to the
next iteration.
Example:
if (i == 6) {
System.out.println(i); // Outputs 1 2 3 4 5 7 8 9 10
Java allows you to pass arguments to your program through the command line. These
arguments are stored in the String[] args parameter of the main method.
Example:
if (args.length > 0) {
} else {
}
To run the program with an argument, use the following command:
import java.util.Scanner;
if (num % 2 == 0) {
} else {
import java.util.Scanner;
public class Calculator {
switch (operator) {
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
if (num2 != 0) {
} else {
break;
default:
System.out.println("Invalid operator.");
}
import java.util.Scanner;
int factorial = 1;
int i = 1;
factorial *= i;
i++;