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
- What is a Function? — A function is a named block of code that does a specific job. Instead of writing the same code over and over, you put it in a function and call it whenever you need it. You have already used functions — cout, cin, sort, reverse, min, max. Now you will learn to create your own!
- Why Use Functions? — Functions help in three big ways: (1) Reusability — write once, use many times. (2) Readability — your code is easier to understand when broken into named pieces. (3) Debugging — if something is wrong, you only fix it in one place. In CP, functions make your code shorter and less error-prone!
- Function Syntax — A function has: return_type name(parameters) { body } For example: int add(int a, int b) { return a + b; } The return type says what the function gives back (int, double, string, bool). The parameters are the inputs. The return statement sends back the answer.
- Calling a Function — To use a function, you call it by name and pass the inputs: int result = add(3, 5); The values 3 and 5 are called 'arguments' — they are the actual values that fill in the parameters. The function runs, calculates the answer, and returns it to you.
- Void Functions (No Return) — Some functions just do something without giving back a value — like printing a message or modifying an array. These use 'void' as the return type: void sayHello() { cout << "Hello!"; } You call them without storing a result: sayHello(); No return statement needed.
- Parameters vs Arguments — Parameters are the variable names in the function definition (like placeholders). Arguments are the actual values you pass when calling. In int add(int a, int b), 'a' and 'b' are parameters. In add(3, 5), '3' and '5' are arguments. The arguments get copied into the parameters.
- Functions Must Be Declared Before Use — In C++, you must define a function before you call it. If you write your functions above main(), they will work fine. You can also write a 'prototype' at the top (just the header with a semicolon) and define the full function later. In CP, most people just write functions above main().
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. int add(int a, int b) — takes two integers and returns their sum.
- 2. bool isEven(int n) — returns true if n is divisible by 2, false otherwise.
- 3. int maxOfThree — uses the built-in max() to find the biggest of three numbers.
- 4. void printStars — prints stars but returns nothing (void means no return value).
- 5. In main(), we call add(3, 5) — the 3 goes into 'a' and 5 goes into 'b'.
- 6. isEven(4) returns true, isEven(7) returns false — the ternary operator prints Yes/No.
- 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
- Functions in C++ — Complete Guide (The Cherno)
- Functions — LearnCpp (LearnCpp)
- Function Practice Problems (HackerRank)