Advertisement
Teodor92

10. SumSeq

Jan 12th, 2013
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.14 KB | None | 0 0
  1. /* Write a program that finds in given array of
  2.  * integers a sequence of given sum S (if present).
  3.  * Example:  {4, 3, 1, 4, 2, 5, 8}, S=11  {4, 2, 5} */
  4.  
  5. using System;
  6. using System.Text;
  7.  
  8. class SequenceByGivenSum
  9. {
  10.     static void Main()
  11.     {
  12.         int s = int.Parse(Console.ReadLine());
  13.         int[] myArray = { 4, 3, 1, 4, 2, 5, 8 };
  14.         string sequence = "";
  15.         StringBuilder sequenceBuild = new StringBuilder();
  16.         for (int i = 0; i < myArray.Length; i++)
  17.         {
  18.             int sum = 0;
  19.             for (int j = i; j < myArray.Length; j++)
  20.             {
  21.                 sum = sum + myArray[j];
  22.                 sequenceBuild.AppendFormat("{0}, ",myArray[j]);
  23.                
  24.                 if (sum > s)
  25.                 {
  26.                     sequenceBuild.Clear();
  27.                     sum = 0;
  28.                     break;
  29.                 }
  30.                 if (sum == s)
  31.                 {
  32.                     sequence = sequenceBuild.ToString();
  33.                     Console.WriteLine("This sequence has the sum of {0} : {1}", s, sequence);
  34.                 }
  35.             }
  36.         }
  37.        
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement