0

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!

2 Answers 2

1

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 ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Marco!!! This worked! I'll have to remember this easy but very effective way of solving exercises with dynamic arrays.
You're Welcome Kahn. Have a nice day ;)
0

The initialization:

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

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

 array[0]

1 Comment

Where does it go wrong then? I don't seem to understand your remark. i can't seem to distinguish this from my sum that I have. Does it do -1 since -1 is in the first element?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.