I don't know why but this keeps giving me return 1Code: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 1Code: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; } }
Do you really think your loop is going to execute more than once?
Unless a[] changes, it will always return the same value.
Yes it will loop until the array is over, but somehow it keeps returning 1 even though it is wrong.
No will also stop if a[c] < a[c+1]. If a[c] is less than a[c+1] it will return 1.Yes it will loop until the array is over
Jim
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?
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.
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.
Code:while(!asleep) { sheep++; }
maybe it would help to think of it this way:
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.Code:function do_something(arg1, arg2){ if (true): do_this() else: //if false do_that() }
Warning: Opinions subject to change without notice
The C Library Reference Guide
Understand the fundamentals
Then have some more fun
Turn your warning levels up and fix the warnings. Control currently reaches the end of a non-void funtion.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"