Sort Elements in an array in C++ Programming


The program sorts an array of integers in ascending order using the bubble sort algorithm.

  • The program starts by declaring an integer arraya of size 100 and variables n (for the size of the array), i and j (for loop iteration), and temp (to store temporary values during sorting).
  • The user is prompted to enter the size of the array, which is stored in the variable n. The program then uses a for loop to prompt the user to enter values for each element in the array, which are stored in the array a.
  • The program then uses nested for loops to iterate over each element in the array a and compare it with every other element in the array. If an element is greater than the element it is being compared to, the two elements are swapped. This process continues until the entire array is sorted in ascending order.
  • Finally, the program prints the sorted array using another for loop.

Overall, the program allows the user to enter any number of elements in an array and then sorts the array in ascending order using the bubble sort algorithm. The sorted array is then printed to the console.

Source Code

#include<iostream>
using namespace std;
//program to sort an array in ascending order
int main()
{
    int a[100],n,i,j,temp;
    cout<<"\nEnter The Limit : ";
    cin>>n;
 
    cout<<"\nEnter "<<n<<" Value :"<<endl;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
 
    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
 
    cout<<"\nSorted Array : "<<endl;
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<endl;
    }
    return 0;
}
 

Output

Enter The Limit : 10

Enter 10 Value :
2
34
54
2
12
56
7
21
6
1

Sorted Array :
1
2
2
6
7
12
21
34
54
56
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples