CODING JOY

The stunning potpourri of coding and mundane life

CATALAN NUMBERS IN C LANGUAGE



AMRUHA AHMED
28th 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:

                
                    #include<stdio.h>
                    #include<stdlib.h>
                    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
                        printf("\n Enter the count of catalan numbers to be generated:");
                        scanf("%d",&ctr);
                        printf("\n The first %d Catalan Numbers are...\n",ctr);
                        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
                            printf("%d\t",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