Step-by-step explanation:
Not sure what level that's at, or how you're expected to manage memory, so I'll write it in a "safe" manner and you can adjust accordingly.
Notably, I'm allocating memory dynamically at the moment. If you're not used to that, you might want to change that. Also, the c compiler I'm using (gcc) doesn't handle the bool type, so I used int. You may need to change that.
Also, if you change it to use fixed arrays instead of malloc, realloc and free, then you don't need to include stdlib.h.
The code below builds successfully with gcc, so if you have any issues, it will be in translating to another compiler/language.
Answer:
#include <stdio.h>
#include <stdlib.h>
int isArrayOdd(int *inputVals, int numVals){
int n, rval = 1;
for(n = 0; n < numVals && rval; n++){
rval &= inputVals[n] & 1;
}
return rval;
}
int isArrayEven(int *inputVals, int numVals){
int n, rval = 1;
for(n = 0; n < numVals && rval; n++){
rval &= 1 - (inputVals[n] & 1);
}
return rval;
}
int main(void) {
/*
I'm writing this to allow any quantity of numbers,
using malloc to allocate the memory for them dynamically.
You may want to modify this to match the level that your
class is in.
*/
int *numbers, quantity = 0, input;
numbers = (int *) malloc(sizeof(int));
printf("Please enter a number, or hit \"q\" to quit: ");
while(scanf("%i", &input) == 1){
quantity++;
numbers = (int *) realloc(numbers, quantity * sizeof(int));
numbers[quantity - 1] = input;
printf("\\you entered %i\\", numbers[quantity - 1]);
}
if(isArrayOdd(numbers, quantity)){
printf("all odd\\");
}else if(isArrayEven(numbers, quantity)){
printf("all even\\");
}else{
printf("not even or odd\\");
}
free(numbers);
return 0;
}
=================================================================
BONUS! BONUS! BONUS! BONUS! BONUS! BONUS! BONUS!
=================================================================
The inefficiency of the logic dictated in the assignment drove me nuts, so here's one that's ridiculously simpler and does exactly the same job:
#include <stdio.h>
int main(void) {
int input, oddEven = -1;
printf("Please enter a number, or hit \"q\" to quit: ");
while(scanf("%i", &input) == 1){
printf("\\you entered %i\\", input);
if(oddEven == -1){
oddEven = input & 1;
}else if(oddEven != (input & 1)){
oddEven = 2;
}
}
switch(oddEven){
case 0:
printf("The numbers are all even\\");
break;
case 1:
printf("The numbers are all odd\\");
break;
case 2:
printf("The numbers are both odd and even\\");
break;
default:
// should never happen
printf("Something odd happened.");
}
return 0;
}