Write a Program in C to Sort a List of Numbers in Ascending Order
468x60
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].a[j]=a[j+1];
a[j+1]=c;
Program in C to Sort a List of Numbers in Ascending Order
Steps:
- Declare an array with float to insert real numbers.
- Declare integers i, j, n, c and flag.
- Print the message to enter how many numbers want to insert and allow to enter the number.
- Use for() loop to allow to enter the numbers to sort in ascending order.
- Use nested for() loop to to sort the list.
- 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 Copy a String to Another.
- Write a Program in C to Calculate the Factorial Value of an Integer.
- Write a Program in C to Determine Whether a Number is Prime or Not.
- C Program to Read Set of Real Numbers from Keyboard & Find the Maximum
- How to Create a Digital Clock in JavaScript?
- How to Detect Visitor's Browser Using JavaScript?
- How to Create JavaScript Image Slideshow with Links
- Simple JavaScript Fade Effect Animation Using Jquery
- How to Create Simple JavaScript Fade Effect Animation?
- How to Create Pop Up Menus in Oracle Forms ?
- How to Create LOV in Oracle Forms Using Wizard ?
468x60
250x300
التالي
« التدوينة السابقة
« التدوينة السابقة
السابق
التدوينة التالية »
التدوينة التالية »