Hey, it's been quite awhile since I last posted, but I'm stuck. What I'm supposed to do is look at this code and tell what would appear on the output screen. I ran the program and found that it should display: 2 3 6 1 5 0. However, I just don't see how those numbers are obtained. Here's the code:

#include<iostream>
using namespace std;
int main()
{
int a[ 6 ]={ 2, 6, 3, 7, 1, 5 }, t = 0;
for( int i = 0; i < 6; i++ )
{
      if ( a [ i + 1 ] < a[ i ] )
     {
          t = a[ i ];
          a[ i ] = a[ i + 1 ];
          a[ i + 1 ] = t;
      }
}
for( int k = 0; k < 6; k++ )
 
       cout << a[ k ] << " ";
 
return 0;
}

Thanks ahead of time for the help.

The code contains an error -- it accesses an element of the array that does not exist, which probably explains why one of the results is 0 instead of 7.

Anyway, the reason for the strange arrangement of the final results is that the function only sorts part of the array. A complete bubble sort algorithm requires two loops, not one.

if you don't do for(i = 0; i < SIZE - 1(5 in this example); i++) you try to reach the array[SIZE(6 in this example)] which doesn't have any user defined value...

Thanks for the replies. So there is a problem with the code? That's what my professor provided in the review sheet.

sometimes professors make mistakes too.

lol, even though some professors don't want to admit that they do. Well, it's nice to know that it wasn't me, I've been looking at that for a few hours. Thanks again for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.