My task for this function is to find the index of the <= string in the array. If more than one string, then retrun the smallest index of such string. Retunr -1 if no elements in array.

I came out with a rough code. I hope what I did was in the right direction ..

``````int indexOfMin(const string a[], int n);
int indexOfMin(const string a[], int n)
{

if (n==0)
{
return -1;
}

else
{
int i = 0;
string min = a[i];

for (i=1; i<n; i++)
{
if (a[i] < min)
{
min = a[i];
}
}
return -1;
}

}``````
5
Contributors
8
Replies
9
Views
11 Years
Discussion Span
Last Post by aznballerlee

there's a function in C called strlen which returns the length of the string (in characters) you should probably use this method in your program. This website describes the function:

That would work out, but unfortunately, I cannot implement that in my task .. :sad:

How come your function never returns anything besides -1? You still need to implement that.

Everything else looks good.

I wrote a newer function .. still doesn't work when I use assert.

``````int indexOfMin(const string a[], int n);
int indexOfMin(const string a[], int n)
{

for (int i=0; i<n; i++)
{
if (a[i] >= a[i+1])
{
int min = i+1;
}
}

if (n>=0)
{
int min;
return min;
}
else
return -1;

}``````

Can anyone tell me what's wrong?

var 'min' is declared twice.

And what does 'n' do?

This is how to implement your function. Check it out, hope it helps

``````int indexOfMin(const string a[], int n) // i'm assuming n is the number of
{                                        // elements in the array??
int min=0; // minimum of all strings

if (n<0) // check if empty first
{
return (-1);
} else
{
for (int i=0; i<n; i++)
{
if (a[i] >= a[i+1])
{
min = (i+1);
}
}
return (min);
}
}``````

sorry, not (n<0) to check if empty, but (n==0)...

Thanks for the help! It worked out ..
:lol:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.