This is a simple C program which gets 100 numbers from user and counts even and odd numbers. Problem is that it gets 101 numbers instead of 100. i checked it twice and i can't figure it out.

#include <stdio.h> int main() { unsigned int i; int numbers[101]; int even = 0, odd = 0; printf("%s", "Enter 100 numbers:\n"); for (i = 0; i < 101; i++) { scanf("%d", &numbers[i]); if (numbers[i] % 2 == 0) even++; else odd++; printf("even is %d odd is %d\n", even, odd); } return 0; } 
6

2 Answers

Just change this:

int numbers[101]; 

to:

int numbers[100]; 

and this:

for (i=0; i<101; i++) 

to:

for (i=0; i<100; i++) 

Also so you wouldn't have to change this number in 2 places you could define a constant like this:

#define SIZE 100 

and then you can use the constant instead(int numbers[SIZE];, for (i=0; i<SIZE; i++))!

If you start counting from zero, you will count an extra number.

0 ... 1 => this is 2 numbers

0... 100 => this is 101 numbers

So count from 1 to 100, or from 0 to 99 - e.g.

for (i=0; i<100; i++)