954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

what is the error

please where is the error in this code doesn't run

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
  int ages[1000];
  int size=1000;
  int i,a,b;
  for( i=0;i<size;i++)
  {
    ages[i]=rand();
    for( a=1;a<size;a++)
    {
      for( b=size-1;b>=a;b--)
      {
        if(ages[b-1]<ages[b])
        {
          i=ages[b-1];
          ages[b-1]=ages[i];
          ages[b]=i;
        }
      }
    }
  }
  cout<<ages[i];

  return 0;
}

Code indented and tags added. -Narue

some one
Junior Poster
129 posts since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

>ages[b-1]=ages[i];
That's your error. i isn't an index, it's a content value, and the value could very well exceed 999, which is the largest possible index for ages. Change that line to:

ages[b-1]=ages[b];

You probably also want to restructure your code so that it has specific sections for initializing the array, sorting the array, and printing the sorted array:

#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
  int ages[1000];
  int size=1000;
  int i,a,b;
  for(i=0;i<size;i++)
  {
    ages[i]=rand();
  }
  for( a=1;a<size;a++)
  {
    for( b=size-1;b>=a;b--)
    {
      if(ages[b-1]<ages[b])
      {
        i=ages[b-1];
        ages[b-1]=ages[b];
        ages[b]=i;
      }
    }
  }
  for( i=0;i<size;i++)
  {
    cout<<ages[i]<<' ';
  }

  return 0;
}

I'm also not sure if you really wanted this functionality or not, but as it is the sort is descending, not ascending, which is the most common preference.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

thanks a lot Naure

some one
Junior Poster
129 posts since Apr 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You