Advertisement
Naralex

Arrays-SequenceOfGivenSum

Jan 16th, 2013
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using System;
  2.  
  3. class SequenceOfGivenSum
  4. {
  5.     static void Main()
  6.     {
  7.         /*10.Write a program that finds in given array of integers a sequence of given sum S (if present).
  8.         Example:{4, 3, 1, 4, 2, 5, 8}, S=11  {4, 2, 5}*/
  9.  
  10.         Console.Write("Array size: ");
  11.         int arraySize = int.Parse(Console.ReadLine());
  12.         int[] arr = new int[arraySize];
  13.  
  14.         int number;
  15.  
  16.         for (int index = 0; index < arraySize; index++)
  17.         {
  18.             Console.Write("Position {0} : ", index + 1);
  19.             number = int.Parse(Console.ReadLine());
  20.             arr[index] = number;
  21.         }
  22.  
  23.         Console.Write("The sum your looking for: ");
  24.         int sum = int.Parse(Console.ReadLine());
  25.  
  26.         int startPosition = 0, endPosition = 0, curentSum = 0;
  27.  
  28.         for (int i = 0; i < arr.Length-1; i++)
  29.         {
  30.             curentSum = arr[i];
  31.  
  32.             for (int k = i+1; k < arr.Length-1; k++)
  33.             {
  34.                 curentSum += arr[k];
  35.  
  36.                 if (curentSum == sum)
  37.                 {
  38.                     startPosition = i;
  39.                     endPosition = k;
  40.                 }
  41.                 if (curentSum > sum)
  42.                 {
  43.                     curentSum = 0;
  44.                     break;
  45.                 }
  46.             }
  47.         }
  48.         for (int i = 3; i <= 5; i++)
  49.         {
  50.             Console.Write(arr[i] + " ");
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement