zuai-logo

What is the purpose of an 'else' statement?

To provide an alternative block of code to execute when the 'if' condition is false.

Flip to see [answer/question]
Flip to see [answer/question]

All Flashcards

What is the purpose of an 'else' statement?

To provide an alternative block of code to execute when the 'if' condition is false.

Why are curly braces {} important in if-else statements?

They define the code blocks for both the 'if' and 'else' parts, ensuring correct execution.

Explain the flow of execution in an if-else statement.

The condition is evaluated. If true, the 'if' block executes. If false, the 'else' block executes.

Why is indentation important in if-else statements?

Improves code readability and helps visually identify code blocks.

What is the output of the following code?

java
int x = 7;
if (x % 2 == 0) {
 System.out.print("Even");
} else {
 System.out.print("Odd");
}

Odd

What is the output of the following code?

java
int y = 12;
if (y > 10) {
 System.out.print("Greater");
} else {
 System.out.print("Less");
}

Greater

Identify the error in the following code:

java
int age = 17;
if (age >= 18)
 System.out.print("Adult");
else
 System.out.print("Minor");

Missing curly braces {} to define the code blocks for 'if' and 'else'.

What is the output of the following code?

java
int num = -5;
if (num > 0) {
 System.out.print("Positive");
} else {
 System.out.print("Not Positive");
}

Not Positive

Complete the code to check if a number is positive or negative.

java
int number = ...;
if (number > 0) {
 System.out.print("Positive");
} else {
 // Complete this part
}
java
System.out.print("Negative or Zero");

What is the output of the following code snippet?

java
int x = 5;
if (x > 10) {
  System.out.print("A");
} else {
  System.out.print("B");
}

B

Identify the error in the following code:

java
int age = 20
if (age > 18) {
 System.out.println("Adult");
} else {
 System.out.println("Not adult");
}

Missing semicolon at the end of the first line. (int age = 20;)

What is the output of the following code?

java
int a = 10;
int b = 5;
if (a < b) {
 System.out.println("a is less than b");
} else {
 System.out.println("a is not less than b");
}

a is not less than b

What is the output of the following code?

java
int number = 7;
if (number % 2 == 0) {
 System.out.println("Even");
} else {
 System.out.println("Odd");
}

Odd

What is the output of the following code?

java
int num = 15;
if (num > 10) {
 System.out.println("Greater than 10");
} else {
 System.out.println("Less than or equal to 10");
}

Greater than 10

What are the basic steps for executing an if-else statement?

  1. Evaluate the condition. 2. If true, execute the 'if' block. 3. If false, execute the 'else' block.