Use logic statements to define parts of an algorithm solution
9.2 Algorithms: Using Logic Statements
What are Logic Statements?
Logic statements are the building blocks of any algorithm. They let the computer decide what to do next based on conditions. Think of them like a traffic light: green means go, red means stop, and yellow means be careful. In programming we use if, else, while, and for to create those decisions. 🚦
Common Logic Operators
- AND – both conditions must be true: $p \land q$
- OR – at least one condition is true: $p \lor q$
- NOT – flips the truth value: $eg p$
- IMPLIES – if $p$ then $q$: $p \rightarrow q$
Truth Table for AND, OR, NOT
| p | q | p ∧ q | p ∨ q | ¬p |
|---|---|---|---|---|
| T | T | T | T | F |
| T | F | F | T | F |
| F | T | F | T | T |
| F | F | F | F | T |
Algorithm Example: Finding the Largest Number
Suppose you have three numbers: $a$, $b$, and $c$. We want to find the largest. Here’s how logic statements help us build the algorithm step‑by‑step. 📊
- Start with the assumption that $a$ is the largest.
- Check if $b$ is greater than the current largest:
if (b > a) then a = b;?? - Check if $c$ is greater than the current largest:
if (c > a) then a = c;?? - After both checks, $a$ holds the largest value.
In pseudocode, it looks like this:
largest = a
if (b > largest) {
largest = b
}
if (c > largest) {
largest = c
}
print(largest)
Using Loops with Logic
Loops let us repeat logic statements until a condition is met. For example, to find the sum of numbers from 1 to $n$:
- Set
sum = 0andi = 1. - While
i <= ndo:- sum = sum + i
- i = i + 1
- When the loop ends,
sumholds the total.
This uses the while loop combined with the i <= n logic condition. 🔁
Quick Quiz
- What will the algorithm output if all three numbers are equal? ??
- Rewrite the largest‑number algorithm using a
forloop instead of twoifstatements. 🔄 - Explain in your own words why the loop condition
i <= nis necessary. ❓
Revision
Log in to practice.
2 views
0 suggestions