for( i=0; i< 10; i++){
for( j=i; j < 10; j++) {
if( a[i] > a[j]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
for( i=0; i< 10; i++){
for( j=i; j < 10; j++) {
if( a[i] > a[j]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
Let me show you an equivalence:
Code:int i; for (i = 0; i < 10; i++){ // Things happening in here }See?Code:int i; i = 0; while (i < 10) { // Things happening in here i++; }
Devoted my life to programming...
The code appears to be a sort routine, if the code worked correctly! It doesn't!
First of all, you need to properly format your code. Secondly, you need to properly close your braces.
Your first error is:Code:for( i=0; i< 10; i++){ for( j=i; j < 10; j++) { if( a[i] > a[j]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } }i & j are pointing to the same subscript. The statement will always be false!Code:if( a[i] > a[j]) {
Assuming that a is an array of 10 elements, how should this line be written?Code:for( j=i; j < 10; j++) {
That is true on each first iteration of the inner loop, but it will not be true on subsequent iterations. So, the code does an unnecessary iteration, but it should not change the net effect, hence it is inefficient rather than an error per se.Originally Posted by rstanley
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I knew I needed a second cup of coffee today! ;^)
Heheh. That said, it looks like there is an error on that line, but it has to do with whether a[i], a[j] or a[j+1] should be involved in the comparison. Furthermore, it looks like there is another error on the line that you suggested fixing, but it has to do with a[j+1] in the loop body: if j == 9, and 9 is the last index, then a[j+1] accesses the array out of bounds.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I was leaving it ti the OP to figure out the remainder of the problems. I didn't want to do all the work for the OP.