Take (10) integers, store them in 1D array then do the following:

1. find the max and min number of them
2. find the average
3. sort these numbers in ascending squence

the first two questions are quite easy but my problem is in sorting those numbers...anyways, i came up with this code:

#include<iostream.h>
void main()
{
int a[10],max,min,sum=0;
int temp,j;
float average;
for(int i=0;i<10;i++)
cin>>a[i];
max=a[0];
min=[0];
for(i=0;i<10;i++)
{
if(a[i]>max)
max=a[i];
else
if(a[i]<min)
min=a[i];
sum+=a[i];
}
for(i=0,j=9;i<5,j>4;i++,j--)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
cout<<"ascending order:\n";
for(i=0;i<10;i++)
cout<<a[i]<<endl;
average=sum/10.0;
cout<<"max:"<<max<<endl;
cout<<"min:"<<min<<endl;
cout<<"average:"<<average;
}

after running the progam i entered 10 9 8 7 6 5 4 3 2 1, for instance ... the output was :

1 2 3 4 5 6 7 8 9 10 ..which is correct

but when i entered random numbers .. 34 52 78 100 77 53 37 99 100 143 .... the output was missed up and incorrect .....so can somebody help plz?

Look up bubble sort as it appears that that is what you are trying to do. Bubble sort usually is done with two loops, one nested inside the other. The outer loop controls which value you are looking at. The inner loop looks at all values in the array with higher index than the current value. The body of the loop using the logic similar to what you have posted.

BTW: iostream.h isn't the prefered header any longer, and void was never the return type for main().

Ah well .. i modified the code to be:

for(j=9;j>0;j--)
{
for(i=0;i<10;i++)
{
if(a>a[j])
{
temp=a;
a=a[j];
a[j]=temp;
}
}

but when i entered a series of numbers 5 6 7 3 9 10 56 41 93 141
the output was as follows 3 141 5 6 7 9 10 41 56 93
if u notice ..it's all correct exept the second number 141.. it has to be in the last place instead of the second ..so what's the matter with the code?!

Edited 3 Years Ago by happygeek: fixed formatting

Whooooooo ...finally, i figured it out :)

the outter loop counts from 0 ---> 9 as the inner loop does ..

for(j=0;j<10;j++)
{
for(i=0;i<10;i++)

whoooooooooo ..finally, i figured it out ..

i wasn't paying attention that the outter loop must count from 0 ---> 9 as the inner loop does... so nested for has to be :

for(j=0;j<10;j++)
{
for(i=0;i<10;i++)

This question has already been answered. Start a new discussion instead.