Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read until EOF and print the even/odd numbers entered?

Tags:

c

I have the below C code which reads user input until end of file (ctrl+d) and stores them in an array. Then, it should print all the odd numbers in a line and then even numbers on another line. For some reason it's not working 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 is 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");

}
like image 258
novice Avatar asked May 04 '17 10:05

novice


1 Answers

There is a easier solution for your problem

Hope you 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 matched with expected output

Happy Coding

like image 117
SHAH MD IMRAN HOSSAIN Avatar answered Oct 16 '22 20:10

SHAH MD IMRAN HOSSAIN