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

  1. Start with the assumption that $a$ is the largest.
  2. Check if $b$ is greater than the current largest: if (b > a) then a = b; ??
  3. Check if $c$ is greater than the current largest: if (c > a) then a = c; ??
  4. 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$:

  1. Set sum = 0 and i = 1.
  2. While i <= n do:
    • sum = sum + i
    • i = i + 1
  3. When the loop ends, sum holds 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 for loop instead of two if statements. 🔄
  • Explain in your own words why the loop condition i <= n is necessary. ❓

Revision

Log in to practice.

2 views 0 suggestions