Control Flow Algorithms: Fundamentals of Programming Part 4

Remember when you learned about input and output—how programs talk to users and get information? That’s great, but here’s the thing: knowing how to get data doesn’t mean your program can actually think or make smart choices.

Imagine you’re writing instructions for your friend to make a sandwich. You could write: “Get bread. Get peanut butter. Spread peanut butter. Get jelly. Spread jelly. Put bread together.” That works fine… until your friend doesn’t have jelly. Now what? Your instructions just break.

That’s the problem with basic programs. They follow instructions blindly, top to bottom, with no ability to adapt. If something unexpected happens, they crash or give weird results.

That’s what we’re fixing today. We’re talking about control flow—giving your programs the ability to make decisions, repeat actions when needed, and handle different situations.

What We’re Covering Today

  • Why programs need to be flexible (not just run top to bottom)
  • The three basic patterns all programs use
  • How to make programs choose between options (and why we have different tools for this)
  • How to make programs repeat actions (and when to use which method)
  • Interactive exercises where you’ll see these concepts actually work

Let’s start with the big question.

Why Can’t Programs Just Run Top to Bottom?

Short answer: They can. That’s actually how the simplest programs work.

But think about your daily routine. You don’t do the exact same thing every day in the exact same order, right?

  • On rainy days, you grab an umbrella
  • If you’re running late, you skip breakfast
  • You check your phone until your friend replies
  • You repeat “one more episode” until it’s too late

Programs need this same flexibility. Without it, every calculator app would only work for one specific math problem. Every game would play the same way every time. Every app would crash the moment something unexpected happened.

So programmers use three basic patterns to make programs flexible:

  1. Sequence: Do this, then do that (the normal top-to-bottom flow)
  2. Selection: Choose which path to take based on what’s true
  3. Repetition: Keep doing something until a condition changes

That’s it. Everything else we’ll talk about is just different ways to use these three patterns. Once you understand these, you understand how all programs work.

Pattern #1: Sequence (The Boring But Important One)

Sequence just means the computer runs code in order. Line 1, then line 2, then line 3.

Example (making a sandwich):

1. Get two slices of bread
2. Get peanut butter
3. Spread peanut butter on one slice
4. Get jelly
5. Spread jelly on the other slice
6. Put slices together

The computer does step 1, then step 2, then step 3, and so on. No thinking, no choices, just following the list.

This is how programs start. But it’s not enough.

TRY THIS WITH AI:

I'm learning about sequential execution. 
Can you simulate this simple morning routine program step by step: 

1) Wake up, 
2) Brush teeth, 
3) Get dressed, 
4) Eat breakfast. 
Show me what happens at each step.

Watch how the AI executes each step in order.

Then try asking:

What happens if I remove step 2?

See how sequence works—the program just skips that step and continues.

Pattern #2: Selection (Making Choices)

Selection means your program looks at a situation and chooses what to do next. Think of it like those “Choose Your Own Adventure” books where the story changes based on your choices.

Now here’s where beginners get confused: there are several tools for making choices (if, else, switch), and they all look slightly different. But here’s the truth—they all do the same basic thing. They’re just optimized for different situations.

Let me show you why we need different tools.

The If Statement: The Simplest Choice

Use this when you want to do something only if a condition is true.

Example (morning routine):

SET temperature TO 18
IF temperature is less than 20 THEN
    DISPLAY "Grab a jacket"
DISPLAY "Leave the house"

If the temperature is below 20, you grab a jacket. Either way, you leave the house.

TRY THIS WITH AI:

Ask your AI:

Can you run this pseudo code.
Show me what happens when temperature = 18.
Then show me what happens when temperature = 25?

SET temperature TO 18
IF temperature is less than 20 THEN
    DISPLAY "Grab a jacket"
DISPLAY "Leave the house"

Watch how the program either executes the jacket line or skips it, but always executes the last line. Try changing the temperature value and running it again.

