C program to sort an array in an ascending order


Problem

Sort the given array in descending or ascending order based on the code that has been written.

Solution

An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its "index number".

Declaring array

The syntax for declaring an array is as follows −

datatype array_name [size];

For example,

float marks [50]

It declares ‘marks’ to be an array containing 50 float elements.

int number[10]

It declares the ‘number’ as an array to contain a maximum of 10 integer constants.

Each element is identified by using an "array index".

Accessing array elements is easy by using the array index.

The logic we use to sort the array elements in ascending order is as follows −

for (i = 0; i < n; ++i){
   for (j = i + 1; j < n; ++j){
      if (num[i] > num[j]){
         a = num[i];
         num[i] = num[j];
         num[j] = a;
      }
   }
}

Program

Following is the C program to sort an array in an ascending order −

 Live Demo

#include <stdio.h>
void main (){
   int num[20];
   int i, j, a, n;
   printf("enter number of elements in an array
"
);    scanf("%d", &n);    printf("Enter the elements
"
);    for (i = 0; i < n; ++i)       scanf("%d", &num[i]);    for (i = 0; i < n; ++i){       for (j = i + 1; j < n; ++j){          if (num[i] > num[j]){             a = num[i];             num[i] = num[j];             num[j] = a;          }       }    }    printf("The numbers in ascending order is:
"
);    for (i = 0; i < n; ++i){       printf("%d
"
, num[i]);    } }

Output

When the above program is executed, it produces the following result −

enter number of elements in an array
5
Enter the elements
12
23
89
11
22
The numbers in ascending order is:
11
12
22
23
89

Updated on: 02-Sep-2023

78K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements