Functions

Programming Languages · C++ Loops & Vectors · 12 min

Write your own reusable commands with inputs and outputs.

Your own command

A function is a named block of code you can run whenever you like. Write it above main. void means it doesn't hand anything back:

void sayHi() {
    std::cout << "Hi!\n";
}

int main() {
    sayHi();
    sayHi();
}

Writing sayHi(); is called calling the function. This prints Hi! twice.

  • Above main, write a void function called greet that prints Welcome!.

  • Call greet twice from main.

Giving it inputs

A parameter is an input for a function. Put its type and name in the brackets. Whatever you pass in when you call it is used inside:

void cheer(std::string team) {
    std::cout << "Go " << team << "!\n";
}

cheer("Lions");   // Go Lions!
  • Write void sayHello(std::string name) that prints Hello, followed by name.

  • Call it with "Ada", then with "Linus".

Getting an answer back

Some functions hand a value back with return. Swap void for the type of the value you return:

int add(int a, int b) {
    return a + b;
}

std::cout << add(2, 3) << "\n";   // 5
  • Write int square(int x) that returns x * x.

  • In main, print square(7).

Two inputs, any type

Separate parameters with commas. The return type can be any type: int, double, bool, std::string...

bool canRide(int age, int height) {
    return age >= 8 && height >= 120;
}
  • Write double average(double a, double b) that returns the average of a and b.

  • Print average(3, 4). You should get 3.5.

Put it together: temperature converter

Write a function that turns Celsius into Fahrenheit, then use it twice. The formula is c * 9 / 5 + 32.

Write it in that order: c is a double, so the maths keeps its decimals.

  • Write double toFahrenheit(double c) that returns c * 9 / 5 + 32.

  • Print 100C is 212F using toFahrenheit(100).

  • Print 37C is 98.6F using toFahrenheit(37).

More in C++ Loops & Vectors

Previous: Vectors · Next: Strings