user3063911
user3063911

Reputation: 1

different numbers output from an array than input using recursive function?

I am in the middle of making a recursive array function that counts the numbers and adds them together returning them in a recursive function. The function seems to actually work but the number I originally input into the array were 1,2,3,4,5 but the program tells me that those number are 49, 50, 51, 52, 53... Very confused on why this might be happening, any help or insight would be greatly appreciated. Thank you!

#include <iostream>
using namespace std;

const int SIZE = 5;//size of array
int sum(int [], int);//recursive function

int main()
{
    int sumArray[SIZE] = { '1', '2', '3', '4', '5'};//array with predetermined values

    cout << sumArray[0] << endl;//49
    cout << sumArray[1] << endl;//50
    cout << sumArray[2] << endl;//51
    cout << sumArray[3] << endl;//52
    cout << sumArray[4] << endl;//53

    cout << sum(sumArray, SIZE) << endl;//displays the amount 255 (5 elements added)

    system("pause");
    return 0;
}

int sum(int sumArray[], int size)
{
    if (size == 1)
        return sumArray[size - 1];
    else
    {
        cout << size << endl;
        return sumArray[size - 1] + sum(sumArray, size - 1);
    }
}

Upvotes: 0

Views: 325

Answers (1)

Spock77
Spock77

Reputation: 3325

You are actually put in the array ASCII-codes of the numbers: '1' is really a char with code 49 which is converted to int 49. Write as follows:

int sumArray[SIZE] = { 1, 2, 3, 4, 5 };

This is called implicit conversion - look at the section "Integral promotion."

Upvotes: 2

Related Questions