You must keep track of the count, or else you won't know what index to use for the array. Your current code doesn't work because you're leaving gaps in the array between the even numbers:
for (x = 0; x != 5; x++) {
scanf("%d", &n);
if (n % 2 == 0) {
array[x] = n;
g++;
}
For the input "2 3 5 6 7", you are storing the number 2 at position 0 in the array, and the number 6 at position 3. At the other positions there is random data. They aren't even zero values because you declared the array inside a function. By the way, a fixed-size array should be declared in the global scope, outside any function. That's because variables inside a function are allocated in a stack frame, which is a small and transient piece of memory. You want your arrays on the heap, which is big and long-lived.
The following code contains several improvements. It defines a constant for the length of the array, and checks the current count before saving a number. (Bad things happen if you write beyond the end of an array.) Also, this code imposes no fixed limit on the amount of data it will read. It keeps calling scanf
until the end-of-file value, EOF
, is returned.
#include <stdio.h>
#include <stdlib.h>
#define MAX_COUNT 1000
int even[MAX_COUNT];
int main() {
int x,
count = 0; /* Track the number of even numbers. */
while (scanf("%d", &x) != EOF) { /* Get an integer from standard input. */
if(x % 2 == 0) { /* Is it even? */
if (count == MAX_COUNT) { /* If so, check the count first. */
printf("I have reached the limit of %d! I cannot store %d.",
MAX_COUNT, x); /* Fail gracefully if the array is */
} else { /* full. Otherwise, we can go */
even[count++] = x; /* ahead and save the number. */
}
}
}
printf("There are %d even numbers.\n", count);
return 0;
}