How to Sort Array in Ascending Order in C++?

Sort Array in Ascending Order in C++

This program is to sort array in ascending order in C++ programming language. Program is as under.

#inlcude<iostream.h>
#inlcude<conio.h>
void main()
{ 
int a[10]={23,43,12,67,3,8,19,234,157,281};
int i,j,temp;
clrscr();
for(i=0;i<10;i++)
    {
      for(j=i+1;j<10;j++)
       {
        if(a[i]<a[j])
         {
         temp=a[i];
         a[i]=a[j];
         a[j]=temp;
         }
      }
   }
for(i=0;i<10;i++)
cout<<a[i]<<”/t”;
getch();
}

Explanation

#include

These are header files and are also called pre-processor directives. These are libraries which contains definitions of the built in functions. Without iostream cout and cin will not work and without conio clrscr() and getch() will not work. Compiler does not process these directives.

Void main()

This is the core function in C and C++. This is where execution of C++ program starts from. void means that the function will not have any return value. If we make it int then it must return an integer value.

int a[10]

This is an array of fixed size i.e 10 elements. We can also define a variable length array. The user will then have to enter size of the array. And the loop variable will then increment up to that size.

clrscr()

This function in C++ is for clearing the screen. The header file conio.h defines it.

cout

This is output function is C++. This is used to display something on console. Here we have used it for displaying array elements after making them in ascending order.

Leave a comment