Write C# program to sort an array in ascending order


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. using System;
  2. class Program
  3. {
  4. static void Main()
  5. {
  6. int[] arr = new int[100];;
  7. int size, i, j, temp;
  8.  
  9. //Reads size of the array
  10. Console.WriteLine("Enter size of the array: ");
  11. size = Convert.ToInt32(Console.ReadLine());
  12. //Reads elements in array
  13. Console.WriteLine("Enter elements in the array: ");
  14. for(i=0; i<size; i++)
  15. {
  16. arr[i] = Convert.ToInt32(Console.ReadLine());
  17. }
  18.  
  19. //Sorting an array in ascending order
  20.  
  21. for (i = 0; i < size; i++)
  22. {
  23. for (j = i + 1; j < size; j++)
  24. {
  25. //If there is a smaller element found on right of the array then swap it.
  26. if (arr[j] < arr[i])
  27. {
  28. temp = arr[i];
  29. arr[i] = arr[j];
  30. arr[j] = temp;
  31. }
  32. }
  33. }
  34. //Printing the sorted array in ascending order
  35.  
  36. Console.WriteLine("Elements of array in sorted ascending order:");
  37. for (i = 0; i < size; i++)
  38. {
  39. Console.WriteLine(arr[i]);
  40. }
  41. Console.ReadLine();
  42. }
  43.  
  44. }

Result

C# language techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.