Search in unsorted array

Hi
I have a question , I can not figure out some part of it, so I need a little help.
I was asked for to write function

UNSIGNED SEARCH(CONST UNSIGNED a[],UNSIGNED ELEMENTS,UNSIGNED TARGET)
this function returns position of the first elemen that has value target , or UNIT_MAX if no such element exists.You may not assume that the array is sorted.For instance if main program says unsigned array[]={2,3,5,7}
search(array,4,5)
function returns 2. On the other hand if main says
unsigned array[]={2,3,5,7}
search(array,4,6)
then the function returns UNIT_MAX

I wrote up to here

UNSIGNED SEARCH(CONST UNSIGNED a[],UNSIGNED ELEMENTS,UNSIGNED TARGET)
{
int i;
for(i=0; i<elements; i++)
{
if(a[i]==target)
return i;
break;
}
}
I do not know how to write code for printing UNIT_MAX.
Any help is highly appriciated.
Firstly, you know c++ is case sensitive, right?
Now, your code
1
2
3
4
5
6
7
8
9
unsigned SEARCH(const unsigned a[],unsigned elements,unsigned target)
{
   int i;
   for(i=0; i<elements; i++){
      if(a[i]==target)
         return i;
      break;
   }
}
Line 7 is one problem. It is not a part of the if. You're missing {}. Though you don't need it at all. return breaks from all loops and leaves the function without executing any code after it. Thus you can be sure that if the for loop has ended and you're still in the function, no element was found. Add a return UNIT_MAX; after the loop.
Thanks for your reply
But how to call the function , because it is unsigned , when I write return UNIT_MAX. in the output it shows me a big number instead of UNIT_MAX.
I called it like
cout<<search(a,4,3);
?
closed account (zb0S216C)
By reading your code, UINT_MAX was never initialized. Until UINT_MAX is initialized, it will hold "garbage".
Last edited on
UINT_MAX by itself is a number or string ?
UINT_MAX is a macro defined in climits. It translates to 4294967295
Edit: system dependent http://www.cplusplus.com/reference/clibrary/climits/ minimum value 65535
Last edited on
Topic archived. No new replies allowed.