In this article, we are going to learn how to sort an array in ascending order C++. We will do the sorting of the array elements. We will take the array of elements from the user and then sort them in ascending order.
How to sort an array in ascending order C++
- We first accept the size of the array from the user.
- Next, we will ask the user to enter the elements as per the size given.
- We will use a temp variable to sort the array.
- We will start iterating over all elements of the array and then compare the elements.
- Once we found a smaller number we will put it in the array location.
How to sort an array in ascending order C++
#include <iostream>
using namespace std;
#define MAX_SIZE 250
int main()
{
int Array[MAX_SIZE];
int Size;
int Temp;
cout<<"Please enter size of the array (Max 250): ";
cin>>Size;
cout<<"Please enter the elements in array: ";
for(int i=0; i<Size; i++)
{
cin>>Array[i];
}
for(int i=0; i<Size; i++)
{
for(int j=i+1; j<Size; j++)
{
if(Array[j] < Array[i])
{
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
cout<<"The Array after sorting in ascending order is:"<<endl;
for(int i=0; i<Size; i++)
{
cout<<Array[i]<<endl;
}
return 0;
}
Output
error