The If-Else Statement: Two Paths

Use this when you need to choose between exactly two options.

Example (deciding on breakfast):

SET time_available TO 5

IF time_available is less than 10 THEN
    DISPLAY "Grab a granola bar"
ELSE
    DISPLAY "Make pancakes"
END IF

No matter what, exactly one of those happens. You either grab a bar or make pancakes.

TRY THIS WITH AI:

Ask your AI:

Simulate this breakfast decision pseudo code with time_available = 5.
Then run it again with time_available = 15.
Show me how the program chooses different paths.

SET time_available TO 5

IF time_available is less than 10 THEN
    DISPLAY "Grab a granola bar"
ELSE
    DISPLAY "Make pancakes"
END IF

Try asking:

What happens when time_available = 10 exactly?
Which path does it take and why?

The If-Else-If Chain: Multiple Paths

Use this when you have more than two options.

Example (deciding what to wear):

SET temperature TO 22

IF temperature is less than 15 THEN
    DISPLAY "Wear a jacket"
ELSE IF temperature is less than 25 THEN
    DISPLAY "Wear a sweater"
ELSE IF temperature is less than 30 THEN
    DISPLAY "Wear a t-shirt"
ELSE
    DISPLAY "Wear shorts"
END IF

The program checks each condition from top to bottom. As soon as it finds one that’s true, it does that action and skips the rest.

TRY THIS WITH AI:

Ask your AI:

Run this clothing selector with these temperatures one at a time: 
- 10
- 22
- 28
- 35

For each one, tell me which clothing gets selected.
Explain why the program stops checking after finding the first true condition.

SET temperature TO 22

IF temperature is less than 15 THEN
    DISPLAY "Wear a jacket"
ELSE IF temperature is less than 25 THEN
    DISPLAY "Wear a sweater"
ELSE IF temperature is less than 30 THEN
    DISPLAY "Wear a t-shirt"
ELSE
    DISPLAY "Wear shorts"
END IF

Notice how when temperature is 10, it says “Wear a jacket” and never checks the other conditions, even though 10 is also less than 25, 30, etc. This is important—the program stops at the first true condition.

The Switch Statement: Checking One Thing Against Many Values

Use this when you’re checking one specific thing against several possible values.

Example (different message for each day):

SET day TO "Friday"

SWITCH day:
    CASE "Monday":
        DISPLAY "First day of the week"
    CASE "Friday":
        DISPLAY "Almost the weekend!"
    CASE "Saturday" OR "Sunday":
        DISPLAY "It's the weekend!"
    DEFAULT:
        DISPLAY "Just another weekday"
END SWITCH

TRY THIS WITH AI:

Ask your AI:

Simulate this day-of-week program with day = Monday.
Then Friday.
Then Saturday.
Then Wednesday. 
Show me what message displays for each day.

SET day TO "Friday"

SWITCH day:
    CASE "Monday":
        DISPLAY "First day of the week"
    CASE "Friday":
        DISPLAY "Almost the weekend!"
    CASE "Saturday" OR "Sunday":
        DISPLAY "It's the weekend!"
    DEFAULT:
        DISPLAY "Just another weekday"
END SWITCH

Then ask:

Then ask: 
"Why would I use a SWITCH statement instead of multiple IF-ELSE-IF?"

So why all these different tools? They all make choices, but each one is designed to make your logic easier to read in different situations. Think of it like transportation: walking, biking, driving, and taking the bus all get you somewhere. You could walk everywhere, but biking is better for medium distances. Same with these decision tools—pick the one that fits the situation.

Pattern #3: Repetition (Doing Things Multiple Times)

Repetition means your program keeps doing something until a condition changes. This is where loops come in.

Again, there are several types of loops, and beginners often wonder: “Why so many?” The answer is the same—they all repeat actions, but they’re designed for different situations to make your code clearer.

The For Loop: When You Know How Many Times

Use this when you know exactly how many times you need to repeat something.

Example (counting practice):

FOR counter FROM 1 TO 5:
    DISPLAY "Count: " + counter
END FOR

DISPLAY "Done counting!"

You know in advance: count from 1 to 5. The loop runs exactly 5 times.

TRY THIS WITH AI:

Ask your AI:

Simulate this counting program and show me what gets displayed.

FOR counter FROM 1 TO 5:
    DISPLAY "Count: " + counter
END FOR

DISPLAY "Done counting!"

Then ask:

Modify this to count from 1 to 10 and show me the output.

Try this next:

Can you create pseudo code that uses a FOR loop.
Display 'Hello' 3 times, then simulate running it?

The While Loop: When You Don’t Know How Many Times

Use this when you need to keep going until something specific happens, but you don’t know when that’ll be.

Example (guessing game):

SET secret_number TO 7
SET guess TO 0

WHILE guess is not equal to secret_number:
    GET guess from user
    IF guess is not equal to secret_number THEN
        DISPLAY "Wrong! Try again."
    END IF
END WHILE

DISPLAY "You got it!"

You don’t know how many guesses it’ll take. Could be 1, could be 20. You keep going until they guess correctly.

TRY THIS WITH AI:

Ask your AI:

Simulate this guessing game. 
Pretend the user guesses these numbers in order: 3, 8, 5, 7. 
Show me what happens at each guess.
Explain when the WHILE loop stops running.

SET secret_number TO 7
SET guess TO 0

WHILE guess is not equal to secret_number:
    GET guess from user (use: 3, then 8, then 5, then 7)
    IF guess is not equal to secret_number THEN
        DISPLAY "Wrong! Try again."
    END IF
END WHILE

DISPLAY "You got it!"

Then ask:

What would happen if the secret_number is 7.
But the user just kept guessing 5 forever?
Would the loop ever end?

This is your introduction to infinite loops—loops that never end because the condition never becomes false.

About infinite loops: You know how sometimes you accidentally create a feedback loop in life? Like “I’ll check Instagram while I wait for this to load” and suddenly an hour passed? An infinite loop is when you accidentally forget to include a way for the loop to end. The program just keeps going forever. Your computer won’t break, but the program will freeze and you’ll have to force-quit it.

TRY THIS WITH AI:

Ask your AI:

Show me an example of pseudo code that creates an infinite loop.
Explain why it never ends.
Don't actually run it, just show me the code and explain the problem.

The Do-While Loop: At Least Once, Then Check

This is like a while loop, but it always runs at least once before checking if it should continue.

Example (password entry):

DO:
    DISPLAY "Enter password: "
    GET password from user
WHILE password is not equal to "secret123"

DISPLAY "Access granted!"

Even if they enter the correct password on the first try, the program still asks them once. This is different from a regular WHILE loop, which might not run at all if the condition starts as false.

TRY THIS WITH AI:

Ask your AI:

Simulate this password program. 
First, pretend the user enters 'wrong' then 'hello' then 'secret123'.
Show what happens.
Then explain the difference between DO-WHILE and a regular WHILE loop.

DO:
    DISPLAY "Enter password: "
    GET password from user
WHILE password is not equal to "secret123"

DISPLAY "Access granted!"

The For-Each Loop: Going Through Every Item

This is a special version designed specifically for going through collections of things.

Example (checking notifications):

SET notifications TO [
    "Message from Ana", 
    "Like on photo", 
    "Event reminder", 
    "Comment from Juan"
]

FOR EACH notification IN notifications:
    DISPLAY "You have: " + notification
END FOR

DISPLAY "All caught up!"

You don’t need to count how many notifications there are. The loop automatically goes through each one.

TRY THIS WITH AI:

Ask your AI:

Simulate this notification program and show me the output.

SET notifications TO [
    "Message from Ana", 
    "Like on photo", 
    "Event reminder", 
    "Comment from Juan"
]

