Control Statements (Loops, Switch, Conditions
Control Statements (Loops, Switch, Conditions
(Loops, Switch,
Conditions)
Introduction to Control Statements
• Definition: Control statements manage the flow of a program.
• Types:
• Conditional Statements (if, else, switch)
• Loops (for, while, do-while).
• Real-World Use:
• Financial systems (checking balance before withdrawal).
• User authentication (password validation).
Case: If the condition is true, it processes the withdrawal.
False Case: If the condition is false, it alerts the user that the funds are insufficient.
• Real-World Use:
Banking apps: Before allowing a withdrawal, the system must check if the balance is sufficient.
Authentication: When validating a password, you use if-else to check if the entered password matches the
correct one.
Condition: The program checks if balance is greater than or equal to the withdrawalAmount.
• True
Switch statement
Cases: It compares trafficSignal to "Red", "Green", and "Yellow". Each case executes the corresponding
function.
Default: If the value doesn't match any case, the default block is executed, alerting the user about the
invalid signal.
• Real-World Use:
Menu Systems: For example, in a software app where the user selects options (e.g., "New", "Open", "Exit"),
the switch handles each action.
double totalPrice = 0;
totalPrice += items[i].getPrice();
}
Initialization: int i = 0 initializes the counter i to 0.
Condition: The loop continues as long as i is less than items.length (i.e., it iterates through each item in the
list).
Action: The total price is updated by adding the price of each item.
• Real-World Use:
Batch Processing: For example, in e-commerce apps, you may need to calculate the total cost of all items in a
user's shopping cart.
•
While Loop
updateGame();
checkEvents();
• Real-World Use:
• Real-time event processing (games, IoT devices).
• Continuous monitoring of sensors.
Condition: The loop continues as long as gameRunning is true.
Action: Inside the loop, it updates the game and checks for any events (e.g., player input or collisions).
Termination: The loop will stop when gameRunning becomes false (typically, when the player exits the game).
• Real-World Use:
Games: Many games run in an endless loop, constantly updating the game state and responding to user input.
Monitoring Systems: In systems like IoT devices, continuous monitoring of sensors is handled using while loops.
Do-While Loop
o Explanation: Similar to while loop but ensures that the code runs at least once.
o Example: Login system where the user is asked for input at least once.
• Code
do {
userInput = getInput();
} while (!isValidPassword(userInput));
• Real-World Use:
• Input validation (ensuring valid data is entered).
• Interactive systems that require at least one action.
• Action: The program prompts the user for input, then checks if the
password is valid.
• Condition: If the password is invalid, it will ask the user to try again.
The loop continues until a valid password is entered.
• Real-World Use:
• Forms and Input Validation: Ensures the user provides valid input
before proceeding.
• Interactive Systems: Ensuring at least one action (e.g., asking the user
for something before proceeding).
Nested Loops
o Explanation: A loop inside another loop, often used for multi-dimensional data.
o Example: Matrix multiplication.
• Code:
o Real-World Use:
Image processing (pixel manipulation).
Grid-based games or simulations.
•
Outer Loop: Iterates through rows of matrixA.
Action: For each combination of rows and columns, it multiplies the values and stores them in result.
• Real-World Use:
Problem: ATM needs to process multiple actions (withdrawal, deposit, balance check).
Solution:
o Switch Case: For different menu options.
o If-Else: To check balance before withdrawal.
o Loop: To keep the system running until the user chooses to exit.
boolean exit = false;
while (!exit) {
displayMenu();
choice = getUserChoice();
switch(choice) {
case 1: checkBalance(); break;
case 2: withdrawMoney(); break;
case 3: depositMoney(); break;
case 4: exit = true; break;
Loop: The loop ensures the ATM continues running until the user selects "Exit".
Switch: The switch handles different user inputs, such as checking balance, withdrawing money, or exiting.
• Real-World Use:
ATMs: Common for interactive systems where users can choose from several options.
Interactive Applications: Any system that allows the user to choose different options.
•
Advantages of Control
Statements
• Efficiency: Control the flow of logic.
• Flexibility: Change behavior dynamically.
• Simplicity: Easy to understand and debug.
• Best Practices
Content:
o Use switch for handling multiple choices.
o Avoid infinite loops unless absolutely necessary.
o Use nested loops with caution to prevent performance issues.
• Conclusion
Summary: Control statements are vital to managing the flow and decision-making in programs.
Key Points: Loops and conditions are essential for real-time systems and interactive applications.