
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
You can see a live demo here: 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
Also learn these topics to enhance C arrays knowledge:
- C - Arrays
- C - Properties of Array
- C - Multi-Dimensional Arrays
- C - Passing Arrays to Function
- C - Return Array from Function
- C - Variable Length Arrays