0

Umm my code doesn't work properly and I don't seem to find the solution for my problem. Code doesn't print the right numbers. Can anybody help? Thank you!

#include <iostream>
#include <conio.h>
using namespace std;



main(){

int number[] = {3, 5, 8, 1, 9, 2, 6, 4, 7, 10};



   int temp;

     for(int i2=0; i2<10; i2++)
   {

           for(int j=0; j<10; j++)
     {     
           if(number[j]>number[j+1])
       {
        temp=number[j];
        number[j]=number[j+1];
        number[j+1]=temp;        
       }
    }
   }

for(int x =0; x<10; x++){

cout<<number[x];
}





}
5
Contributors
4
Replies
41
Views
2 Years
Discussion Span
Last Post by richieking
0

You probably got an index out of range error, better tell that in the future, instead of code doesn't print...
Try for (int j = 0; j < 9; j++) on line 18 and also try to format your code a bit better.

Edited by ddanbe: addition

2

@ddanbe is right. Look at the last step of the cycle - j=9 is still less than 10 so it executes but you try to swap number[9] with number[10] which is out of range. Also I would do for(int j=0; j<9-i2; j++) - the biggest number always gets to the end so you need to check 1 less number in the next step. It's easiest to imagine with the biggest number initially being in the first place - the check is true in every step of the 1st iteration and it always gets swapped. It ends up at the last place and you don't need to check it in the 2nd iteration (and so on).

Votes + Comments
Good explanation.
0

use this

#include <iostream>

using namespace std;

int main()
{
  int foo []={4555,1,56,2,7,4,5,60,7,8,9,90,8,12};



   int temp;
   for(int i =0; i< sizeof(foo)/sizeof(int); i++ ){
      for(int c =0; c< sizeof(foo)/sizeof(int); c++ ){
          if(foo[c] > foo[i+1]){
              temp = foo[c];
              foo[c]=foo[i+1];
              foo[i+1]=temp;
          }


     }

   }
   std::cout <<"\n"<<"\n";

   for(int &d : foo){
      std::cout <<d <<std::endl;

  }
   return 0;
}

Edited by richieking

This topic has been dead for over six months. 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.