Deciding which loop to use for which use-case is a important task. My general rule-of-thumb (and the one I got taught in school) is as follows
For-Loops: When you know in advance how many times you want to iterate.
While-Loops: When the number of iterations is not known in advance and depends on a condition being true. It checks the condition before each iteration.
Do-While-Loops: Similar to the while loop, but it guarantees that the loop body is executed at least once because the condition is checked after the loop's execution.
For your case since you have a defined and small range of numbers I would suggest the foor-loop I rarely ever use the do-while-loops but they do for sure have an advantage since you save at least one condition-check. the classic while loop i usually only use for user input to exit the cycle. (In Controllers as example i use a while(true) to simulate a repetetive task which needs Userconfirmation
Now that we have decided what loop to use lets take a glance on whats next:
int num, evenSum = 0, evenCount = 0, oddProduct = 1;
float average;
those are variables I created. Just for clarification for the following code
for (int i = 0; i < 10; i++) {
printf("Enter integer %d: ", i + 1);
scanf("%d", &num);
if (num % 2 == 0) { // Check if the number is even
evenSum += num; // Add to sum of even numbers
evenCount++; // Increment the count of even numbers
} else { // The number is odd
oddProduct *= num; // Multiply odd numbers
}
What I did here is hopefully explained enough by my comments
Keep in mind I did calculate the even numbers. Why? To prepare for the following code
// Calculate the average of even numbers
if (evenCount > 0) {
average = (float)evenSum / evenCount;
printf("Average of even numbers: %.2f\n", average);
} else {
printf("No even numbers were entered.\n");
}
// Print the product of odd numbers
if (oddProduct != 1) {
printf("Product of odd numbers: %d\n", oddProduct);
} else {
printf("No odd numbers were entered.\n");
}
return 0;
What I did here is using the float variable declared earlier and make an simple average calculation.
This should do the trick and solve your task and also clear when to use which Loops