Resources | Subject Notes | Computer Science
Nested statements occur when one control structure (like an if
statement, a for
loop, or a while
loop) is placed inside another control structure. This allows for more complex and conditional program logic.
Nested statements are essential for creating programs that can handle multiple levels of conditions or repeat actions within other repeating actions. They enable you to build sophisticated algorithms.
if
StatementsYou can place an if
statement inside another if
statement. This is useful for checking multiple conditions.
Example: Determine if a number is within a specific range and also positive.
Code | Explanation |
---|---|
|
The outer if checks if the number is greater than 0. If it is, the inner if checks if it's also less than 100. The output depends on the evaluation of both conditions.
|
for
LoopsA for
loop can be placed inside another for
loop. This is commonly used for processing multi-dimensional data (like a 2D array) or generating combinations.
Example: Print a multiplication table up to 5x5.
Code | Explanation |
---|---|
|
The outer loop iterates through numbers 1 to 5 (inclusive). The inner loop also iterates through numbers 1 to 5 (inclusive). For each combination of i and j , their product is calculated and printed, followed by a tab. After each row, a newline is printed to move to the next line.
|
while
LoopsSimilar to for
loops, while
loops can be nested to create more complex iterative processes. The inner loop continues to execute as long as the outer loop's condition is true.
Example: Prompt the user for input until they enter a valid number between 1 and 10.
Code | Explanation |
---|---|
|
The outer while loop runs indefinitely until a valid number is entered. The inner while loop attempts to convert the user's input to an integer and checks if it falls within the range of 1 to 10. If the input is valid, the loop breaks. If not, an error message is displayed, and the outer loop continues.
|