Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class ZeroSubset
- {
- static void Main()
- {
- /* We are given 5 integer numbers. Write a program that finds all subsets of these numbers whose sum is 0.
- * Assume that repeating the same subset several times is not a problem */
- int[] arrayInt = new int[5];
- Console.WriteLine("Enter a five integers");
- for (int counter = 0; counter < arrayInt.Length; counter++) // input 5 integers inta array
- {
- Console.Write("int [{0}]: ", counter + 1);
- arrayInt[counter] = Convert.ToInt32(Console.ReadLine());
- }
- int counterOfZeroSums = 0;
- // check for sum of two numbers -> using 2 loops: i, j
- for (int i = 0; i < arrayInt.Length - 1; i++)
- {
- for (int j = (i + 1); j < arrayInt.Length; j++)
- {
- if (arrayInt[i] + arrayInt[j] == 0)
- {
- Console.WriteLine("{0} + {1} = 0", arrayInt[i], arrayInt[j]);
- counterOfZeroSums++;
- }
- }
- }
- // check for sum of three numbers -> using 3 loops: i, j, k
- for (int i = 0; i < arrayInt.Length - 2; i++)
- {
- for (int j = (i + 1); j < arrayInt.Length - 1; j++)
- {
- for (int k = (j + 1); k < arrayInt.Length; k++)
- {
- if (arrayInt[i] + arrayInt[j] + arrayInt[k] == 0)
- {
- Console.WriteLine("{0} + {1} + {2} = 0", arrayInt[i], arrayInt[j], arrayInt[k]);
- counterOfZeroSums ++;
- }
- }
- }
- }
- // check for sum of four numbers -> using 4 loops: i, j, k, l
- for (int i = 0; i < arrayInt.Length - 3; i++)
- {
- for (int j = (i + 1); j < arrayInt.Length - 2; j++)
- {
- for (int k = (j + 1); k < arrayInt.Length - 1; k++)
- {
- for (int l = (k + 1); l < arrayInt.Length; l++)
- {
- if (arrayInt[i] + arrayInt[j] + arrayInt[k] + arrayInt[l] == 0)
- {
- Console.WriteLine("{0} + {1} + {2} + {3} = 0",
- arrayInt[i], arrayInt[j], arrayInt[k], arrayInt[l]);
- counterOfZeroSums ++;
- }
- }
- }
- }
- }
- // check for sum of all five numbers
- if (arrayInt[0] + arrayInt[1] + arrayInt[2] + arrayInt[3] + arrayInt[4] == 0)
- {
- Console.WriteLine("{0} + {1} + {2} + {3} + {4} = 0",
- arrayInt[0], arrayInt[1], arrayInt[2], arrayInt[3], arrayInt[4]);
- counterOfZeroSums ++;
- }
- if (counterOfZeroSums == 0)
- {
- Console.WriteLine("no zero subset");
- }
- else
- {
- Console.WriteLine("\nTotal: {0} zero subsets", counterOfZeroSums);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement