For the complete documentation index, see llms.txt. This page is also available as Markdown.

🐝Control Flow

So far, our programs have executed line-by-line, step-by-step from top to bottom. In the real world however, we might want to

  • make decisons based on a condition

  • repeat certain actions

  • organise logic into reusable pieces

This is where control flow comes in

Conditionals

Conditionals let our program make decisions.

main.cpp
int score = 85;

if (score == 100) {
    std::cout << "Perfect" << std::endl;
} else if (score >= 90) {
    std::cout << "Grade A" << std::endl;
} else if (score >= 80) {
    std::cout << "Grade B" << std::endl;
} else if (score >= 70) {
    std::cout << "Grade C" << std::endl;
} else {
    std::cout << "Needs improvement" << std::endl;
}

⚠️ Common Pitfall

= means assignment while == checks for equality

Loops

Loops lets us repeat certain blocks of code

while loop

A while loop keeps running as long as the condition is fufilled.

Code
Output

for loop

A for loop is useful when we know how many times we want to repeat something.

break / continue

break forces the loop to terminate prematurely.

continue skips the rest of the current iteration.

Functions

Functions let us group code into reusable blocks.

Basic Usage

Here:

  • void means the function does not return anything

  • greet is the function name

  • greet() calls the function, causing Hello! to be printed.

Function Parameters

Our current greet function always print the same message (which isn't very flexible). Let's augment it by adding a parameter so that our greeting message can change depending on the person.

Functions Return Value

A return value is the value the function sends back to the caller after it's done executing. At the call site, you can use the result however you wish.

Exercise(s)

⭐ Write a function countdown(int n) that takes in a number n and prints from n down to 1.

⭐⭐ Write a program that hardcodes a secret number. It will repeatedly ask the user to guess. Depending on the user's guess, the program will feedback Too low, Too high or Correct.

Last updated

Was this helpful?