# Thread: Can any tell me what is wrong with this?

1. ## Can any tell me what is wrong with this?

Code:
```int sorted( int a[], int b)
{

for(int c = 0; c < b - 1; ++c)
{
if(a[c]<a[c+1])
return 1;
else
return 0;
}
}```
I don't know why but this keeps giving me return 1

2. Do you really think your loop is going to execute more than once?

Unless a[] changes, it will always return the same value.

3. Yes it will loop until the array is over, but somehow it keeps returning 1 even though it is wrong.

4. Yes it will loop until the array is over
No will also stop if a[c] < a[c+1]. If a[c] is less than a[c+1] it will return 1.

Jim

5. I can only assume that you don't understand what a return statement does.

The return statement terminates the execution of a function and returns control to the calling function.

So, do you still think your loop has any effect?

6. Your problem is you want to return when all elements are checked - I assume you want to see if the array is in sorted order.
Currently the function terminates after the first pair of elements is compared.

7. Let me talk you through what is happening.

On the first iteration of the loop, it tests whether a[0]<a[1]. If that's true then "return 1" happens, which halts the "sorted" function with a return value of 1. If a[0]<a[1] is false, then "return 0" happens, which halts the "sorted" function with a return value of zero.

Under no circumstances can you ever get to the second iteration of the loop, because you exit the "sorted" function at the first iteration, no matter what.

You want to return zero if the array is not sorted, which means returning zero at the first occurrence of a non-sorted pair of elements. So having a "return 0" inside the loop is fine. But you don't want to "return 1" until you've checked whether the entire array is sorted, which means you want the "return 1" outside the loop and after it, so that the loop can run to completion.

8. Originally Posted by AFCKING
Code:
```int sorted( int a[], int b)
{

for(int c = 0; c < b - 1; ++c)
{
if(a[c]<a[c+1])
return 1;
else
return 0;
}
}```
I don't know why but this keeps giving me return 1
maybe it would help to think of it this way:

Code:
```function do_something(arg1, arg2){
if (true):
do_this()

else: //if false
do_that()
}```
so whatever is in that first if statment seems to be true and that's why it keeps returning one. If you know that then you can trace the values for your agruments and see if maybe you can't pin point it.

9. Turn your warning levels up and fix the warnings. Control currently reaches the end of a non-void funtion.