[Solved] How to use functions in c++?


The part you’re missing is the return type of the function, and then to actually return that value from the function.

At the moment you have

void compute_sum(int limit) // compute_sum function
{
    int sum_to_limit;
    sum_to_limit = limit * (limit + 1) / 2;
}

A function prototype in C looks pretty much like this

<return type> <name> (<parameters>)
{
    // your logic here

    return <your_own_variable> // Note: You can omit this if the return type is void (it means the function doesn't return anything)
}

You want to modify your function so you are returning the integer value you’re calculating inside of it

int compute_sum(int limit) // compute_sum function
{
    int sum_to_limit;
    sum_to_limit = limit * (limit + 1) / 2;
    return sum_to_limit;
}

So what happens is after main runs, when the the point of execution hits

compute_sum(maxNumber);

The program flow jumps to that function and executes the code inside of it. When the function finishes, it returns the value back to where it was originally called from. So you also need to add this to store the value returned

int result = compute_sum(maxNumber);

and then make sure to output that value to the user.

You can also make the computer_sum function a little more terse my not storing a temporary variable, you can just do this

int compute_sum(int limit) // compute_sum function
{
    return limit * (limit + 1) / 2;
}

I hope that helps. There’s a lot more going on behind the scenes but that’s the basic idea. Good luck! 🙂

4

solved How to use functions in c++?