Why isn't my array printing the correct output?(even numbers from 0-50)

I'm using a function to find all the even numbers from an array, ranging from 0-50. Without using a function, it's very simpple. However, using size = 50; I'm not getting the expected outcome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
void arrayFill(int evenArray[], int size);
int main()
{

    int size = 50;
    int evenArray[size];
    
    arrayFill(evenArray, size);
    
    return 0;
}

void arrayFill(int evenArray[], int size)
{
    for (int i = 0; i <= size; i = i + 2)
    {
        cout << evenArray[i] << endl;
    }
} 


The output is:
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
1971728815
8
2006565836
-1
2686564
12
2686648
3670016
1971728815
12
2006565836
-1
2686628
0
2686644
3677440
4200976
2686668
1972398152
1971712942
1971732984
-819286188
4199104
4200976
16
1971810848


When it should be
2
4
6
....
50
Last edited on
You don't initialize your array so it just contains random numbers.
You access your array out of bounds for (int i = 0; i <= size; i = i + 2).
The last element is size - 1
Last edited on
Topic archived. No new replies allowed.