Question

I need some help creating an array with 10 number that the user can pick. Had a post about this yesterday but misstook arrays for vectors..

Need to calculate the average value of the numbers, need pseudocode for it as well. Any help would be awesome, I do have a school book but the array examples in it will just not work (as you can se in the code I'll add).

This is what I got sofar:

#include <iostream>
#include <array>
using namespace std;


int main()
{
    int n[10];

    for (int i = 0; i < 10; i++)
    {
        cout << "Please enter number " << i + 1 << ": ";
        cin >> n[i];
    }



    float average(int v[], int n)
    {
        float sum = 0;
        for (int i = 0; i < n; i++)
        {
            sum += v[i]; //sum all the numbers in the vector v
        }

        return sum / n;
    }
system("pause");
}

the part to calculate the average I got help with from the last post I had. But everything else won't work "/ So basicly I need help to make a array with 10 user input numbers. Cheers

Was it helpful?

Solution

The only thing that you wrote correctly is function average. I would add qualifier const to the parameter of the function

#include <iostream>
#include <cstdlib>
using namespace std;

float average( const int v[], int n )
{
    float sum = 0.0f;

    for ( int i = 0; i < n; i++ )
    {
        sum += v[i]; //sum all the numbers in the vector v
    }

    return sum / n;
}

Or statmenet

return sum / n;

could be substituted for

return ( n == 0 ? 0.0f : sum / n );

Take into account that functions shall be defined outside any other functions and a function declaration shall appear before usage of the function.

You need not header <array> because it is not used. But you need to include header <cstdlib> because you use function system.

As it is written in your assigment you need enter arbitrary values for the array

int main()
{
    const int N = 10;
    int a[N];

    cout << "Enter " << N << " integer values: ";
    for ( int i = 0; i < N; i++ ) cin >> a[i];

    cout << "Average of the numbers is equal to " << average( a, N ) << endl;

    system( "pause" );
    return 0;
}

OTHER TIPS

int n[10]; - n is an array of ints, not strings, so why are you doing n[0] = "Number 1: ";? You should instead loop and ask for an input from the user.

After you do this, you should place average function outsude the main function and call it from the main.

I advise you to go through a basic tutorial.

  1. Function definition should always be outside main.
  2. int n[10] mean n is array of integers of size 10. They are not array of pointers of type char * to hold strings
  3. There isn't a caller for function average. Subroutines work like, callers will call callee passing arguments to perform operations on them and return them back - pass by reference.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top