stkirov

10.SumOfSequenceElements

Jan 6th, 2013
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. //Write a program that finds in given array of integers a sequence of given sum S (if present).
  2. //Example:   {4, 3, 1, 4, 2, 5, 8}, S=11  {4, 2, 5}
  3. using System;
  4.  
  5. class SumOfSequenceElements
  6. {
  7.     static void Main()
  8.     {
  9.         int[] array = { 4, 3, 1, 4, 2, 5, 8 };
  10.         int s = 11;
  11.         int currentSum = 0;
  12.         int startElement = 0;
  13.         int printStart = 0;
  14.         int printEnd = 0;
  15.  
  16.         for (int i = 0; i < array.Length; i++)
  17.         {
  18.             currentSum += array[i];
  19.             if (currentSum == s)
  20.             {
  21.                 printStart = startElement; //get the element from which we start printing
  22.                 printEnd = i; //get the element at which we end printing
  23.                 break;
  24.             }
  25.             if (i == array.Length - 1)
  26.             {
  27.                 currentSum = 0;
  28.                 startElement++;
  29.                 if (startElement == array.Length)
  30.                 {
  31.                     break;
  32.                 }
  33.                 i = startElement - 1; //-1, because we have a i++ in the for loop
  34.             }
  35.         }
  36.         if (s!=currentSum)
  37.         {
  38.             Console.WriteLine("No such sum in array");
  39.             return;
  40.         }
  41.         for (int i = printStart; i <= printEnd; i++)
  42.         {
  43.             Console.Write("{0} ", array[i]);
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment