0% found this document useful (0 votes)
27 views18 pages

Control Statements (Loops, Switch, Conditions

Control statements are essential for managing program flow, including conditional statements (if, else, switch) and loops (for, while, do-while). They enable decision-making, repetition of actions, and are widely used in real-world applications such as banking systems and interactive software. Best practices include using switch for multiple choices, avoiding infinite loops, and being cautious with nested loops to maintain performance.

Uploaded by

kvkumaravel28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views18 pages

Control Statements (Loops, Switch, Conditions

Control statements are essential for managing program flow, including conditional statements (if, else, switch) and loops (for, while, do-while). They enable decision-making, repetition of actions, and are widely used in real-world applications such as banking systems and interactive software. Best practices include using switch for multiple choices, avoiding infinite loops, and being cautious with nested loops to maintain performance.

Uploaded by

kvkumaravel28
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Control Statements

(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).

• Purpose: Make decisions, repeat actions, and control program flow.


If-Else Statement
• Executes code based on whether a condition is true or false.
• Example: Bank Account System (Check Balance)
• Code
• if (balance >= withdrawalAmount)
{
processWithdrawal();
} else {
alert("Insufficient funds.");
}

• 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

• Efficiently handles multiple conditions by matching values to case labels.


• Example: Traffic Light System
• Code
switch (trafficSignal) {
case "Red":
stopVehicle();
break;
case "Green":
goVehicle();
break;
case "Yellow":
slowDownVehicle();
break;
default:
alert("Invalid signal.");
• }
 Switch: The program checks the value of trafficSignal.

 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.

 Traffic Control: Managing the actions of vehicles at a traffic signal.


For Loop
 Content:
o Explanation: Repeats a block of code for a specified number of times.
o Example: Calculating total price in a shopping cart
o Code

double totalPrice = 0;

for (int i = 0; i < items.length; i++)

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).

 Iteration: The i++ increments the counter after each iteration.

 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.

 Data Manipulation: Iterating over datasets for processing or analysis.


While Loop

o Explanation: Repeats a block of code as long as a condition is true.


o Example: Game Loop that runs until the player exits.
• Code
while (gameRunning) {

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:

for (int i = 0; i < matrixA.length; i++) {

for (int j = 0; j < matrixB[i].length; j++) {

result[i][j] = matrixA[i][j] * matrixB[j][i];

o Real-World Use:
 Image processing (pixel manipulation).
 Grid-based games or simulations.

 Outer Loop: Iterates through rows of matrixA.

 Inner Loop: Iterates through columns of matrixB.

 Action: For each combination of rows and columns, it multiplies the values and stores them in result.

• Real-World Use:

 Matrix Operations: Common in scientific computing, graphics, and machine learning.

 Grids and Tables: Often used in games, simulations, and visualization.


Real-World Example: ATM System

 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.

You might also like