Lesson 19 of 50 beginner

Functions — Your Helper Robots

Learn to create reusable blocks of code that make your programs cleaner and your CP solutions faster!

Open interactive version (quiz + challenge)

Real-world analogy

A function is like a helper robot you build. You teach it one specific job — like 'calculate the area of a rectangle.' Every time you need that job done, you just call the robot by name and give it the inputs (length and width), and it gives you back the answer. You build it once, use it a thousand times!

What is it?

A function is a self-contained block of code that performs a specific task. It takes inputs (parameters), processes them, and optionally returns an output. Functions are the building blocks of organized, reusable code — essential for writing clean competitive programming solutions.

Real-world relevance

Functions are everywhere in real life! A calculator app has functions for add, subtract, multiply, divide. A weather app has a function that converts Celsius to Fahrenheit. A game has a function that checks if two objects collide. Every app is built from hundreds of small functions working together.

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

// Function that returns the sum of two numbers
int add(int a, int b) {
    return a + b;
}

// Function that checks if a number is even
bool isEven(int n) {
    return n % 2 == 0;
}

// Function that returns the maximum of three numbers
int maxOfThree(int a, int b, int c) {
    return max(a, max(b, c));
}

// Void function — just prints, returns nothing
void printStars(int count) {
    for (int i = 0; i < count; i++) {
        cout << "*";
    }
    cout << endl;
}

int main() {
    // Calling our functions
    cout << "3 + 5 = " << add(3, 5) << endl;
    cout << "7 + 2 = " << add(7, 2) << endl;
    
    cout << "4 is even? " << (isEven(4) ? "Yes" : "No") << endl;
    cout << "7 is even? " << (isEven(7) ? "Yes" : "No") << endl;
    
    cout << "Max of 3, 7, 5: " << maxOfThree(3, 7, 5) << endl;
    
    printStars(5);   // Prints: *****
    printStars(10);  // Prints: **********
    
    return 0;
}
// Output: 3 + 5 = 8
//         7 + 2 = 9
//         4 is even? Yes
//         7 is even? No
//         Max of 3, 7, 5: 7
//         *****
//         **********

Line-by-line walkthrough

  1. 1. int add(int a, int b) — takes two integers and returns their sum.
  2. 2. bool isEven(int n) — returns true if n is divisible by 2, false otherwise.
  3. 3. int maxOfThree — uses the built-in max() to find the biggest of three numbers.
  4. 4. void printStars — prints stars but returns nothing (void means no return value).
  5. 5. In main(), we call add(3, 5) — the 3 goes into 'a' and 5 goes into 'b'.
  6. 6. isEven(4) returns true, isEven(7) returns false — the ternary operator prints Yes/No.
  7. 7. Each function is defined BEFORE main() so the compiler knows about it when main() calls it.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int result = square(5);
    cout << "5 squared = " << result << endl;
    return 0;
}

int square(int n) {
    return n * n;
}
Need a hint?
Look at where the function 'square' is defined relative to where it is called. Does the compiler know about 'square' when main() tries to use it?
Show answer
The bug is that the function 'square' is defined AFTER main(), but it is called inside main(). The compiler reads top to bottom, so when it sees square(5), it does not know what 'square' is yet! The fix is to either move the entire function definition above main(), or add a prototype 'int square(int n);' before main() to tell the compiler the function exists.

Explain like I'm 5

Imagine you have a magic recipe box. You label one box 'Make a Sandwich' and write the steps inside. Every time you are hungry, you don't have to remember all the steps — you just say 'Make a Sandwich!' and the recipe does the work. That is what a function is! You write the steps once, give it a name, and then just call it whenever you need it.

Fun fact

The concept of functions in programming was inspired by mathematical functions like f(x) = x + 1. But the idea of reusable 'subroutines' was first used by Ada Lovelace in the 1840s — she wrote the world's first algorithm for Charles Babbage's Analytical Engine, and she realized that parts of the algorithm could be reused. She was basically the inventor of functions!

Hands-on challenge

Write the following functions: (1) bool isPositive(int n) — returns true if n > 0. (2) int factorial(int n) — returns n! using a loop. (3) void printArray(int arr[], int n) — prints array elements separated by spaces. Then use all three in main()!

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero