Write a Program in C to Sort a List of Numbers in Ascending Order


Program in C to Sort a List of Numbers in Ascending Order
In the program below nested  for loop is used to sort a list of  real numbers in ascending order. This program below asks to enter how many numbers want to sort and allow to enter the numbers to sort them in ascending order.
The nested for loop in the program swaps the numbers if first number is greater than the next number. i.e. using (a[j]>a[j+1]) and
       c=a[j];
       a[j]=a[j+1];
       a[j+1]=c;
Here the value of a[j] copied to c and value of a[j+1] copied to a[j] and then value of c is copied to a[j+1].



 Program in C to Sort a List of Numbers in Ascending Order



Steps:
  1. Declare an array with float to insert real numbers.
  2. Declare integers i, j, n, c and flag.
  3. Print the message to enter how many numbers want to insert and allow to enter the number.
  4.  Use for() loop to allow to enter the numbers to sort in ascending order.
  5. Use nested for() loop to to sort the list.
  6. Again use for() loop with printf() command to display the numbers on screen.



Code:



#include <stdio.h>
#include <conio.h>

void main()
{
float a[20];
int i,j,n,c,flag;

clrscr();

printf("how many numbers you want to enter:\n");
scanf("%d", &n);

printf("\Enter the numbers :\n");
for(i=0; i<n; i++)
scanf("%f", &a[i]);


for (i=0; i<n-1; i++)
{
for(j=0; j<n-1-i; j++)
{
if(a[j]>a[j+1])
{
c=a[j];
a[j]=a[j+1];
a[j+1]=c;
flag=0;
}
}
if(flag)
break;
else
flag=1;
}

printf("Stored elements:\n");
for(i=0; i<n; i++)
printf("%f\n", a[i]);
printf("\n");
getch();

}

 



Related Posts:


Write a Program in C to Sort a List of Numbers in Ascending Order Write a Program in C to Sort a List of Numbers in Ascending Order Reviewed by mohamed on 4:38 AM Rating: 5

No comments:

Powered by Blogger.