944,017 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 1087
  • C++ RSS
Apr 8th, 2005
0

what is the error

Expand Post »
please where is the error in this code doesn't run
C++ Syntax (Toggle Plain Text)
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6. int ages[1000];
  7. int size=1000;
  8. int i,a,b;
  9. for( i=0;i<size;i++)
  10. {
  11. ages[i]=rand();
  12. for( a=1;a<size;a++)
  13. {
  14. for( b=size-1;b>=a;b--)
  15. {
  16. if(ages[b-1]<ages[b])
  17. {
  18. i=ages[b-1];
  19. ages[b-1]=ages[i];
  20. ages[b]=i;
  21. }
  22. }
  23. }
  24. }
  25. cout<<ages[i];
  26.  
  27. return 0;
  28. }
Code indented and tags added. -Narue
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster
some one is offline Offline
129 posts
since Apr 2005
Apr 8th, 2005
0

Re: what is the error

>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:
C++ Syntax (Toggle Plain Text)
  1. 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:
C++ Syntax (Toggle Plain Text)
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6. int ages[1000];
  7. int size=1000;
  8. int i,a,b;
  9. for(i=0;i<size;i++)
  10. {
  11. ages[i]=rand();
  12. }
  13. for( a=1;a<size;a++)
  14. {
  15. for( b=size-1;b>=a;b--)
  16. {
  17. if(ages[b-1]<ages[b])
  18. {
  19. i=ages[b-1];
  20. ages[b-1]=ages[b];
  21. ages[b]=i;
  22. }
  23. }
  24. }
  25. for( i=0;i<size;i++)
  26. {
  27. cout<<ages[i]<<' ';
  28. }
  29.  
  30. return 0;
  31. }
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.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Apr 8th, 2005
0

Re: what is the error

thanks a lot Naure
Reputation Points: 10
Solved Threads: 0
Junior Poster
some one is offline Offline
129 posts
since Apr 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: drawing - stickman with array
Next Thread in C++ Forum Timeline: Simple Program will not exit gracefully





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC