Given a number N, the task is to print the following pattern:- Examples:
Input : 10
Output :
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
Input :5
Output :
*
* *
* * *
* * * *
* * * * *
There is a nested loop required to print the above pattern. The outer loop is used to run for the number of rows given as input. The first loop within the outer loop is used to print the spaces before each star. As you can see the number of spaces decreases with each row while we move towards the base of the triangle, so this loop runs one time less with each iteration. The second loop within the outer loop is used to print the stars. As you can see the number of stars increases in each row as we move towards the base of the triangle, so this loop runs one time more with each iteration. Clarity can be achieved if this program is dry run.
Java
import java.util.*;
class pattern {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println( "Enter the number of rows to be printed" );
int rows = sc.nextInt();
for ( int i = 1 ; i <= rows; i++) {
for ( int j = rows; j >= i; j--) {
System.out.print( " " );
}
for ( int j = 1 ; j <= i; j++) {
System.out.print( "* " );
}
System.out.println();
}
}
}
|
Time Complexity: O(rows*rows)
Auxiliary Space: O(1)
Method 2:Using Recursion
Java
import java.util.*;
class GFG {
static void printspace( int space)
{
if (space == 0 )
return ;
System.out.print( " " );
printspace(space - 1 );
}
static void printstar( int asterisk)
{
if (asterisk == 0 )
return ;
System.out.print( "* " );
printstar(asterisk - 1 );
}
static void printrow( int n, int num)
{
if (n == 0 )
return ;
printspace(n - 1 );
printstar(num - n + 1 );
System.out.println( "" );
printrow(n - 1 , num);
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int rows = 5 ;
printrow(rows, rows);
}
}
|
Output *
* *
* * *
* * * *
* * * * *
Time Complexity: O(rows*rows)
Auxiliary Space: O(1)