0
#include<iostream>
#include<conio.h>

using namespace std;

int main()
{
    int a, b, c[5], d;

    cout << "enter any five number\n";
    for(a=0; a<5; a++)
    {
        cin>>c[a];
    }
    for(a=0; a<5; a++)
    {
        for(b=++a; b<5; b++)
        {
            if(c[b] < c[a])
            {
                d = c[b];
                c[b] = c[a];
                c[a] = d;
            }
        }       
    }

    cout << "\nhere is the entered numbers in order\n"; 
    for(a=0; a<5; a++)
    {
        cout << c[a];
        cout << endl;
    }
    getch();
    return 3;
}

I am desk checking this program and I expect the program to sort numbers in ascending order but I am getting the wrong output help please.

4
  • no,no no @MarounMaroun i am sorry, if it's a bad habit this is my last time. Commented Feb 13, 2014 at 10:13
  • Could you not just use std::sort? Commented Feb 13, 2014 at 10:16
  • @Ralara: the original format of the title really suggested that this is a task assigned as an excercise Commented Feb 13, 2014 at 10:18
  • It would be helpful if you included a transcript of your desk-check, so that we could help you figure out where exactly your program's behavior differs from what you expected it to do. Commented Feb 13, 2014 at 10:19

4 Answers 4

1

in the inner loop it should be a + 1 not ++a

Sign up to request clarification or add additional context in comments.

Comments

1

for(a=0;a<5;a++) and for(b=++a;..) causes a to be incremented twice.

Did you mean for(b=a+1;b<5;b++) ?

1 Comment

yeah that's what i meant but i did not know that the second loop is the one causing that output, thank you so much @quetzalcoatl
0
for(a=0; a<5-1; a++){
  for(b=0; b<5-a-1; b++){
    if(c[b] < c[a]){
      d = c[b];
      c[b] = c[a];
      c[a] = d;
    }
  }
}

Comments

0
   for(a=0; a<5; a++)
    {
        for(b=++a; b<5; b++)
        {
            if(c[b] < c[a])
            {
                d = c[b];
                c[b] = c[a];
                c[a] = d;
            }
        }       
    }

this should be

for(a=0; a<4; a++)
{
    for(b=a+1; b<5; b++)
    {
        if(c[b] < c[a])
        {
            d = c[b];
            c[b] = c[a];
            c[a] = d;
        }
    }       
}

1 Comment

a<4 should be better to avoid a useless step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.