else

Someone posted earlier and wanted two arrays - one for odd numbers and one for even. Since I'm a total newbie it sounded like a good exercise for me to try but I didn't want to post the code on that thread. At any rate my code works but generates a windows error - "Windows has generated errors and must be closed."

I'm sure it is the else statement but I can't figure out what's wrong it.

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

int main ()
{
    int num1[5];
    int num2[5];

    for (int n=0; n<10; n++) {
        if (n%2 == 0)
        {
            num1[n] = n;
            cout << "This number is even: " << num1[n] << '\n';
        }
        else
        {
            num2[n] = n;
            cout << "this number is odd: " << num2[n] << '\n';
        }
    }
    return 0;
}
Most likely because once you get up to n == 5 and above, you will be writing to invalid memory. You will need to increase the size of num1/num2 to at least 10.
Yep firedraco that does it. I don't understand why since I'm only assigning 5 integers to each array but nevertheless...

Thanks! I'm sure at some point in time knowing this odd behavior will come in handy.

ugh, nevermind I see why....the "for" is running ten times. doh! sorry.
Last edited on
or you could try
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main ()
{
    int num1[5];
    int num2[5];

    for (int n=0; n<10; n++) {
        if (n%2 == 0)
        {
            num1[n/2] = n;
        }
        else
        {
            num2[(n-1)/2] = n;
        }
    }
    return 0;
}

this way you would put 7 into num2[3] and 8 into num1[4]...
Yep hamsterman, that is not only better but is actually correct where mine is not. I believe the request was for each array to hold only odd or even numbers.
Because look at your code.

 
num1[n] = n;


This says that the nth element of num1 will be given the value n. Since n goes from [0...10), this means that the value 8 will be inserted as position 8 in the array. Your array has only 5 elements.

The fix is not to increase the size of the arrays because the way your code works, num1, which holds only even numbers, will only use elements 0, 2, 4, 6, and 8, and num2, which holds only odd numbers, will only use elements 1, 3, 5, 7, 9.
jsmith, thank you very much! Your post made me really think about what was happening in hamsterman's code. I wanna tell you it took a lot of head banging to finally see what you fellas were saying but it finally dawned on me.

num1[n/2] and num2[(n-1)/2] is actually assigning the correct value to the element, not just printing the output I wanted to see on the screen. Have I got it now? Hope your answer is yes, otherwise I might have to start looking for bandages. :)
Topic archived. No new replies allowed.