Advertisement
TanyaPetkova

C# Part II Arrays Exercise 6

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