Reputation: 79
We were tasked to make a program that accepts ONLY ten inputs from the user and then sort it into an Even or Odd Array.
This is the program I made:
#include<stdio.h>
int main(){
int even[10];
int odd[10];
int number;
int numOdd = 0;
int numEven = 0;
int sizeOdd = 0;
int sizeEven = 0;
int count;
printf("Input numbers:\n");
for(count = 0; count < 10; count++){
scanf("%d", &number);
if (number %2 == 0){
while (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
else {
while (numOdd < 10){
odd[numOdd++] = number;
sizeOdd++;
}
}
}
printf("\n\nEven numbers(%d): ", sizeEven);
for(number = 0; number < numEven; number++){
printf("%d, ", even[number]);
}
printf("\n\nOdd numbers(%d): ", sizeOdd);
for(number = 0; number < numOdd; number++){
printf("%d, ", odd[number]);
}
system("pause");
return 0;
}
But my program just outputs the first numbers in the array and repeats it. Like, if I input 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, I get:
Even numbers (10): 2, 2, 2, 2, 2 Odd numbers (10): 1, 1, 1, 1, 1
Am I wrong with everything/my logic in the program? Am I on the right track and I just have to tweak it a bit? Hope for help!
Upvotes: 1
Views: 5850
Reputation: 1
The while keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if checks either. You only input 10 items, so at most you can add
Upvotes: 0
Reputation:
You've used while
twice, where you should have used if
. As a result, your even
array will be filled with the first even number entered, and your odd
array will be filled with the first odd number.
Change each while
to an if
and you may be OK, though I haven't checked for other errors. For example...
if (number %2 == 0){
if (numEven < 10){
even[numEven++] = number;
sizeEven++;
}
}
The while
keyword defines a complete loop of it's own - it's not a limit on some other kind of repetition such as (in this case) your addition of elements to each array.
BTW - you don't really need the if
checks either. You only input 10 items, so at most you can add 10 items to the even
array, or 10 items to the odd
array. As the arrays are both large enough to take 10 items, you don't need bounds checks in this code.
Upvotes: 0
Reputation: 754
This may help you: Why do you add that while loop inside the if and else condition:
if (number %2 == 0){
even[numEven++] = number;
Also even[numEven++]
itself increses the value of numEven variable no need to increment again in the next line.
Upvotes: 1