Issue
This code is supposed to find the smallest odd number in given array and store it in min
but when I try to print min
it always prints 0
.
int smallestodd(int x[5]){
int j;
int k[5];
int p = 0;
int r = 0;
for(int h =0; h<5;h++){
j = x[h] % 2;
if(j == 1){
int temp =x[h];
k[p] =temp;
p++;
}
}
int min = k[0];
while(k[r] !=0){
if(k[r] < min ){
min = k[r];
r++;
}
}
return min;
}
Solution
Assuming there is an odd number in the array — let’s say trying to find the minimum odd number in an array with just even numbers (or no numbers) is UB 🙂
index = 0;
while (arr[index] % 2 == 0) index++; // skip even numbers
min = arr[index++]; // first odd number
while (index < length) {
if (arr[index] % 2) {
if (arr[index] < min) min = arr[index];
}
index++;
}
Answered By – pmg
Answer Checked By – Cary Denson (BugsFixing Admin)