JJNgr
JJNgr

Reputation: 3

Function and Array in C++: Unexpected output

I need some help here please.

I just started learning C++ (coming from Python background).

I'm trying to familiarize myself with arrays and functions. Wrote a bunch of functions to do as stated, above each one.

However, the function which is supposed to sum elements in an array and return their sum, seem to be adding 10 to the result, no matter the argument supplied as input. What am I doing wrong please, as I can't seem to find this out. Any help on general layout of my code also would be appreciated.

// WORKING WITH ARRAYS AND FUNCTIONS

#include<iostream>

using namespace std;

// FUNCTION TO INSTANTIATE ARRAY INT OF LENGTH N.
int* array_creator(int n)
{
    static int ary_of_ten[10];  //declare array
    for (int i=0; i<n; i++)   //use loop to fill it up
    {
        ary_of_ten[i] = i+1;
    }
    return ary_of_ten;
}

//FUNCTION TO PRINT ARRAY ELEMENTS
void* array_printer(int arr[], int array_lenght)
{
    for (int i=0; i<array_lenght-1; i++)
    {
        cout << arr[i] << " ";
    }
    cout << arr[array_lenght-1] << endl;
}

//FUNCTION ACCEPTS INT ARRAYS AND RETURNS ARRAY OF SQUARE OF EACH ELEMENT
int* square_array(int *p, int array_length)
{
    const int ary_sz(array_length);
    static int sqd_values[10];
    for (int i=0; i<ary_sz; i++)
    {
        *(sqd_values + i) = *(p+i) * *(p+i);
    }
    return sqd_values;
}

//FUNCTION ACCEPTS INT ARRAYS AND RETURNS SUM OF ITS ELEMENTS
int sum_array(int *arry, int array_length)
{
    int summation;
    for(int i=0; i<array_length; i++)
    {
        summation += *(arry + i);
    }
    return summation;
}

int main()
{
    cout << sum_array(array_creator(10), 3) << endl;
    array_printer(array_creator(10), 10);           //print array of 1-10 elements
    array_printer(square_array(array_creator(10), 10), 10);     //prt arry of sqrd values
    return 0;
}

Upvotes: 0

Views: 64

Answers (1)

Gili Levy
Gili Levy

Reputation: 116

summation shuld be initialized to 0.

int summation=0;

Upvotes: 2

Related Questions