﻿ Java - The first 10 Catalan numbers from the Pascal triangle

# Java: Print out the first 10 Catalan numbers by extracting them from Pascal's triangle

## Java Numbers: Exercise-8 with Solution

Write a Java program to print out the first 10 Catalan numbers by extracting them from Pascal's triangle.

In combinatorial mathematics, the Catalan numbers form a sequence of natural numbers that occur in various counting problems, often involving recursively-defined objects. They are named after the Belgian mathematician Eugène Charles Catalan.
The first Catalan numbers for n = 0, 1, 2, 3, … are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020, 91482563640, 343059613650, 1289904147324, 4861946401452,

Sample Solution:

Java Code:

``````import java.util.Scanner;
public class Example8 {
public static void main(String[] args) {
int num = 10;
int[] t = new int[num + 2];
t = 1;
System.out.printf("\nList 10 Catalan numbers:-\n");
for (int i = 1; i <= num; i++) {

for (int j = i; j > 1; j--)
t[j] = t[j] + t[j - 1];

t[i + 1] = t[i];

for (int j = i + 1; j > 1; j--)
t[j] = t[j] + t[j - 1];
System.out.printf("\n%d ", t[i + 1] - t[i]);
}
System.out.printf("\n");
}
}
```
```

Sample Output:

```List 10 Catalan numbers:-
1
2
5
14
42
132
429
1430
4862
16796
```

Flowchart: Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Java: Tips of the Day

IsPowerOfTwo

Checks if a value is positive power of two.

To understand how it works let's assume we made a call IsPowerOfTwo(4).

As value is greater than 0, so right side of the && operator will be evaluated.

The result of (~value + 1) is equal to value itself. ~100 + 001 => 011 + 001 => 100. This is equal to value.

The result of (value & value) is value. 100 & 100 => 100.

This will value the expression to true as value is equal to value.

```public static boolean isPowerOfTwo(final int value) {
return value > 0 && ((value & (~value + 1)) == value);
}
```

Ref: https://bit.ly/3sA5d4I

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook