Venciity

C#] BOOK Arrays - 11 Задача

Jan 7th, 2014
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 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.  
  4. // не работи при пример : 20 - 10 , трябва да се пооправи
  5.  
  6. using System;
  7. using System.Text;
  8.  
  9. class SequenceByGivenSum
  10. {
  11.     static void Main()
  12.     {
  13.         Console.Write("Sum = ");
  14.         int s = int.Parse(Console.ReadLine());
  15.  
  16.         Console.Write("Enter array length: ");
  17.         int length = int.Parse(Console.ReadLine());
  18.         int[] myArray = new int[length];
  19.  
  20.         //enter array elements
  21.         for (int i = 0; i < myArray.Length; i++)
  22.         {
  23.             Console.Write("Number {0} = ", i + 1);
  24.             myArray[i] = int.Parse(Console.ReadLine());
  25.         }
  26.  
  27.  
  28.         string sequence = "";
  29.         StringBuilder sequenceBuild = new StringBuilder();
  30.         for (int i = 0; i < myArray.Length; i++)
  31.         {
  32.             int sum = 0;
  33.             for (int j = i; j < myArray.Length; j++)
  34.             {
  35.                 sum = sum + myArray[j];
  36.                 sequenceBuild.AppendFormat("{0}, ", myArray[j]);
  37.  
  38.                 if (sum > s)
  39.                 {
  40.                     sequenceBuild.Clear();
  41.                     sum = 0;
  42.                     break;
  43.                 }
  44.                 if (sum == s)
  45.                 {
  46.                     sequence = sequenceBuild.ToString();
  47.                     Console.WriteLine("This sequence has the sum of {0} : {1}", s, sequence);
  48.                 }
  49.             }
  50.         }
  51.  
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment