Wednesday, September 27, 2023

How to Print Pyramid Pattern of Alphabet Characters in Java? Example Tutorial [Solved]

In earlier programming tutorials, I have taught you how to print a pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn the printing pyramid patterns of alphabets. If you understand the logic of previous programs then this one won't be difficult for you because we will use the same logic of printing rows and columns using the nested loop in Java. Actually, a pyramid pattern is nothing but a matrix where you need to print rows and columns. Though, you need to learn where to print those values and when to move to the next row.

Once you know this trick of advancing, you can print any kind of pyramid pattern in Java. The one, we'll see in this tutorial is the simplest of one but I'll give you some tough ones for exercise to develop your creativity and coding skill.

Strong coding skill is a must for any programmer because this is the one skill that is valued more than any programming language. No matter, whether you code in Java, C, C++, or Python, if you are a good coder, you will remain a coder.

On the other hand, if you are a good Java developer it doesn't mean you are a good programmer or coder. Learning the theory of Java and API is easier as compared to developing coding and design skill. This is where such kind of program helps when you start learning to program.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve their knowledge and algorithms skills.

Problem

You need to write a Java program to print the following pattern of alphabets:
A
AB
ABC
ABCD
ABCDE

Your program should take input from the user about how many rows it needs to print as part of the pattern and also whether to print alphabets in lowercase or upper case.




How to Print Pyramid Pattern of Alphabets in Java program

Here is our Java program to solve this problem. This program uses the Scanner class to take input from the command prompt and nested loop to print the pyramid pattern of alphabets. In order to print alphabets you can use a char variable e.g. char nextChar = 'A' and then keep increasing it to get the next character e.g. (char) 'A' + 1 will print character B. 

You can start with a small case or capital case depending upon user input.

The key thing to remember here is casting the result of the addition. For example, if you don't cast 'A' + 1 back to the character then it will char nextChar = 'A' + 1; will give compile-time error because the result of integer arithmetic is always an integer and  you cannot store an integer value to a char variable.

In the background, Java will promote character 'A' to integer and then perform the addition with 1, hence the result of the addition will be an int that needs to be cast back into character.

There is one more thing in this program that is very important to learn, clever use of print() and println() method to print characters in the same row and then advancing to the next row. This is the essential technique to solve any pattern-based problem in Java like printing left and right triangle pattern.  

If you remember, I have also used them earlier to print Floyd's triangle and Pascal's triangle in Java, two of the most popular pattern-based problems in Java.




Java Program to Print Pyramid Pattern of Alphabets

import java.util.Scanner;

/*
 * Java Program to print pattern of alphabets in both upper and lower
 * case e.g.
 * a
 * ab
 * abc
 * abcd
 * abcde
 * abcdef
 */

public class PatternOfAlphabets {

  public static void main(String[] args) {

  Scanner commandReader = new Scanner(System.in);
  System.out
  .println("Welcome to Java Program for printing pattern of alphabets");
  System.out.println("Enter number of rows : ");
  int rows = commandReader.nextInt();
  System.out.println("Do you want pattern to be displayed in upper case? ");
  boolean isUpperCase = commandReader.nextBoolean();

  printPatternOfAlphabets(rows, isUpperCase);

  commandReader.close();

  }

  /**
  * A Java method to print pattern of alphabets
  * 
  * @param rows
  * - number of rows in pattern
  * @param isCapital
  * - if true, pattern will contain upper case alphabets
  */
  public static void printPatternOfAlphabets(int rows, boolean isCapital) {
  char start = 'a' - 1;
  if (isCapital) {
  start = 'A' - 1;
  }
  for (int i = 1; i <= rows; i++) {

  for (int j = 1; j <= i; j++) {
  char ch = (char) (start + j);
  System.out.print(ch);
  }
  System.out.println();
  }
  }

}

Output
Welcome to Java Program for printing pattern of alphabets
Enter number of rows : 
5
Do you want the pattern to be displayed in upper case? 
true
A
AB
ABC
ABCD
ABCDE

