Kahn Kah
Kahn Kah

Reputation: 1453

Dynamic Array C++ not working right

I have a problem with my dynamic array.

The exercise goes as follows:

Let the user input a N-amount of numbers and let the program stop if the user puts in the number -1. Give the sum of all the numbers in the end.

Example:

Number 1: 10

Number 2: 10

Number 3: -1

The sum of the numbers is: 20.

My code is working but it keeps giving the sum -1, so my output of sum is 19, not 20.

This is my code:

int number = 0;
int sum=0;
int *array = new int[number];

do
{
cout <<"Number " << (i+1) << ": ";
cin >> array[number];
i++;
sum+=array[number];
} while (array[number] != -1);


cout <<"Sum of the numbers is: " << sum;

delete[] array;

If I edit my:

cout << sum;

To:

cout << sum+1;

It works perfect, but this doesn't feel as a correct way of making the exercise. I think my teacher won't approve that way of solving this exercise. Or is the way I think the correct way of solving this exercise?

I would love to learn my mistake and the correct way of solving this problem.

Thank you!

Upvotes: 0

Views: 474

Answers (2)

Marco Cadei
Marco Cadei

Reputation: 145

Maybe you could do something like this:

bool continue = true;
while(continue)
{
    cout <<"Number " << (i+1) << ": ";
    cin >> array[number];
    i++;
    if(array[number] == -1)
        continue = false;
    else
        sum+=array[number];
}

Try this and let me know ;)

Upvotes: 1

Yotam
Yotam

Reputation: 888

The initialization:

int number = 0;
int *array = new int[number];

Gives a 0-sized array. You cannot access its 'first' element

 array[0]

Upvotes: 0

Related Questions