Reputation: 2290
Im trying to pick from a list of 5 numbers, the biggest and the smallest numbers. With the biggest I have no problems, either with the smallest for some cases. But, for the smallest number I would like to adding a condition that if its zero ('0'), I wouldn't pick it, thats mean from 5 numbers I would like to pick the smallest one, that is not 0. for example: 1000 2000 3000 0 0 I would like to pick the 1000.
Also, I can't use any methods, or based functions, Just If statements.
thats my code:
if((manufactorsPrice1<manufactorsPrice2)&&(manufactorsPrice1<manufactorsPrice3)&&(manufactorsPrice1<manufactorsPrice4)&&(manufactorsPrice1<manufactorsPrice5)){
if(manufactorsPrice1>0){
smallestPrice=manufactorsPrice1;
}
}else if((manufactorsPrice2<manufactorsPrice3)&&(manufactorsPrice2<manufactorsPrice4)&&(manufactorsPrice2<manufactorsPrice5)){
if(manufactorsPrice2>0){
smallestPrice=manufactorsPrice2;
}
}else if((manufactorsPrice3<manufactorsPrice4)&&(manufactorsPrice3<manufactorsPrice5)){
if(manufactorsPrice3>0){
smallestPrice=manufactorsPrice3;
}
}else if(manufactorsPrice4 < manufactorsPrice5){
if(manufactorsPrice4>0){
smallestPrice=manufactorsPrice4;
}
}else{
if(manufactorsPrice5>0){
smallestPrice=manufactorsPrice5;
}}
Thats work fine if I could pick the 0 as the smallest, But I cannot. Please help me, How can I pick the next smallest number that is not a Zero from the list.? thanks.
Upvotes: 1
Views: 96
Reputation: 6251
Here is a solution which only uses an extra local variable to reduce nesting. It will find the minimum non-zero value (if it exists) or zero in the case they are all 0. It also uses fewer comparisons.
...
int min1, min2;
if (a2 == 0 || (a1 < a2 && a1 != 0))
min1 = a1;
else
min1 = a2;
if (a4 == 0 || (a3 < a4 && a3 != 0))
min2 = a3;
else
min2 = a4;
if (min1 == 0 || (min2 < min1 && min2 != 0))
min1 = min2;
if (min1 == 0 || (a5 < min1 && a5 != 0))
min1 = a5;
return min1;
Upvotes: 2
Reputation: 5576
Solution appropriate for your teacher who only allows the use of conditionals...
s=
(s=
(s=
(s=
x2!=0&&x2
<x1?x2:x1)>x3
&&x3!=0?x3:s)>x4
&&x4!=0?x4:s)>x5
&&x5!=0?x5:s;
Upvotes: 0