Print All Possible Number Combinations Whose Sum is 10: The program InterviewPrograms55 aims to find pairs of numbers in a given sequence that add up to 10. It takes an input array of integers and looks for all combinations of two numbers whose sum is equal to 10.
If you are trying to understand the Java Program, then you should know Array uses in Java and For loop concepts
Print All Possible Number Combinations Whose Sum is 10
package com.softwaretestingo.interviewprograms; public class InterviewPrograms55 { /* * Write classes to find any pairs of numbers in a sequence that add up to 10. * Example: * * Sample input: 1, 8, 2, 3, 5, 7 * Sample output: “(8,2), (3, 7)” */ public static void main(String[] args) { int a[]= {1,2,3,4,9,5,6,7,8,10,0}; System.out.println("The Combinations in the array whose sum is 10 are:"); InterviewPrograms55.combinator(a); } public static void combinator(int a[]) { int sum=0; for(int i=0;i<a.length;i++) { for (int j=a.length-1;j>=0;j--) { sum=a[i]+a[j]; if(sum==10 && a[i]<=a[j] && a[i]!=a[j]) { System.out.println("("+a[i]+","+a[j]+")"); } } } } }
Output
The Combinations in the array whose sum is 10 are: (1,9) (2,8) (3,7) (4,6) (0,10)
Here’s how the program works:
- The program declares an integer array containing a sequence of numbers.
- It calls the combinator function, passing the array a as an argument.
- Inside the combinator function, there are two nested loops. The outer loop iterates through each element of the array, starting from the first element (i=0), and the inner loop iterates through the array in reverse, starting from the last element (j=a.length-1).
- For each pair of elements, the program calculates the sum of the two numbers (sum = a[i] + a[j]).
- If the sum is equal to 10 and the first number a[i] is less than or equal to the second number a[j], the program prints the pair in the format (a[i], a[j]).
- The program continues this process to find all pairs of numbers in the sequence that add up to 10.
- The output represents the combinations of pairs of numbers whose sum is equal to 10. For example, if the input array is [1, 2, 3, 4, 9, 5, 6, 7, 8, 10, 0], the output will be: “(1,9), (2,8), (3,7), (4,6)”. These are all the unique pairs whose sum is 10 and where the first number is less than or equal to the second number.