0% found this document useful (0 votes)
5 views14 pages

Flowgorithm: If-Else Logic Basics

The document provides an introduction to Flowgorithm and decision-making in programming using if-else statements. It includes examples of single and nested if statements, Boolean operators, and various lab tasks for practical application, such as classifying numbers and calculating traffic fines. Additionally, it outlines the logic for several programming tasks, including a restaurant tip calculator and a smart thermostat system.

Uploaded by

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

Flowgorithm: If-Else Logic Basics

The document provides an introduction to Flowgorithm and decision-making in programming using if-else statements. It includes examples of single and nested if statements, Boolean operators, and various lab tasks for practical application, such as classifying numbers and calculating traffic fines. Additionally, it outlines the logic for several programming tasks, including a restaurant tip calculator and a smart thermostat system.

Uploaded by

muzalimking
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Computing

Lab 04

Topic Flowgorithm

Flowgorithm (continue)
 If-else
 Nested if else
Objective

Functions
What it Does
An If Statement checks a Boolean expression and then executes a true or false
branch based on the result.

Example

The example, to the right, declares an integer called 'age'. It then reads the age from
the keyboard.
Finally, an If Statement checks if the age is greater than or equal to 18. Based on this,
it either takes the false branch and displays "Sorry, not yet", or takes the true branch
and displays "Go vote!".

Decisions (if statements)

Making a decision based on a single value (if


statements)
When the computer needs to “decide” which branch of a flowchart (or algorithm to
follow) it evaluates a variable against some condition that we place on it. These
decisions are frequently documented in a condition/action table. For instance for the
decision below: if age >= 18 we could document it like this:

path condition Action

User is 18 or older age >= 18 Print “Go vote!”

User is less than 18 age < 18 Print “Sorry, not yet”

The diamond shape is used to designate a decision. The “if” is not listed, just the
condition.

 Declare a variable for age


 Output the instruction to the user and store the result in age
 Add an IF shape, then double-click the shape to add the condition
 Back on the flowchart, click on each branch of the if statement and add an action that
the program will take (i.e. the message that is output to the user)
Making a decision based on multiple values
(if statements with Boolean operators)
In the case of multiple conditions that need to be met, we would use Boolean
operators to chain two or more conditions together. Boolean operators:

 AND – all conditions must be true in order to execute the code


 OR – only one of the conditions must be true in order to execute the code
 ! - NOT means that the code will only execute if the condition is not true

For instance for the decision below: if age >= 18 AND enrolled = true we could
document it like this:

path condition Action

User is 18 or older age > = 18 AND enrolled = true Print “Go vote!”

User is less than 18 or not enrolled age < 18 OR enrolled = false Print “Sorry, not yet”
Making decisions using multiple values with !
= (if statements checking for a negative
condition)
Many times we need to force the user to enter a certain value that we are looking for.
This is especially true when we need to validate the users input before continuing on
with the program.
The != operator (not equal) is very useful for this task. The flowchart below asks the
user to enter a specific character from the menu. If the condition is met (the user
didn’t enter an A, B or C) the true path is chosen. If the condition is not met (user
entered an A, B or C) the false path is taken.

Note: We use AND rather than OR here because all conditions need to evaluate to
true. For example, they didn’t enter any of the valid inputs (A, B and C).

Nested If (a condition within a condition)


At times we may need to test for a certain condition, and then run a further test on
another condition. However, if we want the program to be able to keep track of these
individual evaluations we will need a nested conditional statement. Think of this as an
if statement inside another if statement. In a previous section we were evaluating if a
person was old enough to vote AND was enrolled to vote. The condition action table
looked like the following:
path condition Action

age > = 18 AND enrolled =


User is 18 or older Print “Go vote!”
true

User is less than 18 or not Print “Sorry, not


age < 18 OR enrolled = false
enrolled yet”

In this case we can only respond to the two conditions:

 Either the user is old enough to vote and is enrolled


 Resulting in message: “Go vote”
 Or one of the conditions is false
 Resulting in the message: “Sorry, not yet”

If we want to be able target each individual condition, we will need a nested structure.

Path Condition Action

User is 18 or older and age >= 18 AND enrolled


Print “Go vote!”
enrolled = true

User is 18 or older and is age >= 18 AND enrolled “You are old enough to vote,
not enrolled = false Print but are not enrolled.”

User is not 18 or older age < 18 AND enrolled = Print “You are not yet 18 and
and is enrolled true are enrolled”

User is not 18 or older age < 18 18 AND Print “You are not yet 18 and
and is not enrolled enrolled = false are not enrolled”
Lab Tasks

Task 1: Number Classification

Write a program that classifies a number as positive, negative, or zero.

 Steps for if-else Logic:


1. Input a number.
2. Use nested if-else to check if the number is positive, negative, or zero.

Task 2: Age Group Classification

Write a program that classifies a person into an age group (Child, Teen, Adult, Senior).

 Steps for if-else Logic:


1. Input the person's age.
2. Use if-else to classify the person:

 0–12: Child
 13–19: Teen
 20–64: Adult
 65+: Senior
Task 3: Triangle Type

Write a program that checks if a triangle is equilateral, isosceles, or scalene based on its side lengths.

 Steps for if-else Logic:


1. Input the three side lengths of the triangle.
2. Use if-else conditions to check the type of triangle:

 Equilateral: All sides are equal.


 Isosceles: Two sides are equal.
 Scalene: No sides are equal.

Task 04: Traffic Violation Fine Calculator

You are creating a system that calculates a traffic fine based on the speed of a driver. The rules
for the fine are:

1. If the driver is driving within the speed limit, display: "No fine."
2. If the driver is speeding up to 10 km/h over the limit, the fine is $50.
3. If the driver is speeding between 11 and 30 km/h over the limit, the fine is $100.
4. If the driver is speeding more than 30 km/h over the limit, the fine is $200.

Steps for if-else Logic:

1. Input the speed limit and the driver's speed.


2. Use if-else conditions to determine the fine based on how much the driver exceeds the speed
limit.

Task 5: Fitness Calorie Tracker

A fitness app needs to track calories burned during exercise. The system should:

1. Ask the user to input the type of exercise they performed (e.g., running, cycling, swimming).
2. Ask the user to input the duration of the exercise (in minutes).
3. Based on the exercise type and duration, calculate the calories burned (using a simple formula
like: running = 10 calories/min, cycling = 8 calories/min, swimming = 7 calories/min).
4. Display the total calories burned.

Input/Output Steps:
1. Input: Exercise type and duration.
2. Output: Total calories burned.

Task 6: Online Shopping Cart System

An online shopping cart system allows users to add items to their cart and calculates the total
price. The system should:

1. Ask the user to input the number of items they want to purchase.
2. For each item, ask for the item name, quantity, and price.
3. Calculate and display the total price of all items in the cart.

Input/Output Steps:

1. Input: Number of items, item name, quantity, and price.


2. Output: Total price of all items.

Task 7: Pizza Order System

You are designing a pizza ordering system for a local restaurant. The system should:

1. Ask the user to select a pizza size (small, medium, large).


2. Ask the user to choose toppings from a list (e.g., pepperoni, mushrooms, onions, etc.).
3. Based on the size and number of toppings, calculate the total cost.
4. Display the order summary and total cost.

Input/Output Steps:

1. Input: Pizza size and selected toppings.


2. Output: Order summary and total cost.
Task 8: Grocery Store Discount Calculator

A grocery store is running a discount promotion. The system should:

1. Ask the user to input the total amount of their purchase.


2. If the total amount is greater than $100, offer a 10% discount.
3. Calculate the discount (if applicable) and display the total amount after applying the discount.

Input/Output Steps:

1. Input: Total purchase amount.


2. Output: Discount (if applicable) and final total.

Task 09: ATM Withdrawal System

Simulate an ATM that allows withdrawal only if the entered amount is valid.

 Steps for Nested if-else Logic:


1. Input balance and withdrawal amount.
2. Check if withdrawal amount is positive.

 If yes, check if it’s less than or equal to balance.

 If yes, allow transaction.


 Else, show "Insufficient balance".

 Else, show "Invalid amount".

Task 1: Restaurant Tip Calculator


A busy restaurant wants a bill-helper that recommends a fair tip based on service quality. At
checkout, the app asks the customer for the bill amount and a service rating of “excellent,”
“good,” or “poor.” It then suggests a tip by applying a fixed percentage to the bill: 20% for
excellent, 15% for good, and 10% for poor. The goal is to implement a tiny advisory tool using
simple if–else logic that reads the two inputs, selects the right percentage from the three
options, and prints a clear recommendation such as “Suggested Tip: $X (Y% of bill).”

Sample Input/Output
Input: Input:
Bill Amount: 3200 Bill Amount: 1850
Service Rating: excellent Service Rating: poor
Output: Output:
Suggested Tip: 640 (20% of 3200) Suggested Tip: 185 (10% of 1850)

Task 2: Smart Thermostat Temperature Control


A smart home thermostat needs to keep rooms comfortable without user micromanagement.
The controller reads the current room temperature and the user’s preferred temperature
range (minimum and maximum). It then decides what to do: if the current temperature is
below the range, it should display “Heating on.” If the temperature sits within the range, it
shows “Temperature is ideal.” If it’s above the range, it shows “Cooling on.” Build the core
decision logic with if–else so the thermostat consistently chooses one clear action based on the
inputs.

Sample Input/Output
Input: Input:
Current Temp: 19 Current Temp: 22
Preferred Min: 20 Preferred Min: 20
Preferred Max: 24 Preferred Max: 24
Output: Output:
Heating on. Temperature is ideal.

Task 3: Health Risk Assessment Based on BMI

A wellness app offers an instant health-risk check using Body Mass Index (BMI). The user enters
height and weight, the app computes BMI, and then classifies the result into one of four
advisory bands. If BMI is < 18.5, display “Underweight – Possible health risks.” For 18.5–24.9,
display “Normal weight – Healthy range.” For 25–29.9, display “Overweight – Increased health
risks.” For ≥ 30, display “Obese – High health risks.” Implement the classification with clear if–
else checks and print the matching message.

Sample Input/Output
Input: Input:
Height (m): 1.75 Height (m): 1.62
Weight (kg): 68 Weight (kg): 82
Output: Output:
BMI: 22.20 BMI: 31.27
Normal weight – Healthy range. Obese – High health risks.
Task 4: Ride-Share Pricing System
A ride-share app wants surge pricing that feels predictable. The system reads the time of day
(24-hour format) and the traffic condition (“heavy” or “light”). If it’s rush hour (07–09 or 17–
19) and traffic is heavy, the app increases the base fare by 50%. If it’s rush hour with light
traffic, it increases by 20%. At all other times, it uses the normal base fare. Write the if–else
logic that takes the two inputs, identifies whether it’s rush hour, applies the correct multiplier,
and prints the final fare.

Sample Input/Output
Input: Input:
Base Fare: 600 Base Fare: 450
Hour (0–23): 8 Hour (0–23): 14
Traffic: heavy Traffic: light
Output: Output:
Final Fare: 900 (Rush hour + heavy → Final Fare: 450 (Not rush hour)
+50%)

You might also like