We are going to share a C++ program to sort an array in ascending order. If you are a C++ beginner and want to learn C++ programming, then keep your close attention in this tutorial as I am going to share a C++ program to sort an array in ascending order with the output.
Copy below C++ program and execute it with Turbo C compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <iostream> using namespace std; #define MAX 100 int main() { int arr[MAX]; int n,i,j; int temp; cout<<"Enter total number of elements to read: "; cin>>n; if(n<0 || n>MAX) { cout<<"Input valid range!!!"<<endl; return -1; } for(i=0;i<n;i++) { cout<<"Enter element ["<<i+1<<"] "; cin>>arr[i]; } cout<<"Unsorted Array elements:"<<endl; for(i=0;i<n;i++) cout<<arr[i]<<"\t"; cout<<endl; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(arr[i]>arr[j]) { temp =arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } cout<<"Sorted (Ascending Order) Array elements:"<<endl; for(i=0;i<n;i++) cout<<arr[i]<<"\t"; cout<<endl; return 0; } |
Enter total number of elements to read: 5
Enter element [1] 5
Enter element [2] 10
Enter element [3] 15
2Enter element [4] 20
Enter element [5] 25
Unsorted Array elements:
5 10 15 20 25
Sorted (Ascending Order) Array elements:
5 10 15 20 25
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.