ellapt

T7.10.FindSumSequence

Jan 15th, 2013
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. using System;
  2.  
  3. class FindSumSequence
  4. {
  5. static void Main()
  6. {
  7. Console.WriteLine("Find in given array of integers a sequence of given sum S (if present)");
  8. string inputVar;
  9. uint n;
  10. int sum = 0; ;
  11. int tempSum = 0;
  12. int start = 0;
  13. int end = 0;
  14. do
  15. {
  16. Console.Write("Enter array length: ");
  17. }
  18. while (!(uint.TryParse(inputVar = Console.ReadLine(), out n)) || n == 0);
  19.  
  20. int[] arrayOfints = new int[n];
  21.  
  22. Console.WriteLine("Enter the elements of the array:");
  23. for (int i = 0; i < n; i++)
  24. {
  25. arrayOfints[i] = int.Parse(Console.ReadLine());
  26. }
  27. Console.WriteLine("Enter the sum:");
  28. sum = int.Parse(Console.ReadLine());
  29.  
  30. for (int i = 0; i < n; i++)
  31. {
  32. for (int j = i; j < n; j++)
  33. {
  34. tempSum += arrayOfints[j];
  35. if (tempSum == sum)
  36. {
  37. start = i;
  38. end = j;
  39. }
  40. else if (tempSum>sum)
  41. {
  42. tempSum = 0;
  43. break;
  44. }
  45. }
  46. }
  47. if (start == 0 && end == 0)
  48. {
  49. Console.WriteLine("There is not a sequence with sum={0}", sum);
  50. }
  51. else
  52. {
  53. Console.WriteLine("The following sequense gives a sum={0}:", sum);
  54. for (int i = start; i < end; i++)
  55. {
  56. Console.Write("{0}, ", arrayOfints[i]);
  57. }
  58. Console.WriteLine("{0}", arrayOfints[end]);
  59. }
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment