Functions
A function is a named block of code you can run again and again. In C++ you write its return type, its name and its parameters: int square(int n) { return n * n; }
void means a function returns nothing; it just does something, like printing.
C++ reads your file from top to bottom, so write a function above main before you call it. Open Step through to see how a call jumps into the function and comes back with the answer.
Example
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}
Output
5
The return type before the name must match what you return: an int function returns an int.
Your tasks
0 of 3 done- Define int square(int n)
- Return the number multiplied by itself
- Define square above main
Tutor
The tutor guides you toward the answer instead of handing it over. It uses your own Claude usage.
Quick check
What does void mean in void greet()?
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.
1#include <iostream>
2
3int square(int n) {
4 return n * n;
5}
6
7int main() {
8 int a = square(3);
9 int b = square(a);
10 std::cout << a << " " << b << std::endl;
11 return 0;
12}
The program always starts in main, even though square is written above it.
Variables
| No variables yet |
Output
Step 1 of 9