Algorithm 3
Algorithm 3
Analogy to a Three-Year-Old
When programming a computer (or instructing a three-year-old), you typically
provide instructions sequentially: statement one, statement two, statement three.
However, to enable decision-making, you must program how the decision will be
made.
Page 1
Created by Turbolearn AI
Computer's Understanding
Conditions must be given in a way that the computer understands, using variables
and logic (equal to, less than, greater than, etc.).
Sequential Instructions
1. Enter first number (displayed to the user).
2. Read number into num1.
The computer creates a box (memory location) called num1.
3. Enter second number (displayed to the user).
4. Read number into num2.
The computer creates a box called num2.
User Input
The user (not the programmer) enters the numbers. For example:
num1 =7
num2 = 2
Decision-Making Process
The condition is: "if num1 is greater than num2?"
The computer checks if the value in num1 is greater than the value in num2.
The answer can be yes or no.
Page 2
Created by Turbolearn AI
Scenario 1: 7 and 2
Is 7 > 2? Yes.
The computer prints: "The larger number is num1" (which is 7).
The algorithm works correctly.
Scenario 2: 2 and 7
Values are reversed: num1 = 2, num2 = 7
Is 2 > 7? No.
The computer prints: "The larger number is num2" (which is 7).
The algorithm still works correctly.## Selection Control Structures
Page 3
Created by Turbolearn AI
1. Start
2. Enter first price (p1)
3. Enter second price (p2)
4. If p1 < p2:
low = p1
5. Else:
low = p2
6. Display low
Explanation:
Example:
p1 = 10
p2 = 12
Is p1 < p2? Yes, because 10 is less than 12. Therefore, low = 10, and 10 is displayed.
1. Variables:
mark (or m)
2. Start
3. Print "Please enter the mark the student got."
4. Read m
5. If m > 59:
Print "You have passed."
6. Else:
Print "You failed to pass this time."
7. Stop
Page 4
Created by Turbolearn AI
Explanation:
The algorithm starts by prompting the user to enter the student's mark.
The input is stored in the variable m.
The condition m > 59 is checked.
If m is greater than 59, the algorithm prints "You have passed."
Otherwise, it prints "You failed to pass this time."
The algorithm then stops.
Alternative Condition: Instead of using m > 59, you can use m >= 60. Both conditions
achieve the same result because the passing mark is 60.
Operator Meaning
This algorithm checks whether a student has passed or failed based on their mark.
Page 5
Created by Turbolearn AI
Let's consider a more complex problem: Ask the user to input three numbers, find
their average, and determine if the average indicates a pass or fail. The passing mark
is 50.
2. Variables:
m1 : Mark 1
m2: Mark 2
m3: Mark 3
3. Start:
4. Calculate Average:
6. Stop.
This selection algorithm determines if a student has passed or failed based on the
average of three marks.
Page 6