Programming Tutorials

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

Pinterest LinkedIn Tumblr
 
In the program below nested  for loop is used to sort a list of  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].

Read Also: C Program to Find the Sum and Average of Numbers Using Do-While Loop

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("%fn", a[i]);
printf("n");
getch();

}

Read Next: C Program to Read a Set of Real Numbers from Keyboard & Find the Maximum

Author

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 8 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Comments are closed.