Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * 10. Write a program that finds in given array of integers a sequence of given sum S (if present).
- * Example: {4, 3, 1, 4, 2, 5, 8}, S=11 -> {4, 2, 5}
- */
- class SequenceOfGivenSum
- {
- static void Main()
- {
- int n;
- int S;
- int currentSum = 0;
- int firstIndex = 0;
- int lastIndex = 0;
- Console.Write("Number of array elements: ");
- string strN = Console.ReadLine();
- Console.Write("S = ");
- string strS = Console.ReadLine();
- if (!int.TryParse(strN, out n) || !int.TryParse(strS, out S))
- {
- Console.WriteLine("Invalid numbers!");
- }
- else
- {
- int[] array = new int[n];
- // Get all array values
- for (int i = 0; i < n; i++)
- {
- Console.Write("Please enter array element: ");
- array[i] = int.Parse(Console.ReadLine());
- }
- currentSum = array[0];
- for (int i = 0; i < array.Length; i++)
- {
- for (int j = i + 1; j < array.Length; j++)
- {
- currentSum += array[j];
- if (currentSum == S)
- {
- firstIndex = i + 1;
- lastIndex = j;
- }
- }
- currentSum = 0;
- }
- if (firstIndex > 0 && lastIndex > 0)
- {
- Console.WriteLine("The sequence with sum {0} is: ", S);
- Console.Write("{ ");
- for (int i = firstIndex; i <= lastIndex; i++)
- {
- if (i == lastIndex)
- {
- Console.Write("{0}", array[i]);
- }
- else
- {
- Console.Write("{0}, ", array[i]);
- }
- }
- Console.WriteLine(" }");
- }
- else
- {
- Console.WriteLine("There is no sequence with sum {0} in the array.", S);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement