All lessons

5. Functions

Functions

0 of 5 activities0%

Reading 1

A function is a named block of work

Open

You declare a return type, a name, and parameters. The body runs when you call the function.

return sends a value back to the caller and ends the function. Use void when the function does not return a value.

Put your own functions above main, or declare them first and define them later. These lessons keep helpers above main.

int square(int x) {
    return x * x;
}

int main() {
    cout << square(4) << endl;  // 16
    return 0;
}

Check 2

What return does

Open

What does return x + 1; do inside a function?

Fill in 3

No result

Open

The return type you use when a function does not return a value is

Try it 4

Call square

Open

Run the program. Call square with another argument.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Write add

Open

Write a function add that takes two ints and returns their sum. In main, read two integers and print add(a, b).

main.cpp
Loading editor…