Concepts:
While cycle, if instruction, module operator (%)
Text:
Implement a C program that:
Solution:
/* Insert 5 numbers using the keyboard and count how many even and odd numbers have been inserted */ #include <stdio.h> #define NUMBERS 5 int main(){ int n; int x; int n_even, n_odd; n=0; n_even=0; n_odd=0; while(n<NUMBERS){ printf("Insert number %d: ", n); scanf("%d", &x); if (x%2 == 0) { printf("Even!\n"); n_even = n_even+1; }else{ printf("Odd!\n"); n_odd = n_odd+1; } n = n+1; } printf("EVEN: %d - ODD: %d\n", n_even, n_odd); return 0; }
Comments:
The program executes 5 times the block of code inside the while cycle that:
scanf("%d", &x);
if (x%2 == 0) { /* Code executed if x is even */ }else{ /* Code executed if x is odd */ }
printf("EVEN: %d - ODD: %d\n", n_even, n_odd);