w3resource

Java: Reads an integer n and find the number of combinations of a,b,c and d will be equal to n


Count Combinations for Sum N

Write a Java program which reads an integer n and finds the number of combinations of a,b,c and d (0 ≤ a,b,c,d ≤ 9) where (a + b + c + d) equals n.

Input:

n (1 ≤ n ≤ 50).

Sample Solution:

Java Code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Prompting the user to input the number (n)
        System.out.println("Input the number(n):");

        // Creating a Scanner object for user input
        Scanner s = new Scanner(System.in);

        // Reading the input number (n) from the user
        int c = s.nextInt();

        // Calling the check method to find the number of combinations
        int ans = check(c);

        // Displaying the number of combinations of a, b, c, and d
        System.out.println("Number of combinations of a, b, c, and d :");
        System.out.println(ans);
    }

    // Method to check the number of combinations
    static int check(int c) {
        // Initializing a counter for combinations
        int ctr = 0;

        // Nested loops to iterate through all possible combinations of a, b, c, and d
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                for (int k = 0; k < 10; k++) {
                    for (int l = 0; l < 10; l++) {
                        // Checking if the sum of a, b, c, and d equals the input number (n)
                        if (i + j + k + l == c) {
                            // Incrementing the counter for valid combinations
                            ctr++;
                        }
                    }
                }
            }
        }

        // Returning the total number of combinations
        return ctr;
    }
} 

Sample Output:

Input the number(n):
 5 
Number of combinations of a, b, c and d :
56

Flowchart:

Flowchart: Java exercises: Find the number of combinations of a,b,c and d will be equal to n.



For more Practice: Solve these Related Problems:

  • Write a Java program to count the number of combinations of four digits (0–9) that sum to a given target using recursion.
  • Write a Java program to determine the number of combinations of five digits that sum to a specified value under given constraints.
  • Write a Java program to compute the number of combinations where the sum of selected digits equals n using dynamic programming.
  • Write a Java program to count the number of distinct combinations of digits (order irrelevant) that yield a specific sum.

Go to:


PREV : Compute Loan Debt After N Months.
NEXT : Count Prime Numbers ≤ N.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.