Nested if and Multi-Way if-else Statements
Nested if and Multi-Way if-else Statements:
An if statement can be nested inside another if statement, forming a nested if statement. This allows for more complex decision-making in a program.
In a nested if statement, an if statement is placed inside another if statement. The inner if statement is considered to be nested within the outer if statement. There is no limit to the depth of nesting and an inner if statement can also contain another if statement.
Here is an example of a nested if statement:
- if (i > k) {
- if (j > k)
- System.out.println("i and j are greater than k");
- }
- else {
- System.out.println("i is less than or equal to k");
- }
In this example, the inner if statement `if (j > k)` is nested inside the outer if statement `if (i > k)`. This allows for different actions to be taken based on multiple conditions.
A nested if statement can be used to implement multiple alternatives. Figure-1a shows an example of an if statement with multiple conditions to determine a letter grade based on a score.
The execution of a nested if statement proceeds by testing each condition in order. If a condition evaluates to true, the corresponding action is taken, and the rest of the conditions are skipped. If all of the conditions evaluate to false, the final else block is executed.
It is important to note that a condition is tested only when all the preceding conditions are false. This ensures that only one action is performed based on the first condition that evaluates to true, and the subsequent conditions are not checked.
The execution of this if statement proceeds as shown in Figure-2. The first condition (score >= 90.0) is tested. If it is true, the grade is A. If it is false, the second condition (score >= 80.0) is tested. If the second condition is true, the grade is B. If that condition is false, the third condition and the rest of the conditions (if necessary) are tested until a condition is met or all of the conditions prove to be false. If all of the conditions are false, the grade is F. Note that a condition is tested only when all of the conditions that come before it are false.
Comments
Post a Comment