w3resource

C Exercises: Display the first 10 catalan numbers


12. Catalan Numbers Variants

Write a program in C to display the first 10 Catalan numbers.

Sample Solution:

C Code:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

// Function to calculate the nth Catalan number recursively
unsigned long int cataLan(unsigned int n)
{
    if (n <= 1) return 1; // Base case: Catalan number is 1 if n is 0 or 1
    unsigned long int catno = 0; // Initialize the Catalan number

    // Calculate the Catalan number using recursive formula
    for (int i = 0; i < n; i++)
        catno += cataLan(i) * cataLan(n - i - 1); // Sum of products of Catalan numbers

    return catno; // Return the calculated Catalan number
}

int main()
{
    printf("\n\n Find the first 10 Catalan numbers: \n");
    printf(" --------------------------------------\n");
    printf(" The first 10 Catalan numbers are: \n");

    // Calculate and display the first 10 Catalan numbers
    for (int i = 0; i < 10; i++)
        printf("%lu ", cataLan(i)); // Print the ith Catalan number

    printf("\n");

    return 0;
}

Sample Output:

 The first 10 catalan numbers are:                                                                             
1 1 2 5 14 42 132 429 1430 4862

Visual Presentation:

C programming: Display the first 10 catalan numbers.

Flowchart:

Flowchart: Display the first 10 catalan numbers

For more Practice: Solve these Related Problems:

  • Write a C program to compute Catalan numbers using dynamic programming.
  • Write a C program to display Catalan numbers alongside their binomial coefficient representations.
  • Write a C program to generate Catalan numbers recursively and analyze performance.
  • Write a C program to list Catalan numbers with combinatorial interpretations for each.

Go to:


PREV : Lucas Numbers Variants.
NEXT : Happy Number Check Variants.

C Programming 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.