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 avoidfunction calledgreetthat printsWelcome!.Call
greettwice frommain.
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 printsHello,followed byname.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 returnsx * x.In
main, printsquare(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 ofaandb.Print
average(3, 4). You should get3.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 returnsc * 9 / 5 + 32.Print
100C is 212FusingtoFahrenheit(100).Print
37C is 98.6FusingtoFahrenheit(37).