C++ Starter · free course

Free course · Lesson 2 of 5

Control Flow & Functions

In this lesson you will

  • Make decisions with if/else and repeat work with loops
  • Write functions with parameters and return values

C++ control flow (if, for, while) will look familiar if you've seen any C-family language. Functions must declare the type they return, and every parameter's type is fixed — the compiler checks all of it before your program ever runs.

  • for (int i = 0; i < n; i++) { } is the standard counting loop.
  • A function signature looks like double average(int total, int count).
  • void return type means the function performs an action but returns nothing.
  • Declaring a function before main() (or in a header file) lets you call it from anywhere.

💡 Practical Skill: Writing small, focused functions is just as valuable in C++ as in any language — and essential once programs grow past a single file.

Worked exampleAttendance Threshold Check
C++
#include <iostream>#include <string> std::string checkStatus(int classesAttended, int totalClasses) {    double rate = (double)classesAttended / totalClasses * 100;    if (rate >= 80) return "Eligible for certificate";    if (rate >= 60) return "Needs make-up session";    return "At risk — contact student";} int main() {    int attendance[] = {18, 15, 20, 9, 17};    int studentCount = 5;     for (int i = 0; i < studentCount; i++) {        std::cout << "Student " << (i + 1) << ": "                  << checkStatus(attendance[i], 20) << std::endl;    }    return 0;}

Practice exercise

Write a function that returns whether a number is even, then use a loop to print the even numbers from 1 to 20.

Key takeaways

  • Conditions choose what runs; loops repeat it
  • Functions name a task so it can be reused and tested
  • Pass large objects by const reference to avoid copies
In the full program Module 2: Control Flow and Functions in C++ See how this topic is taught in depth, with practical activities and an assessment.

Free self-study lesson — no certificate. For the full instructor-led program, see registration options.