Storing a fixed set of odd numbers between a given range and adding the sum of what is stored.

I am writing a program to store the first 20 odd numbers between 0-100 and provide the sum of all those odd numbers. using two user-defined functions.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
using namespace std;

double numbers[20];

double odd(double a[])
{
    double j=0;
    double sum_odd=0;

    for(int x=0; x<20; x++)
    {
        while(a[x]<100)
        {
            a[x]++;
            if(a[x] % 2 != 0)
            {
                cout<<a[x]<<"\n";
                numbers[x]=a[x];
                sum_odd = sum_odd + a[x];
            }
        }
    }
    return (sum_odd);
}
void printsum()
{
    cout<<"The sum of the odd numbers are: ";
}
int main()
{
    double b=0;

    cout<<"enter a number: ";
    cin>>b;

    b=odd(b);
    printsum();

    return 0;
}
-
From what I see the logic for what you are trying to accomplish is wrong.

If I gather correctly the logic is: in an array store the first 20 odd numbers between 1 and 100 in an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int oddnumers[20];
int arrayIndex =0;

// this should fill the array with the needed information.
for(int nCount =1; nCount < 101; nCount++)
{
    if(nCount % 2 != 0)
    {
           oddnumbers[arrayIndex] = nCount;
           arrayIndex++;
           if(arrayIndex > 19) break;
    }
}

// with the array filled we sum the array.
int sum = 0;
for(int nIndex = 0; nIndex < 20, nIndex++)
{ 
     sum+=oddnumbers[nIndex];
}

cout << "the sum of odds is " << sum << endl;


Printing the array should be pretty easy from the snippets I gave. I did not put these in functions they are only code snippets. The logic puts the last number in the array near 50 with every ten number you should get 5 odd numbers. You would overrun the array with getting every odd number between 1-100.

I am not going to finish the project for you but hopefully I pointed the logic in the right direction.
Topic archived. No new replies allowed.