Saturday, May 22, 2010

Write a C program that stores 5 input numbers into an array and sorts these?

What Vera said. :-)

Write a C program that stores 5 input numbers into an array and sorts these?
C++ :P ('cause I'm more comfortable with itas methods of input and output).





I'm assuming that you want the array ordered in ascending order:





.........


void main()


{


double array[5];





for(int i=0; i%26lt;5; i++)


{


cout%26lt;%26lt;"Please provide a number: ";


cin%26gt;%26gt;array[i];


}





for(int i=0; i%26lt;4; i++)


{


for(j=i+1; j%26lt;5; j++)


{


if(array[i]%26gt;array[j])


{


int aux = array[i];


array[i] = array[j];


array[j] = aux;


}


}


}





count%26lt;%26lt;"The ordered array is: "


for(int i=0; i%26lt;5; i++)


{


cout%26lt;%26lt;array[i]%26lt;%26lt;" ";


}





return;


}





The idea is as follows:


In a for loop I read 5 numbers. Then for the first 4 positions, I make sure that every element on the following positions is greater than or equal to them.





eg.


for a given position i, I make sure that array[i+1], array[i+2] .. array[4] are all greater than or equal to array[i]. If I find a value that does not conform to this, I exchange it with the value of array[i].





P.S. you will need to include the appropriate libraries.





PPS. cout and cin are C++ specific functions, you will need need to switch them with printf respectively gets.


No comments:

Post a Comment