FOR EACH notification IN notifications:
    DISPLAY "You have: " + notification
END FOR

DISPLAY "All caught up!"

Then ask:

Add two more notifications to the list and simulate it again.
Show me how the FOR EACH loop automatically handles more items.
And without changing the loop code itself.

So why different types of loops? Because they make your logic match your intention:

  • FOR loop: “Do this exactly N times”
  • WHILE loop: “Keep doing this until something changes”
  • DO-WHILE loop: “Do this once, then keep doing it if needed”
  • FOR EACH loop: “Do something with every item in this collection”

You could technically use a WHILE loop for everything, but the others make your logic easier to understand.

Breaking the Pattern: Skip and Exit Tools

Sometimes you need to mess with how loops work. These tools let you skip ahead or bail out early.

Break: Exit the Loop Immediately

Think of BREAK like leaving a movie theater early. You were supposed to watch the whole thing, but something came up and you leave now.

Example (searching for your keys):

SET items TO ["book", "pen", "keys", "phone", "wallet"]
SET looking_for TO "keys"

FOR EACH item IN items:
    DISPLAY "Checking: " + item
    
    IF item equals looking_for THEN
        DISPLAY "Found " + looking_for + "!"
        BREAK (exit the loop now)
    END IF
    
    DISPLAY "Not " + looking_for + ", keep looking..."
END FOR

DISPLAY "Search ended"

TRY THIS WITH AI:

Ask your AI:

Simulate this search program.
Watch how it stops searching immediately after finding 'keys'.
Instead of checking 'phone' and 'wallet'.
Then change looking_for to 'wallet'.
And simulate it again to see the difference.

SET items TO ["book", "pen", "keys", "phone", "wallet"]
SET looking_for TO "keys"

FOR EACH item IN items:
    DISPLAY "Checking: " + item
    
    IF item equals looking_for THEN
        DISPLAY "Found " + looking_for + "!"
        BREAK (exit the loop now)
    END IF
    
    DISPLAY "Not " + looking_for + ", keep looking..."
END FOR

DISPLAY "Search ended"

Then ask:

Why is using BREAK more efficient than letting the loop check all items?
When you've already found what you need?

Continue: Skip to the Next Loop

Think of CONTINUE like skipping a song. You don’t stop listening to music entirely, you just skip this one song and move to the next.

Example (filtering spam comments):

SET comments TO ["Great post!", "SPAM LINK", "I agree!", "SPAM", "Thanks!"]

FOR EACH comment IN comments:
    IF comment starts with "SPAM" THEN
        DISPLAY "Skipping spam..."
        CONTINUE (skip to next comment)
    END IF
    
    DISPLAY "Reading: " + comment
END FOR

TRY THIS WITH AI:

Ask your AI:

Simulate this comment filter program.
Show me which comments get read and which get skipped.

SET comments TO ["Great post!", "SPAM LINK", "I agree!", "SPAM", "Thanks!"]

FOR EACH comment IN comments:
    IF comment starts with "SPAM" THEN
        DISPLAY "Skipping spam..."
        CONTINUE
    END IF
    
    DISPLAY "Reading: " + comment
END FOR

Then ask:

What's the difference between using CONTINUE 
versus just putting the 'Reading' display inside an ELSE block?

Do these make code messy? They can if you overuse them. But when used correctly, they actually make code clearer because they communicate intent: “I’m done with this loop” or “Skip this item.”

Nesting: Putting Structures Inside Each Other

Nesting means putting one control structure inside another. A loop inside a loop. An IF inside a loop. This is where things get mentally challenging.

Here’s the truth: nesting is like those Russian stacking dolls. Each layer is simple on its own, but when you stack them, you need to keep track of what’s inside what.

Example (weekly class schedule):

SET Monday_classes TO ["Math", "Science", "History"]
SET Tuesday_classes TO ["English", "PE"]
SET Wednesday_classes TO ["Math", "Art", "Science"]
SET Friday_classes TO []

DISPLAY "Monday:"
IF Monday_classes is not empty THEN
    FOR EACH subject IN Monday_classes:
        DISPLAY "  - " + subject
    END FOR
ELSE
    DISPLAY "  - No classes!"
END IF

DISPLAY "Tuesday:"
IF Tuesday_classes is not empty THEN
    FOR EACH subject IN Tuesday_classes:
        DISPLAY "  - " + subject
    END FOR
ELSE
    DISPLAY "  - No classes!"
END IF

See what happened? We have:

  • An IF statement (do we have classes?)
  • Inside that IF, a FOR EACH loop (for each class)

TRY THIS WITH AI:

Ask your AI:

Simulate this class schedule program. 
Show me what gets displayed for Monday and Tuesday.

SET Monday_classes TO ["Math", "Science", "History"]
SET Tuesday_classes TO ["English", "PE"]
SET Wednesday_classes TO ["Math", "Art", "Science"]
SET Friday_classes TO []

DISPLAY "Monday:"
IF Monday_classes is not empty THEN
    FOR EACH subject IN Monday_classes:
        DISPLAY "  - " + subject
    END FOR
ELSE
    DISPLAY "  - No classes!"
END IF

DISPLAY "Tuesday:"
IF Tuesday_classes is not empty THEN
    FOR EACH subject IN Tuesday_classes:
        DISPLAY "  - " + subject
    END FOR
ELSE
    DISPLAY "  - No classes!"
END IF

Then ask:

Walk me through just the Friday section step by step.
What happens when Friday_classes is empty?
Which parts of the nested structure execute and which don't?

Each piece is simple. The challenge is tracking which piece you’re in. But here’s the secret: you don’t need to understand all of it at once. You read it from the outside in.

How to avoid getting lost: Notice how the inner parts are indented (moved to the right)? That shows what’s inside what. It’s like those indented bullet points in your notes—the indentation shows the hierarchy.

Putting It All Together: A Real Example

Let’s combine everything we’ve learned into one practical program.

Example (grade calculator for multiple students):

SET student1_name TO "Ana"
SET student1_scores TO [85, 92, 78, 88]

SET student2_name TO "Juan"  
SET student2_scores TO [95, 98, 100, 94]

SET student3_name TO "Maria"
SET student3_scores TO [72, 68, 75, 70]

SET passing_grade TO 75

// Process Ana
SET total TO 0
FOR EACH score IN student1_scores:
    SET total TO total + score
END FOR
SET average TO total divided by 4

DISPLAY student1_name + "'s average: " + average

IF average is 90 or higher THEN
    DISPLAY "  Grade: A - Excellent work!"
ELSE IF average is passing_grade or higher THEN
    DISPLAY "  Grade: Passing - Good job!"
ELSE
    DISPLAY "  Grade: Needs improvement"
    DISPLAY "  Recommend tutoring"
END IF

// (Same process repeats for Juan and Maria)

This program uses:

  • FOR EACH loop (adding up scores)
  • IF-ELSE-IF chain (determine grade)
  • Sequential execution (calculate average before checking grade)

TRY THIS WITH AI:

Ask your AI:

Simulate this grade calculator for Ana only. 
Walk me through step by step: 
- how the loop adds up her scores
- how the average gets calculated
- which grade message gets displayed

SET student1_name TO "Ana"
SET student1_scores TO [85, 92, 78, 88]

SET student2_name TO "Juan"  
SET student2_scores TO [95, 98, 100, 94]

SET student3_name TO "Maria"
SET student3_scores TO [72, 68, 75, 70]

SET passing_grade TO 75

// Process Ana
SET total TO 0
FOR EACH score IN student1_scores:
    SET total TO total + score
END FOR
SET average TO total divided by 4

DISPLAY student1_name + "'s average: " + average

