Advertisement
stefanpu

Fimd sum in array

Feb 9th, 2013
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.23 KB | None | 0 0
  1. //10.Write a program that finds in given array of integers a sequence of given
  2. //sum S (if present).
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8.  
  9. namespace _10.sequenceGivenSum
  10. {
  11.     class Program
  12.     {
  13.         static void Main(string[] args)
  14.         {
  15.             int S;
  16.             int sum;
  17.             int firstPos;
  18.             int counter;
  19.             int[] array;
  20.             Input(out S, out sum, out firstPos, out counter, out array);
  21.  
  22.             for (int i = 0; i < array.Length; i++)
  23.             {
  24.                 sum += array[i];
  25.                 counter++;
  26.  
  27.                 if (sum==S)
  28.                 {
  29.                     for (int j = 0; j < counter; j++)
  30.                     {
  31.                         Console.Write("{0} ",array[firstPos]);
  32.                         firstPos++;
  33.                     }
  34.                     break;
  35.                 }
  36.  
  37.                 else
  38.                 {
  39.                     while (sum>S)
  40.                     {
  41.                         sum -= array[firstPos];
  42.                         firstPos++;
  43.                         counter--;
  44.                     }
  45.  
  46.                     if (sum == S && counter>0)
  47.                     {
  48.                         for (int j = 0; j < counter; j++)
  49.                         {
  50.                             Console.Write("{0} ", array[firstPos]);
  51.                             firstPos++;
  52.                         }
  53.                         return;
  54.                     }
  55.                 }
  56.             }
  57.  
  58.             Console.WriteLine("No subsequence sums to {0}", S);
  59.         }
  60.  
  61.         private static void Input(out int S, out int sum, out int firstPos, out int counter, out int[] array)
  62.         {
  63.             Console.WriteLine("Enter S:");
  64.             S = int.Parse(Console.ReadLine());
  65.             sum = 0;
  66.             firstPos = 0;
  67.             counter = 0;
  68.             Console.WriteLine("Enter the size of the array:");
  69.             int size = int.Parse(Console.ReadLine());
  70.  
  71.             array = new int[size];
  72.             for (int i = 0; i < array.Length; i++)
  73.             {
  74.                 array[i] = int.Parse(Console.ReadLine());
  75.             }
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement