kobowo
kobowo

Reputation: 2787

I have a (logical?) error on my loop with an array

Okay so bear with me if my title was very vague. I even tried googling my problem and searching it here but I really can't think of a sentence that would best describe my problem.

I have an assignment and it goes like this:

Write a program that reads a set of integers and then finds and prints the sum of the even and odd integers

I thought of the solution already and determined to use an array to store the numbers that the user will input and using an if/else statement to add the even and odd numbers together. So far my code below words for even numbers but I really can't find the reason why whenever I try to add the odd numbers it ends up with a really large number.

Ex: I enter 13 and 17, I'll get 4253907, this does not affect the even numbers whatsoever even if I place the odd and even numbers in specific indices of the array. The even numbers will add properly but the odd numbers won't.

Here's what I've got so far

int length, evenSum, oddSum, temp, arsize;
cout <<"Input how many integers will be evaluated:  ";
cin >> length;
arsize = length-1;
int num[arsize];

for(int i = 0; i<=arsize; i++)
{
    cout<<"Input integer " << i+1 <<": ";
    cin>>num[i];
}

for(int i = 0; i<=arsize; i++)
{
    if(num[i]%2 != 0)
    {

        oddSum += num[i];

    }

 else 
    evenSum += num[i];
}

cout << "Sum of even integers: " << evenSum << endl;
cout << "Sum of odd integers: " << oddSum;

Upvotes: 1

Views: 73

Answers (1)

Naman
Naman

Reputation: 31868

This should help :

int evenSum = 0, oddSum = 0;

initialise the variables.

Upvotes: 1

Related Questions