0
This program to get small element in array, why i get zero? What is problem?
#include<iostream> using namespace std; int small(int hawa[] ,int size){ int smallest=0; for (int i=1 ;i<size;i++) { if (hawa[smallest] >hawa[i]){ smallest=i;} return smallest; } } int main() { int pa[10]={2,4,6,7,8,9,8,6,99}; cout<< small(pa,10); }
2 Respuestas
+ 2
There are multiple errors in your program, first of all, check you array size, the size is 10 but you only initialize 9 elements, and then you pass 10 as an array size into the function, this can cause bug. Second is the function, the for-loop for an array has to start from 0, so it has to become like this
for (int i = 0; i < size; i++)
After that, the smallest variable has to be maxed out since you are finding the smallest value, so change it to
int smallest = INT_MAX
Another error is the if statement, change it to
if (smallest > hawa[i]) {
smallest = hawa[i];
}
Also, put the return statement after the loop, not inside it
0
***
Now that you mentioned it, it actually depends on what he want, if he actually want the index of the smallest array, then yes, you're right, but his description say to get the smallest element.
Even though it's the former that he want, there is actually a simpler solution (I just thought about that), it's to put the return after the loop and change it to
return hawa[smallest]