IF average is 90 or higher THEN
    DISPLAY "  Grade: A - Excellent work!"
ELSE IF average is passing_grade or higher THEN
    DISPLAY "  Grade: Passing - Good job!"
ELSE
    DISPLAY "  Grade: Needs improvement"
    DISPLAY "  Recommend tutoring"
END IF

// (Same process repeats for Juan and Maria)

Then try:

Add a fourth student named Claudia with four test scores (from 0 to 100).
Simulate the program using Claudia's data and determine her grade.

Finally ask:

Can you modify this pseudo code to count how many total students are:
- passing
- need help

Then simulate running the modified version.

Bonus Pre-cursor to Learning Python:

Can you give me a Python version of the grade calculator?

Did you get something like this?

# Student data
students = {
    "Ana":    [85, 92, 78, 88],
    "Juan":   [95, 98, 100, 94],
    "Maria":  [72, 68, 75, 70],
    "Claudia":[88, 91, 84, 95]
}

passing_grade = 75

# Counters
passing_count = 0
needs_help_count = 0

# Process each student
for name, scores in students.items():
    total = sum(scores)  # add up all scores
    average = total / len(scores)

    print(f"{name}'s average: {average:.2f}")

    if average >= 90:
        print("  Grade: A - Excellent work!")
        passing_count += 1
    elif average >= passing_grade:
        print("  Grade: Passing - Good job!")
        passing_count += 1
    else:
        print("  Grade: Needs improvement")
        print("  Recommend tutoring")
        needs_help_count += 1

    print()  # blank line for readability

# Final summary
print(f"Total students passing: {passing_count}")
print(f"Total students needing help: {needs_help_count}")

Key Takeaways

Let’s recap what actually matters here.

Programs need three basic abilities:

  1. Do things in order (sequence)
  2. Choose between options (selection with IF, ELSE, SWITCH)
  3. Repeat actions (loops like FOR, WHILE, FOR EACH)

Everything else—the different types of IF statements, the different types of loops, the BREAK and CONTINUE tools—are just variations designed to make your logic clearer in different situations.

You don’t need to memorize which tool to use when. As you start writing code, you’ll naturally reach for the tool that makes sense. It’s like grammar—you don’t consciously think “I need a comparative adjective here.” You just say “This pizza is better than that one” because it sounds right.

What you should remember from this article:

  • Control flow = the system that lets programs make decisions and repeat actions
  • IF/ELSE/SWITCH = different tools for choosing between options (pick the clearest one)
  • Loops = different tools for repeating actions (pick the one that matches your situation)
  • BREAK/CONTINUE = tools for fine-tuning loop behavior (use sparingly)
  • Nesting = putting structures inside each other (read from outside in, watch the indentation)

Most importantly: you don’t need to be an expert in control flow before you start coding. You learn by doing. Start with simple IF statements. Then simple loops. Then combine them when you need to. You’ll build up naturally.

The exercises you did with AI showed you how these concepts actually work in practice. That’s the key—control flow isn’t just theory. It’s how every program you’ve ever used makes decisions and handles repetition. Your weather app checking conditions. Your music app looping through playlists. Your game checking if you won. It’s all control flow.

Now you understand the foundation of how programs think.

This completes our Fundamentals of Programming series. You’ve learned how to think like a programmer, understand data types and structures, handle input and output, and control program flow. These are the building blocks that everything else in programming builds upon. Keep practicing, keep building, and most importantly, keep thinking about how to break problems down into sequences, selections, and iterations.

2 responses to “Control Flow Algorithms: Fundamentals of Programming Part 4”

  1. […] For the last topic in this series, let’s unravel control flow algorithms. […]

  2. […] humble tools of logic. Stack enough of them, and you get reasoning. Stack them higher, and you get planning. Stack them […]

Leave a Reply

Discover more from Tech Goes BRRR

Subscribe now to keep reading and get access to the full archive.

Continue reading