Advertisement
TanyaPetkova

C# Part II Arrays Exercise 6 with Array.Sort

Dec 21st, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. using System;
  2.  
  3. class MaxSum
  4. {
  5.     static void Main()
  6.     {
  7.         uint arrayLength = 0;
  8.  
  9.         Console.Write("Enter the arrays's length: ");
  10.  
  11.         while (!uint.TryParse(Console.ReadLine(), out arrayLength))
  12.         {
  13.             Console.Write("Invalid input. Enter a positive integer number: ");
  14.         }
  15.  
  16.         int elementsCount = 0;
  17.  
  18.         Console.Write("Enter the count of the elements to be summed: ");
  19.  
  20.         while (!int.TryParse(Console.ReadLine(), out elementsCount) || elementsCount > arrayLength)
  21.         {
  22.             Console.Write("Invalid input. Enter a positive integer number: ");
  23.         }
  24.  
  25.         int[] array = new int[arrayLength];
  26.  
  27.         for (int i = 0; i < arrayLength; i++)
  28.         {
  29.             Console.Write("Enter the {0} element of the array: ", i);
  30.  
  31.             while (!int.TryParse(Console.ReadLine(), out array[i]))
  32.             {
  33.                 Console.Write("Invalid input. Enter an integer number: ");
  34.             }
  35.         }
  36.  
  37.         Array.Sort(array);
  38.  
  39.         int[] maxElements = new int[elementsCount];
  40.         int maxSum = 0;
  41.  
  42.         for (int i = elementsCount - 1, len = array.Length - 1; i >= 0; i--, len--)
  43.         {
  44.             maxElements[i] = array[len];
  45.             maxSum += maxElements[i];
  46.         }
  47.  
  48.         Console.WriteLine("The maximal sum of {0} elements is the sum of the elements {1}, which is {2}.", elementsCount, string.Join(", ", maxElements), maxSum);
  49.  
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement