Write C++ program to sort an array in ascending order


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int arr[100];
  7. int size, i, j, temp;
  8.  
  9. // Reading the size of the array
  10. cout<<"Enter size of array: ";
  11. cin>>size;
  12.  
  13. //Reading elements of array
  14. cout<<"Enter elements in array: ";
  15. for(i=0; i<size; i++)
  16. {
  17. cin>>arr[i];
  18. }
  19. //Sorting an array in ascending order
  20. for(i=0; i<size; i++)
  21. {
  22. for(j=i+1; j<size; j++)
  23. {
  24. //If there is a smaller element found on right of the array then swap it.
  25. if(arr[j] < arr[i])
  26. {
  27. temp = arr[i];
  28. arr[i] = arr[j];
  29. arr[j] = temp;
  30. }
  31. }
  32. }
  33. //Printing the sorted array in ascending order
  34. cout<<"Elements of array in sorted ascending order:"<<endl;
  35. for(i=0; i<size; i++)
  36. {
  37. cout<<arr[i]<<endl;
  38. }
  39.  
  40. return 0;
  41. }
  42.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts