Introduction to Functions
In this chapter, we'll learn about functions in C++. Imagine you need to calculate the area of three rectangles. For this, we need their width and height and multiply them. We could do this with the following code:
#include <iostream>
int main() {
int width1 = 5;
int height1 = 6;
int area1 = width1 * height1;
std::cout << area1 << std::endl; // Prints 30
int width2 = 10;
int height2 = 5;
int area2 = width2 * height2;
std::cout << area2 << std::endl; // Prints 50
int width3 = 1;
int height3 = 5;
int area3 = width3 * height3;
std::cout << area3 << std::endl; // Prints 5
}
This is tedious and you can surely imagine that calculating the area of 100 rectangles this way would be madness.
In programming, we usually try to avoid repeating the same code multiple times. Instead, we can group a part of code that repeats and reuse it. We achieve this using functions. A function is a reusable piece of code that solves a specific problem.
Instructions
When you're ready, proceed to the next exercise!
Start programming for free
1/7