Advertisement
Klaxon

[C# Arrays] Sequence of Given Sum

Sep 30th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.85 KB | None | 0 0
  1. // 10. 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.  
  4. using System;
  5.  
  6. class SequenceOfGivenSum
  7. {
  8.     static void Main()
  9.     {
  10.         // get the array size and wanted sum
  11.         Console.Write("Enter wanted array size: ");
  12.         int n = int.Parse(Console.ReadLine());
  13.  
  14.         Console.Write("Enter wanted sum: ");
  15.         int sum = int.Parse(Console.ReadLine());
  16.  
  17.         int[] array = new int[n];
  18.  
  19.         // help variables
  20.         int currentSum = 0;
  21.         int startIndex = 0;
  22.         int endIndex = 0;
  23.         int count = 0;
  24.  
  25.         for (int i = 0; i < n; i++)
  26.         {
  27.             array[i] = int.Parse(Console.ReadLine());
  28.         }
  29.  
  30.         // main magic
  31.         for (int i = 0; i < n; i++)
  32.         {
  33.             currentSum = 0;
  34.             count = 0;
  35.  
  36.             for (int j = i; j < n; j++)
  37.             {
  38.                 currentSum += array[j];
  39.                 if (currentSum < sum)
  40.                 {
  41.                     count++;
  42.                 }
  43.                 if (currentSum > sum)
  44.                 {
  45.                     currentSum = 0;
  46.                     count = 0;
  47.                 }
  48.                 if (currentSum == sum)
  49.                 {
  50.                     startIndex = j - count; // get the starting point
  51.                     endIndex = j; // get the ending point
  52.                     break;
  53.                 }
  54.             }
  55.         }
  56.  
  57.         // printing
  58.         Console.Write("{");
  59.         for (int i = startIndex; i <= endIndex; i++)
  60.         {
  61.             if (i == endIndex)
  62.             {
  63.                 Console.Write("{0}", array[i]);
  64.             }
  65.             else
  66.             {
  67.                 Console.Write("{0}, ", array[i]);
  68.             }
  69.         }
  70.         Console.WriteLine("}");
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement