Home > Software design >  How do i create a counter in c?
How do i create a counter in c?

Time:11-17

Im trying to write a code that can tell the difference between an even number and odd number. Even numbers need to be added while the Odd numbers need to have a counter. Any way to fix what i tried?

#include <stdio.h>
#include <stdlib.h>

int main()
{
int i;
int number;
int Odd = 0;
int Even = 0;

printf("Please enter 10 integers:");
for(i=0; i<=10; i  )

    scanf("%d", &number);
    if(number % 2 == 0){
       Even = number   1;
    }
    else{
        Odd =  number   1;
    }
printf("Even number sum = %d\n", Even);
printf("Odd number counter = %d\n", Odd);


return 0;
}

CodePudding user response:

As the comments on your post describe, your Even = number 1 is not doing much.

If i understood correctly, you want all even numbers to be added and count how many odd numbers have been introduced. You could acomplish this by simply changing your if from:

if(number % 2 == 0){
   Even = number   1;
}
else{
    Odd =  number   1;
}

to

if(number % 2 == 0){
   Even = Even   number;
}
else{
    Odd =  Odd   1;
}

Needless to say it can be simplified to Even = number; and Odd ;

CodePudding user response:

You have a couple things wrong with your code.

As others have already mentioned your logic for adding the Even numbers and counting Odds is wrong.

Also, you need to add braces to your for loop like so:

for(i=0; i<10; i  )
{
    scanf("%d", &number);
    if(number % 2 == 0)
    {
       Even = Even   number;
    }
    else
    {
        Odd = Odd   1;
    }
}
  •  Tags:  
  • c
  • Related