Menu
Coddy logo textTech

Declare a Function

Part of the Fundamentals section of Coddy's C++ journey — lesson 51 of 74.

A function is a sequence of code that has a name. The purpose of a function is to reuse a piece of code multiple times.

For example, take a look at this code:

std::cout << "Welcome to Coddy";
std::cout << "New session...";
std::cout << "Welcome to Coddy";
std::cout << "Another session...";
std::cout << "Welcome to Coddy";

We use the same code std::cout << "Welcome to Coddy"; over and over again. Another issue with this code is that if we wanted to change the message: Welcome to Coddy to something different, like "Welcome aboard" it would have to change 3 different lines of code. To solve this issue, we will use functions.

To declare a function, we use the following syntax:

access_modifier return_type function_name(parameters) {
	// code
}

For our example, we will create a function named greet and it will look like this:

void greet() {
    std::cout << "Welcome to Coddy";
}

To use/call/execute the function, we write greet();:

int main() {
    greet();
    std::cout << "New session...";
    greet();
    std::cout << "Another session...";
    greet();
    return 0;
}

This will result in the same output as above.

Important! The function code must come before its call/execution

challenge icon

Challenge

Easy

Write a program that gets one input, a number. The input number indicates how many times to execute the described below function. 

Create a function that calculates the sum of all of the numbers between 1 and 1000 (including) and prints it, name the function however you like.

Note! In your code, write the function before its call/execution.

Cheat sheet

A function is a sequence of code that has a name, used to reuse code multiple times.

Function syntax:

access_modifier return_type function_name(parameters) {
    // code
}

Example function declaration:

void greet() {
    std::cout << "Welcome to Coddy";
}

To call/execute a function:

int main() {
    greet();
    return 0;
}

Important: The function must be declared before it is called/executed.

Try it yourself

#include <iostream>

// Function declaration
void sumNumbers() {
    // Complete the function
    
}

int main() {
    int n;
    std::cin >> n;
    for (int i = 0; i < n; i++) {
        // Call the function n times
    }
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals