Write a program in C# Sharp to find the second largest element in an array.


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. public class program
  3. {
  4. public static void Main()
  5. {
  6. int num, i, j = 0, lrg, lrg2nd;
  7. int[] arr1 = new int[50];
  8.  
  9. Console.Write("Input the size of array : ");
  10. num = Convert.ToInt32(Console.ReadLine());
  11.  
  12. //Stored values into the array
  13. Console.Write("Input {0} elements in the array :\n", num);
  14. for (i = 0; i < num; i++)
  15. {
  16. arr1[i] = Convert.ToInt32(Console.ReadLine());
  17. }
  18. // find location of the largest element in the array
  19. lrg = 0;
  20.  
  21. for (i = 0; i < num; i++)
  22. {
  23. if (lrg < arr1[i])
  24. {
  25. lrg = arr1[i];
  26. j = i;
  27. }
  28. }
  29. // ignore the largest element and find the 2nd largest element in the array
  30. lrg2nd = 0;
  31. for (i = 0; i < num; i++)
  32. {
  33. if (i == j)
  34. {
  35. i++; //ignoring the largest element
  36. i--;
  37. }
  38. else
  39. {
  40. if (lrg2nd < arr1[i])
  41. {
  42. lrg2nd = arr1[i];
  43. }
  44. }
  45. }
  46.  
  47. Console.Write("The Second largest element in the array is : {0} \n\n", lrg2nd);
  48. Console.ReadLine();
  49. }
  50. }

Result

C# language techstudy

     





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/.