0

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.

3
Contributors
5
Replies
6
Views
10 Years
Discussion Span
Last Post by Rickenbacker360
0

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.

0

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...

0

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

0

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.

This question has already been answered. 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.