Advertisement
svetoslavhl

Untitled

May 21st, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 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 Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. Console.WriteLine("Enter the size of the array: ");
  11. int size = int.Parse(Console.ReadLine());
  12.  
  13. int[] arr = new int[size];
  14.  
  15.  
  16. //Entering the values of the array
  17.  
  18. for (int i = 0; i < arr.Length; i++)
  19. {
  20.  
  21. Console.Write("arr[{0}] = ", i);
  22. arr[i] = int.Parse(Console.ReadLine());
  23.  
  24.  
  25. }
  26.  
  27. Console.WriteLine();
  28. Console.WriteLine("Enter the SUM to find: ");
  29. int sum = int.Parse(Console.ReadLine());
  30.  
  31.  
  32.  
  33. //Finding the elements that have the required sum
  34.  
  35. int currentSum = 0;
  36. int firstIndex = 0;
  37. int numElems = 0;
  38. bool found = false;
  39. int count = 0;
  40. for (int j = 0; j < arr.Length; j++)
  41. {
  42.  
  43.  
  44. for (int i = j; i < arr.Length; i++)
  45. {
  46. currentSum += arr[i];
  47. count++;
  48. if (currentSum == sum && count > 1)
  49. {
  50. firstIndex = j;
  51. numElems = i - j + 1;
  52. found = true;
  53.  
  54. }
  55.  
  56.  
  57. }
  58.  
  59.  
  60. currentSum = 0;
  61. count = 0;
  62.  
  63.  
  64. }
  65.  
  66. //Printing the result
  67.  
  68. if (found == true)
  69. {
  70.  
  71. for (int i = 0; i < arr.Length; i++)
  72. {
  73. if (i == 0)
  74. {
  75. Console.Write("{");
  76. }
  77.  
  78. Console.Write("{0}, ", arr[i]);
  79.  
  80.  
  81.  
  82. if (i == arr.Length - 1)
  83. {
  84.  
  85. Console.Write("}");
  86.  
  87. }
  88.  
  89.  
  90.  
  91. }
  92.  
  93. Console.Write(" ------> ");
  94.  
  95. for (int i = firstIndex; i < firstIndex + numElems; i++)
  96. {
  97.  
  98. Console.Write("{0},", arr[i]);
  99.  
  100.  
  101. }
  102.  
  103. Console.WriteLine();
  104.  
  105. }
  106. else
  107. {
  108.  
  109.  
  110.  
  111. Console.WriteLine("In this array none of the elements make the sum of {0}.", sum);
  112.  
  113.  
  114.  
  115. }
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122.  
  123.  
  124.  
  125.  
  126.  
  127.  
  128. }
  129. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement