WAP to Print All Possible Number Combinations Whose Sum is 10

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

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:

  1. The program declares an integer array containing a sequence of numbers.
  2. It calls the combinator function, passing the array a as an argument.
  3. 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).
  4. For each pair of elements, the program calculates the sum of the two numbers (sum = a[i] + a[j]).
  5. 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]).
  6. The program continues this process to find all pairs of numbers in the sequence that add up to 10.
  7. 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.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment