Advertisement
ntodorova

Arrays - 10_SequenceOfGivenSum

Jan 18th, 2013
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.57 KB | None | 0 0
  1. using System;
  2.  
  3. /*
  4.  * 10. Write a program that finds in given array of integers a sequence of given sum S (if present).
  5.  * Example:  {4, 3, 1, 4, 2, 5, 8}, S=11 -> {4, 2, 5}
  6.  */
  7. class SequenceOfGivenSum
  8. {
  9.     static void Main()
  10.     {
  11.         int n;
  12.         int S;
  13.         int currentSum = 0;
  14.         int firstIndex = 0;
  15.         int lastIndex = 0;
  16.  
  17.         Console.Write("Number of array elements: ");
  18.         string strN = Console.ReadLine();
  19.  
  20.         Console.Write("S = ");
  21.         string strS = Console.ReadLine();
  22.  
  23.         if (!int.TryParse(strN, out n) || !int.TryParse(strS, out S))
  24.         {
  25.             Console.WriteLine("Invalid numbers!");
  26.         }
  27.         else
  28.         {
  29.             int[] array = new int[n];
  30.  
  31.             // Get all array values
  32.             for (int i = 0; i < n; i++)
  33.             {
  34.                 Console.Write("Please enter array element: ");
  35.                 array[i] = int.Parse(Console.ReadLine());
  36.             }
  37.  
  38.             currentSum = array[0];
  39.  
  40.             for (int i = 0; i < array.Length; i++)
  41.             {
  42.                 for (int j = i + 1; j < array.Length; j++)
  43.                 {
  44.                     currentSum += array[j];
  45.  
  46.                     if (currentSum == S)
  47.                     {
  48.                         firstIndex = i + 1;
  49.                         lastIndex = j;
  50.                     }
  51.                 }
  52.  
  53.                 currentSum = 0;
  54.             }
  55.  
  56.             if (firstIndex > 0 && lastIndex > 0)
  57.             {
  58.                 Console.WriteLine("The sequence with sum {0} is: ", S);
  59.                 Console.Write("{ ");
  60.  
  61.                 for (int i = firstIndex; i <= lastIndex; i++)
  62.                 {
  63.                     if (i == lastIndex)
  64.                     {
  65.                         Console.Write("{0}", array[i]);
  66.                     }
  67.                     else
  68.                     {
  69.                         Console.Write("{0}, ", array[i]);
  70.                     }
  71.                 }
  72.  
  73.                 Console.WriteLine(" }");
  74.             }
  75.             else
  76.             {
  77.                 Console.WriteLine("There is no sequence with sum {0} in the array.", S);
  78.             }
  79.         }
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement