whats wrong with this code it compiles well but gives wrong results

code is to arrange the 5 numbers in ascending order

for (a=0;a<=4;a++)
{
for (b=a+1;b<=4;b++)
{
if (num[a]>num[b])
{
temp=num[a];
num[a]=num[b];
num[b]=temp;
}
}
}

can anyone tell whats wrong??

Hi,

First use [ code ] code tags [ /code ]. It' makes it alot easier to read code.

Second, show your complet code, where is num declared and how, is it declared as an array?

Third, where is temp declared, it should be declared inside the loop and be a local variable inside the loop.

If you have 5 numbers the main cause shold be a out of bounds error. Use the below.

for (a=0;a<4;a++)
{
for (b=a+1;b<4;b++)
{

Edit:
No. Sorry. My mistake. Your code is correct. I got carried away by the <= sign. As Salem says, the error should be elsewhere.

Well some context for the code would help.

Like how did you declare the num array?
How did you get data into it?
How did you print it out?

It looks about right "as is", so I can only assume the mistake is somewhere else.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.