0

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??

4
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by Salem
0

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.

0

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.

0

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.

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.