Pattern 13
1. You are given a number n.Input Format
2. You've to create a pattern as shown in output format
A number nOutput Format Question Video
1 <= n <= 10Sample Input
5Sample Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Editorial
"The last thing one discovers in composing a work is what to put first."
Question:
1. You are given a number n.
2. You have to create a pattern as shown in the output format.
Input format:
A number n
Output format:
Constraints:
1 <= n <= 10
Solution Approach:
We need a triangle of numbers, so let us focus on the aspects of content of the pattern and shape of the pattern one by one. We know that we need the shape of a triangle like we created with stars, so let us first give our pattern a shape first, and then think about what the contents of that pattern should be.
import java.util.*;public class Main{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); for(int i =1;i<=n;i++) { for(int j = 1;j<=i;j++) { System.out.print( "* "); } System.out.println(); } } }
java false
The above program will provide us with the required shape "starfilled". Now that we have dealt with the shape issue, let us move on to the content analysis.
Up until now, we have been initializing outer loop iterator 'i' as 1 and running it until it was equal to input value n. Now, we make a slight change to it and understand why.
[1,5] > means 5 objects (1,2,3,4,5)
[0,5) > also means 5 objects (0,1,2,3,4) > so 'i' = 0 to i< n will still display 'n' rows
In this program, we are going to start 'i' from 0 to less than n. We also start 'j' from 0 but run it till less than or equal to 'i' only because for each row, the number of columns is one more than row number. The output shows symmetry in the elements it prints. First and last entry on each row is '1'. We know that C_0^n = 1= C_n^n.
Comparing the last row to
C_0^5=1;C_1^n=5;C_2^n=10
And after 10, the pattern is symmetric.
We also know that the mathematical relation C_k^n=C_(nk)^n also holds true; which is the basis on which we can say that the pattern is symmetric, because then: C_3^5=10; C_4^5=5; C_1^5=1
Now to get the required pattern printed in our code, using our outer and inner loop, we are going to use the formula C_(k+1)^n=(C_k^n.(nk))/(k+1).
We modify it to suit our 'i' and 'j' variables as:C_(j+1)^i=(C_j^i.(ij))/(j+1) .
Integrating this formula into our code;
import java.util.*; public class Main{ public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); for(int i =0;i < n ;i++) { int icj = 1; for(int j = 0;j < = i;j++) { System.out.print( icj + " "); int icjp1 = (icj*(ij))/(j+1); icj = icjp1; } System.out.println(); } } }
java false
This code yields us the required output:
(Example n = 5)

Asked in Companies

Related Topics