In this Java pattern program, we show the steps to print the same alphabet or character in every row and column of a right angled triangle using for loop, while loop, and functions.
The below program accepts the user-entered rows and uses the nested for loop to traverse the rows and columns. Next, the program will print the same character or alphabet (A) in a right angled triangle pattern.
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter Numbers of Rows = ");
int rows = sc.nextInt();
int a = 65;
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j <= i; j++ )
{
System.out.printf("%c ", a);
}
System.out.println();
}
}
}
Enter Numbers of Rows = 12
A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A
A A A A A A A A A A A A
Within this program, we replaced the for loop with a while loop to traverse the rows and columns and print the right angled triangle of the same alphabet A at each position. For more Alphabet Patterns, please click here.
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
int rows, i, j, a = 65;
System.out.print("Enter Numbers of Rows = ");
rows = sc.nextInt();
i = 0 ;
while (i < rows )
{
j = 0 ;
while (j <= i )
{
System.out.printf("%c ", a);
j++;
}
System.out.println();
i++;
}
}
}
Enter Numbers of Rows = 15
A
A A
A A A
A A A A
A A A A A
A A A A A A
A A A A A A A
A A A A A A A A
A A A A A A A A A
A A A A A A A A A A
A A A A A A A A A A A
A A A A A A A A A A A A
A A A A A A A A A A A A A
A A A A A A A A A A A A A A
A A A A A A A A A A A A A A A
This example allows the user to enter the rows and the alphabet characters. Next, within this Java pattern program, we created a RightTriSameAlpha function to print the right angled triangle of user-given alphabets on rows and columns.
import java.util.Scanner;
public class Example {
private static Scanner sc;
public static void main(String[] args) {
sc = new Scanner(System.in);
System.out.print("Enter Numbers of Rows = ");
int rows = sc.nextInt();
System.out.print("Enter Character = ");
char a = sc.next().charAt(0);
RightTriSameAlpha(rows, a);
}
public static void RightTriSameAlpha(int rows, char a) {
for (int i = 0 ; i < rows; i++ )
{
for (int j = 0 ; j <= i; j++ )
{
System.out.printf("%c ", a);
}
System.out.println();
}
}
}