Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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}
- using System;
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("Enter the size of the array: ");
- int size = int.Parse(Console.ReadLine());
- int[] arr = new int[size];
- //Entering the values of the array
- for (int i = 0; i < arr.Length; i++)
- {
- Console.Write("arr[{0}] = ", i);
- arr[i] = int.Parse(Console.ReadLine());
- }
- Console.WriteLine();
- Console.WriteLine("Enter the SUM to find: ");
- int sum = int.Parse(Console.ReadLine());
- //Finding the elements that have the required sum
- int currentSum = 0;
- int firstIndex = 0;
- int numElems = 0;
- bool found = false;
- int count = 0;
- for (int j = 0; j < arr.Length; j++)
- {
- for (int i = j; i < arr.Length; i++)
- {
- currentSum += arr[i];
- count++;
- if (currentSum == sum && count > 1)
- {
- firstIndex = j;
- numElems = i - j + 1;
- found = true;
- }
- }
- currentSum = 0;
- count = 0;
- }
- //Printing the result
- if (found == true)
- {
- for (int i = 0; i < arr.Length; i++)
- {
- if (i == 0)
- {
- Console.Write("{");
- }
- Console.Write("{0}, ", arr[i]);
- if (i == arr.Length - 1)
- {
- Console.Write("}");
- }
- }
- Console.Write(" ------> ");
- for (int i = firstIndex; i < firstIndex + numElems; i++)
- {
- Console.Write("{0},", arr[i]);
- }
- Console.WriteLine();
- }
- else
- {
- Console.WriteLine("In this array none of the elements make the sum of {0}.", sum);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement