Trickfinger
Trickfinger

Reputation: 1

How can I take a variable multiple times and implement counters in while loop?

I want this program to determine if given integers are positive/negative & odd/even then increment the counters. But it doesn't work properly.

include <stdio.h>

int main() {
int evenCount=0, oddCount=0, posCount=0, negCount=0, zeroCount=0, m;
char x='x';

while(x!='y') {
 printf("enter an integer\n");
 scanf("%d", &m);
 if((m>0)&&(m%2==0)){
     posCount+=1;
     evenCount+=1;
 }
 else if((m>0)&&(m%2!=0)){
     posCount+=1;
     oddCount+=1;
 }
 else if((m<0)&&(m%2==0)){
     negCount+=1;
     evenCount+=1;
 }
 else if((m<0)&&(m%2!=0)){
     oddCount+=1;
     negCount+=1;
 }    
 else {
     zeroCount+=1;    
 }     
 printf("if you want to end the loop write 'y'\n");
 scanf("%c", &x);
}
printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);
return(0);
}

When I run it and give some numbers counts are at millions.

enter an integer
123
if you want to end the loop write 'y'
enter an integer
2
if you want to end the loop write 'y'
enter an integer
5
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564

The second example.

enter an integer
12
if you want to end the loop write 'y'
enter an integer
y
if you want to end the loop write 'y'
odd 6487572
even 6487576
positive 6487568
negative 6487564

I'm new to coding and this is my first post on this site also english is not my main language. I'm sorry if made any mistakes.

Upvotes: 0

Views: 94

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

For starters you need to change this call

scanf("%c", &x);

to

scanf(" %c", &x);

Pay attention to the space before the conversion specifier.

And instead of trying to output addresses

printf("odd %d \n", &oddCount);
printf("even %d \n", &evenCount);
printf("positive %d \n", &posCount);
printf("negative %d \n", &negCount);

you have to write

printf("odd %d \n", oddCount);
printf("even %d \n", evenCount);
printf("positive %d \n", posCount);
printf("negative %d \n", negCount);

And it is better to substitute the while loop

while(x!='y') {
 //... 
 printf("if you want to end the loop write 'y'\n");
 scanf("%c", &x);
}

for do-while loop

do {
   //...
   x = '\0';
 printf("if you want to end the loop write 'y'\n");
 scanf(" %c", &x);
} while ( x != 'y' && x != 'Y' );

Upvotes: 1

Related Questions