- 2070 Asar · 6 marks
Count even and odd until -1
Short answer
Read numbers until -1; for each non-negative entry, increment even counter if n%2==0 else odd counter. -1 stops and is not counted. Print totals.
Write a program to read the number until -1 is encountered. Also count the number of even number and odd numbers entered by the user.
Numbers are read until -1 is entered (the -1 is not counted). A number is even if n % 2 == 0, otherwise it is odd.
#include <stdio.h>
int main(void)
{
int n, even = 0, odd = 0;
printf("Enter numbers (-1 to stop):\n");
scanf("%d", &n);
while (n != -1)
{
if (n % 2 == 0)
even++;
else
odd++;
scanf("%d", &n);
}
printf("Even numbers = %d\nOdd numbers = %d\n", even, odd);
return 0;
}
Output for the input 4, 7, 10, 3, 8, 9, -1:
Enter numbers (-1 to stop):
Even numbers = 3
Odd numbers = 3
Even numbers are 4, 10, 8 (3 of them); odd numbers are 7, 3, 9 (3 of them).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Odd and even numbers to separate files · Computer Programming, chapter 10 · asked 2×
- Count prime and composite until -1 · Computer Programming, chapter 5
- Sum and average until 0 is entered · Computer Programming, chapter 5
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Sum of digits until single digit · Computer Programming, chapter 5 · asked 2×
- Algorithm for numbers divisible by 9 not 6 · Computer Programming, chapter 2
- Handshaking theorem; even number of odd vertices · Discrete Structure, chapter 4 · asked 3×
- DFA: even a and odd b · Theory of Computation, chapter 2
- RE: even a's followed by odd b's · Theory of Computation, chapter 2
- 8086 ALP: sum of 100 even numbers · Microprocessor, chapter 3