[SOLVED] Passing Array into Function in C++

Issue

I am currently working on a c++ program that uses the function. When I run the code, I am getting 3 error that

error: ‘userInput’ was not declared in this scope
error: ‘displaySum’ was not declared in this scope
error: ‘displayAverage’ was not declared in this scope

I’m not sure if the problem is the passing the array into function or I forgot to declare the function itself.

Here is the code.

#include <iostream>
using namespace std;
int main()
{
    int numbers[10];
    
    userInput(numbers, 10);
    displaySum(numbers, 10);
    displayAverage(numbers, 10);
    
    return 0;
    
}

void userInput(int input[], int num)
{
    for (int i = 0; i <= num; i++)
    {
        cout << "Enter #" << i <<": ";
        cin >> input[i];
    }
}

void displaySum(int averageResult[], int num, int sum)
{
    for (int i = 0; i <= num; i++)
    {
        sum += averageResult[i];
        cout << "\nSum:" << sum;
        
    }
}

void displayAverage(int averageResult[], int num, int sum, int average)
{
    for (int i = 0; i <= num; i++)
    {
        sum += averageResult[i];
        average = sum / i;
        
        cout << "Average:" << average;
        
    }
}

Solution

userInput(numbers, 10);

When your C++ compiler reaches this line it will have absolutely no idea what this mysterious function called userInput() is all about. The C++ program gets compiled in logical order, from beginning to the end, and this function has not been declared yet.

You will need to add a forward declaration at the beginning of the file:

void userInput(int input[], int num);

This declares the function. The actual definition of the function can remain where it is, after your main. This forward declaration tells your C++ compiler what this function is all about.

The same thing applies to the other functions in your program.

Additionally, your program has one more fatal bug that you will discover after fixing this compilation error:

for (int i = 0; i <= num; i++)
{
    cout << "Enter #" << i <<": ";
    cin >> input[i];
}

Your num array has 10 values, it is declared as int numbers[10];. In C++ array indexes begin with 0, not 1, so this means that the values in your array are numbers[0] through numbers[9].

If you work out, on paper and pencil, what the above for loop does: you will discover that it iterates with values of i ranging from 0 to 10. The loop’s condition is i <= num, with num being 10, so 10 <= 10 is obviously true.

Subsequently this loop will attempt to initialize numbers[10] which does not exist, resulting in undefined behavior and a likely crash.

You will need to fix this bug here, and in your other for loops, which all have the same bug.

Answered By – Sam Varshavchik

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.