As others have said in the comments, there is no need for the second loop. Since you only care about the number of coffees drunk by minors, you only need to compare the number of coffees at these indexes to your minCoffee
variable. Doing this, your loop might look something like this:
for(i=0; i<nbElements; i++) {
if (tabAges[i]<18) {
if (tabCoffee[i]<minCoffee) {
minCoffee = tabCoffee[i];
}
}
}
(As an aside, while single line control statements do work without curly braces, they can sometimes cause unintended behaviour if you later come back and add a line. It's safer (and arguably more readable) to always include them.
If you prefer, the above if
statements can be condensed into a single one: if (tabAges[i] < 18 && tabCoffee[i] < minCoffee
.
Now we still need to figure out how to initialise the minCoffee
variable, since we have no idea what could be in there.
One option is to import limits.h
, and set it to INT_MAX
(or UINT_MAX
if you decide to use an unsigned integer).
#include <limits.h>
// declare variables etc...
minCoffee = INT_MAX;
If for some reason you can't/don't want to do this, an alternative is to initialise minCoffee
to something nonsensical, then have a special case in your loop to set it to the first value for a minor it detects.
minCoffee = -1 //This doesn't make sense, you can't drink less than 0 coffees!
for(i=0; i<nbElements; i++) {
if (tabAges[i]<18) {
if (minCoffee == -1) {
minCoffee = tabCoffee[i]
} else if (tabCoffee[i]<minCoffee) {
minCoffee = tabCoffee[i];
}
}
}
In practice, this achieves exactly the same result as the previous solution, however it requires an additional test and is not as intuitive to read over, so I would not recommend this method.
Now if you were to put all of this together, you might end up with a solution that looks something like this:
#include <stdio.h>
#include <limits.h>
int main() {
int tabAges[] = {25, 22, 14, 19, 36, 17};
int tabCoffee[] = {0, 4, 1, 3, 5, 2};
int nbElements = sizeof(tabAges) / sizeof(int);
int i, j, minCoffee;
minCoffee = INT_MAX;
for(i=0; i<nbElements; i++){
if (tabAges[i]<18)
if (tabCoffee[i]<minCoffee)
minCoffee = tabCoffee[i];
}
printf("the minimum of coffee drunk by minor is %d", minCoffee);
return 0;
}