How to read before EOF and print even / odd numbers?

I have code below C that reads user input to the end of the file (ctrl + d) and stores them in an array. Then it should print all the odd numbers on the line, and then even the numbers on another line. For some reason, it does not work as expected.

When I enter the following:

1 2 4 16 32 64 128 256 512 1024 2048 4096 the output is: Odd numbers were: Even numbers were: 2 16 64 256 1024 4096 Expected output: Odd numbers were: 1 Even numbers were: 2 4 16 32 64 128 256 512 1024 2048 4096 

Code below:

 #include <stdio.h> int main(void){ int array[1000]; int i,j,k; int counter = 0; for(i=0; scanf("%d", &array[i]) != EOF; i++){ scanf("%d", &array[i]); counter = counter+1; } printf("Odd numbers were: "); for(j=0; j<counter; j++){ if(array[j]%2 != 0){ printf("%d ", array[j]); } } printf("\n"); printf("Even numbers were: "); for(k=0; k<counter ; k++){ if(array[k]%2 == 0){ printf("%d ", array[k]); } } printf("\n"); } 
+5
source share
2 answers

There is an easier solution to your problem.

I hope you will like it

 #include<stdio.h> int main() { int num,od = 0, ev = 0; int odd[1000],even[1000]; while(scanf("%d",&num) == 1) { if(num%2==0) { even[ev] = num; ev++; } else { odd[od] = num; od++; } } printf("Odds numbers are: "); for(int i = 0;i<od;i++) { printf("%d ",odd[i]); } printf("\nEven numbers are: "); for(int i = 0;i<ev;i++) { printf("%d ",even[i]); } return 0; } 

program output corresponds to the expected result

Happy coding

+5
source

Well, you took a completely different approach, but your example was wrong because you did scanf at each step of the loop, and then another inside the for body, so you did two scanf at each pass of the loop, which caused the second value to kill the first in the element array i . This made you lose half the items you read and explain the result. Just reset scanf inside the loop body so that it works fine, perhaps.

0
source

All Articles