Welcome to Java Program for printing pattern of alphabets
Enter number of rows : 
6
Do you want the pattern to be displayed in upper case? 
false
a
ab
abc
abcd
abcde
abcdef

You can see that our program has nicely printed the pattern of alphabets in both upper and lowercase depending upon user input. You can also see that in the first example, we have a printed pyramid pattern of 5 rows and in the next example, we have a printed pyramid pattern of 6 rows depending upon user input.

This is rather a simple example of the printing pyramid pattern of Alphabets but it gives you the necessary technique to solve any pattern-based problem e.g. nested loop, advancing using print() and println(), and how to print the character in Java.  

Now, if you want to try further, you can try printing the following patterns of alphabets in Java, they are quite challenging and test your programming and coding skills, especially loop and if else statements. 

How to Print Pyramid Pattern of Alphabets in Java program


That's all about how to print patterns of Alphabets in the Java program. By using this technique i.e. nested loops, print() and println(), and using integer arithmetic to print character values in Java, you can print any kind of pattern in Java e.g. diamond pattern, pyramid pattern, rectangular patterns of alphabets, numbers, or stars, etc.

Other Coding Problems to learn Programming in Java
  • How to implement iterative quicksort in Java? (solution)
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to swap two numbers without using the third variable? (answer)
  • How to implement the sieve of the Eratosthenes algorithm in Java? (solution)
  • How to implement post-order traversal in Java? (program)
  • How to add two numbers without using the plus operator in Java? (answer)
  • How to implement in-order traversal in Java? (solution)
  • How to remove duplicate characters from String in Java? (program)
  • How to implement pre-order traversal of a binary tree in Java? (solution)
  • How to implement a binary search tree in Java? (solution)
  • How to implement a binary search algorithm in Java? (solution)
  • How to reverse a singly linked list in Java? (program)
  • How to print all leaf nodes of a binary tree in Java? (solution)
  • How to implement an insertion sort algorithm in Java? (answer)
  • How to reverse an ArrayList in place in Java? (solution)
  • Write a program to implement bubble sort in Java? (solution)
  • How to find the square root of a given number in Java? (solution)

Btw, if you are not a beginner and already solved this problem and looking for more challenging problems to really sharpen your coding and algorithm skills then you should try to solve problems given in the Algorithm Design Manual book by Steve Skiena. 

That book is the bible to improve your coding, data structure, and algorithm skill. It presents you with so many different programming challenges which will test your Maths, Physics, Computer Science, logic, and algorithmic skill. 

And lastly one question for you, which one is your favorite pattern among these? Left triangle pattern, right triangle pattern, star pattern, pyramid pattern, an or inverse pyramid pattern? Do you also like patterns or numbers or characters?

6 comments:

  1. I don't quite understand this two line
    char start = 'a' - 1;
    why do we need to minus 1? and this line
    char ch = (char) (start + j);
    why do we need to put ( ) and how does ( ) ( ) works?

    ReplyDelete
  2. injava characters are actually stored as integers according to a special code,
    the codes are different for Lowercase and uppercase , integer value for 'a'=97 AND integer value for 'A' =65;
    in the above program start ='a'-1//means 96
    start+j=97 //means 97 i.e=a if it is lowercasr same applicable in uppercase

    ReplyDelete
  3. above program " j is an integer variable "and "start is a charecter variable "
    to convert an integer variable to character variable write that line
    "char ch=(char)(start+j)"

    ReplyDelete
  4. Write a program to generate a strick graph
    A B C D E D C B A
    A B C D D C B A
    A B C C B A
    A B B A
    A A

    ReplyDelete
  5. write a program to generate
    a
    a b
    a b c
    without using ASCII values

    ReplyDelete
  6. Input: BreakingBad
    BB
    BRBA
    BREBAD
    BREABAD
    BREAKBAD
    BREAKIBAD
    BREAKINBAD
    BREAKINGBAD

    ReplyDelete