@abhishekpandeycsaiml21_c74cb0ea3a791122 Benchmark your code with my code : and use the concepts given below :
Given pattern is seen as first numbers and then stars for a row. So, first do the work for numbers and then for stars. Also, all the characters are separated by a space.
In Pattern Question, there is a common method which we teach in course viz, taking nsp, nst, csp, cst and row variables.
Pattern Hack : Always first Try to first print pattern by ignoring the value to be printed then accommodate your value in that pattern. For e.g.,
1 2 3 4 5
1 2 3 4 *
1 2 3 * * *
1 2 * * * * *
1 * * * * * * *
View it as:-
- - - - -
- - - - *
- - - * * *
- - * * * * *
- * * * * * * *
``
`` Short Info about the variables:-
1. nsp (number of spaces)-> Number of spaces in very First Line of the pattern.
2. nst (number of stars)-> Number of stars in very first line of the pattern.
3. csp (counter of spaces)-> counter of spaces that will print the required number of spaces and will be initialized with 1 and incremented upto nsp.
4. cst (counter of stars)-> counter of spaces that will print the required number of stars and will be initialized with 1 and incremented upto nst.
5. rows -> It will be initialized with 1 and will go upto the total number of rows in the pattern.
In Given, pattern no spaces are there only stars are present.
- Thinking about variables : nst1 = N, nst2 = -1, cst = 1, rows = 1, total rows = N;
- Thinking about Value to be printed : row number is to be printed each time at the starting of the row and at the end of the row. So, starting of the row is when out cst is 1 and ending of the row when our cst is nst.
public static void pattern3(int N) {
int nst1 = N;
int nst2 = -1;
int rows = 1;
while (rows <= N) {
int val = 1;
int cst = 1;
while (cst <= nst1) {
System.out.print(val++ + " ");
cst++;
}
cst = 1;
while (cst <= nst2) {
System.out.print("* ");
cst++;
}
System.out.println();
nst1--;
nst2 += 2;
rows++;
}
}