Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 10: Write a Java program to calculate the combination of a given number.

Combination.java

import java.util.Scanner;

public class Combination
{
	// fact()  - A method to calculate factorial.
	static int fact(int num)
	{
		int factorial=1;
		for(int i=2;i<=num;i++)
		{
			factorial=factorial*i;
		}
		return factorial;
	}
	
	//main method
	public static void main(String[] args) 
	{
		Scanner s =new Scanner(System.in);
		int n,r;
		
		System.out.println("Enter the value of n");
		n=s.nextInt();
		System.out.println("Enter the value of r");
		r=s.nextInt();
		
		//calculating nCr = (n)!/((n-r)!*(r)!)
		//calling the method fact() to calculate the factorial.
		
		double combination= fact(n)/(fact(n-r)*fact(r)); 
		System.out.println(combination);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.