this is my program do i answer the question??

i also cannot get the sum for even and odd number, it just give me rubbish number....

#include<iostream>
using namespace std;

int main()
{
int x[20],odd=0,even=0;
int evenArray;
int oddArray;

cout << "This program accepts integers until 20.\nPlease enter a value: "<<endl;
for ( int i = 0; i < 20; i++ )
{
cin>>x[i];
}
for ( int m = 0; m < 20; m++ )
{
if ( x[m]%2==0)
evenArray += x[m];
}
for ( int n = 0; n < 20; n++ )
{
if ( x[n]%2!=0)
oddArray += x[n];
}
cout<<"Sum of even numbers = "<<evenArray<<endl;
cout<<"Sum of odd numbers = "<<oddArray<<endl;
system("pause");
return 0;
}
Last edited on
You were not initializing the variables evenArray and oddArray to zero, as you should always do.

This code works correctly:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;

int main()
{
    int x[20],odd=0,even=0;
    int evenArray = 0;
    int oddArray = 0;

    cout << "This program accepts integers until 20.\nPlease enter a value: "<<endl;
    for ( int i = 0; i < 20; i++ ) {
        cin>>x[i];
    }
    for ( int m = 0; m < 20; m++ ) {
        if ( x[m]%2==0)
            evenArray += x[m];
    }
    for ( int n = 0; n < 20; n++ ) {
        if ( x[n]%2!=0)
            oddArray += x[n];
    }
    cout<<"Sum of even numbers = "<<evenArray<<endl;
    cout<<"Sum of odd numbers = "<<oddArray<<endl;

    return 0;
}


One more thing: there is no need to use two for-loop to sum the even and the odd numbers: you can simply write

1
2
3
4
5
6
    for ( int m = 0; m < 20; m++ ) {
        if ( x[m]%2==0)
            evenArray += x[m];
        else
            oddArray += x[m];
    }
Topic archived. No new replies allowed.