CODING JOY

The stunning potpourri of coding and mundane life

CATALAN NUMBERS IN JAVA LANGUAGE



AMRUHA AHMED
29th November,2023.


Catalan Numbers are the sequence of numbers that are calculated using the formula:

(2n)!/(n+1)!n!

Where n=0,1,2,3….

Catalan Numbers prove to be extremely useful in calculating the number of binary search trees that can be made using 'n' nodes.

blog1

FUNCTIONS REQUIRED:

VARIABLES REQUIRED IN FACT FUNCTION:

VARIABLES REQUIRED IN THE MAIN FUNCTION:

ALGORITHM FOR MAIN FUNCTION:

PROGRAM:

                  
                    import java.util.*;
                    class catalannumber
                    {
                        Scanner ob=new Scanner(System.in);
                    int fact(int n)//recursive function to calculate factorial of 'n'
                    {
                        if(n==0)
                        return 1;
                        else
                        return(n*fact(n-1));
                    }
                    void main()
                    {
                        int ctr;//stores the count of numbers to be generated
                        System.out.print("\n Enter the count of catalan numbers to be generated:");
                        ctr=ob.nextInt();
                        System.out.println("\n The first "+ctr+" Catalan Numbers are...\n");
                        for(int i=0;i<ctr;i++)
                        {
                            int term1=fact(2*i);//stores the value of(2n)!
                            int term2=fact(i+1);//stores the value of (n+1)!
                            int term3=fact(i);//stores the value of n!
                            int finalterm=(int)term1/(term2*term3);//gives final term=catalan number at i'th position
                            System.out.print(finalterm+"  ");
                        }
                    }
                    }         
             
         

DRY RUN:

If ctr=5 then the following will be the values of i, term1, term2, term3 and finalterm: blog1

OUTPUT:

Enter the count of catalan numbers to be generated: 5

The first 5 Catalan Numbers are...

1 1 2 5 14