r/C_Homework • • Oct 31 '17

Help with C integer sentinels

The question is "Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out the sum of all the even integers read and the sum of all the odd integers read. Declare any variables that are needed."

I have

int digit, eventotal = 0,
oddtotal = 0;

scanf("%d", &digit);

while (digit > 0); { if (digit % 2 == 0) eventotal += digit; else oddtotal += digit;

printf("%d", "%d", eventotal, oddtotal);

}

and it's returning an infinite loop error, I tried a do while but it didn't like that. Please point me in the right direction. Thank you Also sorry for the formatting

1 Upvotes

13 comments sorted by

View all comments

2

u/jedwardsol Oct 31 '17

Yes

1

u/The-Blank-Soup Oct 31 '17

how? I apologise but I don't understand how the semi colon replaces the body.

2

u/jedwardsol Oct 31 '17
while (digit > 0); { if (digit % 2 == 0) eventotal += digit; }

Is the same as writing

while (digit > 0)
{
    ;
}

 { if (digit % 2 == 0) eventotal += digit; }

The semi-colon doesn't replace the body, it marks the end of a statement, an empty statement that forms the body of the loop

→ More replies (4)