In this article, you will learn nested if-else in Mojo Programming Language, along with real-world examples, engaging visuals, and easy code snippets on real-world scenarios.
Conditional Statements in Mojo (if-else)
In programming, conditional statements allow a program to decide what to do based on certain conditions. In Mojo, these statements help us to perform specific actions only if certain requirements are met. This means the program can choose different paths depending on the situation.
The if-else
statement in Mojo is a type of conditional statement that lets the program check a condition and then take action. When the condition is true the if condition code will be executed. If the condition is false, the code inside the else
block will run instead.
What are Nested Conditions in Mojo?
Nested conditions are when you place one conditional statement inside another. This means using an if-else
statement within the block of another if-else
statement. Nested conditions let the program check multiple conditions in a sequence, allowing more specific actions based on each condition’s outcome.
Real-Life Example of Nested Conditions
Imagine you’re ordering a pizza. First, you decide on the type of crust, and after looking at the menu, you pick thin crust. Then, you consider the toppings; you prefer vegetables, so you go with bell peppers and mushrooms. Lastly, you decide on the size: a small pizza could work, but since you’re sharing with friends, you choose a large one. Each choice—crust, toppings, and size—is like using nested if-else conditions in programming, where each decision depends on the previous one.
- Choose a crust type
if (crust == thin)
- Choose toppings
if (toppings == vegetables)
- Choose size
if (size == large)
Nested If Statement in Mojo
In Mojo, a nested if statement lets you build multiple layers of decision-making within your code. You create a nested if statement by placing one if statement inside another. The program first checks the outer if condition of the program. If this first condition is true, the program then moves on to evaluate another condition inside the block of the first if statement. This setup allows you to add depth to your decision-making and handle complex scenarios step-by-step, where each new choice depends on the result of the previous one.
Real-World Analogy of Nested If Condition – Book from Library
Imagine you’re at a library to borrow a book. First, you check if the book is available. If it is, you then check if your library card is valid. If both conditions are met, you can proceed to borrow the book.
- Check if the book is available
if (book == available)
- Check if your library card is valid
if (libraryCard == valid)
Flow Chart of Nested If in Mojo
The program first evaluates the initial if statement. If the initial if condition is true, the program checks a nested if
condition. If the nested if condition is also true, the program executes its associated statements. However, if the initial if condition is false, the program directly skips to the else block and runs those statements, then ends.
Syntax
if condition1 { # if condition1 is true then run this code if condition2 { # if condition2 is true then run this code } }
Example Code
- The program prompts the user to input a number.
- It stores the input in a variable named number through the read() function.
- The first if statement checks if the number is greater than 0:
- When the condition is correct, prints “The number is positive.”
- Next, it verifies if the number is even (divisible by 2).
- When the condition is correct, prints “The number is even.”
- If the number is not positive (0 or negative), the program does nothing and ends.
number: Int # Declare a variable to hold the number print("Enter a number: ") number = read() # Read user input if number > 0 { # condition checking if the number is positive print("The number is positive.") if number % 2 == 0 { # Second condition checks if the number is even print("The number is even.") } }
Output
Enter a number: 6 The number is positive. The number is even.
Nested If-else Statement in Mojo
Nested if-else
statements allow you to make more complex decisions in your program. Rather just checking if conditions are true, nested if-else
statements let you evaluate multiple conditions, providing options for both true and false outcomes. This approach is useful when you need to manage different possibilities depending on the results of earlier checks, enhancing the flexibility of your code.
Real-World Analogy of Nested If-else – Booking a Hotel Room
Imagine you’re booking a hotel room for your vacation. First, you select a room type: Single, Double, or Suite. If you choose Double or Suite, you then pick the view: City View or Ocean View. Finally, you can decide whether to add breakfast to your reservation. Each choice—room type, view, and breakfast—is like using nested if-else conditions in programming, where one decision leads to the next.
Flow Chart of Nested if-else
Syntax
if condition1 { # Code for condition1 being true if condition2 { # Code for condition2 being true inside condition1 } else { # Code for condition2 being false inside condition1 } } else { # Code for condition1 being false if condition3 { # Code for condition3 being true inside condition1's else } else { # Code for condition3 being false inside condition1's else } }
Example Code
Declare Age Variable: The program starts by creating a variable age
to store the user’s age.
Get User’s Age: It prompts the user to enter their age.
- Checks if age is between 13 and 19.
- If true, it confirms the user is a teenager and, if 16 or older, eligible for a driver’s license.
If Not a Teenager:
- Displays “Not a teenager” and checks other age ranges:
- Adult (20-64): Prints “You are an adult.”
- Senior (65+): Prints “You are a senior citizen.”
- Child (below 13): Prints “You are a child.”
# Variable declaration age: Int # Prompt user for age print("Enter your age: ") age = readInt() if age >= 13 && age <= 19 { # First check: is the person a teenager (13-19)? print("You are a teenager.") if age >= 16 { # Check if the teenager is 16 or older print("You are eligible to apply for a driver's license.") } else { # If the teenager is younger than 16 print("You are not yet eligible to apply for a driver's license.") } } else { # Second check: not a teenager print("You are not a teenager.") if age >= 20 && age <= 64 { # Check if the person is an adult print("You are an adult.") } else if age >= 65 { # Check if the person is a senior print("You are a senior citizen.") } else { # If the person is a child (below 13) print("You are a child.") } }
Output
Enter your age: 18 You are a teenager. You are eligible to apply for a driver's licence.
Example Scenario-Based Program on Nested Conditional Statement in Mojo
Imagine you’re creating a program for a bank to determine loan eligibility for applicants. The bank offers loans with different conditions based on the applicant’s employment type. If the applicant is a full-time employee, the loan approval depends on their credit score: applicants with a score of 700 or above qualify for a low-interest loan, while those with a lower score get a standard-interest loan. If the applicant is self-employed, they need a credit score of at least 750 to be eligible for a low-interest loan, while others may qualify for a standard loan with additional documentation. For unemployed applicants, having a guarantor is mandatory to be eligible for any loan. This structure of checking various conditions within specific categories is a practical use of nested if-else statements.
Example Code
- The program determines loan eligibility based on the applicant’s employment type.
- First, it checks if the applicant is a full-time employee:
- If true, it then checks the applicant’s credit score.
- A score of 700 or above qualifies the applicant for a low-interest loan; otherwise, a standard-interest loan is offered.
- If the applicant is self-employed:
- The program checks if their credit score is 750 or above.
- If the score meets this threshold, the applicant qualifies for a low-interest loan; otherwise, a standard loan is offered with additional documentation required.
- If the applicant is unemployed:
- It checks if they have a guarantor.
- If a guarantor is present, the applicant is eligible for a standard loan; without a guarantor, the application is declined.
# Applicant details employment_type = "full-time" # Options: "full-time", "self-employed", "unemployed" credit_score = 720 has_guarantor = False # Only used if employment_type is "unemployed" # Check loan eligibility based on employment type and credit score if employment_type == "full-time": if credit_score >= 700: print("Eligible for low-interest loan.") else: print("Eligible for standard-interest loan.") elif employment_type == "self-employed": if credit_score >= 750: print("Eligible for low-interest loan.") else: print("Eligible for standard-interest loan, additional documents needed.") elif employment_type == "unemployed": if has_guarantor: print("Eligible for standard-interest loan with guarantor.") else: print("Not eligible for a loan without a guarantor.") else: print("Invalid employment type entered.")
Output
employment_type = "full-time" credit_score = 720 has_guarantor = False Eligible for low-interest loan.
Conclusion
In conclusion, you’ve learned how to use nested if-else statements in Mojo to create flexible programs that can handle multiple conditions. Through real-life examples, like gym memberships and bank loans, you now see how nested conditions make decisions more precise. With this foundation, you can apply nested statements to make your code clearer, smarter, and more adaptable to different situations.
If you haven’t installed Mojo, follow our step-by-step guide on Mojo installation and explore more tutorials on Mojo by Syntax Scenarios.