Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to get the combination of a number in Java using a function

okwudili onyejiaku


We can get the combination of a number by creating a function. A combination is used to find the number of possible arrangements of objects without regarding the order in which they are selected.

We will use the mathematical formula below where we use some factorials n!, r!, and (n-r)!. Hence, we will create a function that returns the factorial.

Formula for combination in mathematics

From the illustration above, we can see that:

  • nCr: Represents the number of combinations.
  • n : Represents the total number of objects.
  • r: Represents the number of chosen objects.


The syntax for finding the factorial of a number is as follows:

for(counter; counter <= number; counter++) {
    result = result * counter;
Syntax for finding the factorial of a number


The parameters in the loop are as follows:

  • counter: Represents a counter. It will be used for looping.
  • number: Represents the number whose factorial we want to find.

Code example

Let's look at a code example below:

class HelloWorld {
    // create the factorial function
    public static int factorial(int num){
      int result = 1, counter;
      // create for loop
      for(counter=1; counter<=num; counter++){
        result = result*counter;

      return result;

    public static void main( String args[] ) {
        // create some numbers of objects we want to get the combination
        int n1 = 10;
        int n2 = 4;
        // create number of the objects are taken at a time
        int r1 = 3;
        int r2 = 2;

        // get the combination based on the mathematical formula
Get the combination of a number


  • Line 3: We create the factorial function, which takes an integer number and returns its factorial.
  • Lines 15 - 16: We create and initialize variables for the number of objects we want to get the combinations for.
  • Lines 19 - 20: We create the number of objects taken at a particular time for every selection.
  • Lines 23 - 24: With the mathematical formula for combination, as explained earlier on, we get the combinations and print the values to the console.



View all Courses

Keep Exploring