Saturday, December 10, 2016

How to Print Pyramid Pattern of Alphabets in Java program

In earlier programming tutorials, I have taught you how to print pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn printing pyramid pattern 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 nested loop in Java. Actually, 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 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 one for exercise to develop your creativity and coding skill.

The strong coding skill is a must for any programmer because this is the one skill which 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 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 help when you start learning to program.

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 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 which needs to be cast back into character.

There is one more thing in this program which is very important to learn, clever use of print() and println() method to print characters in the same row and then advancing to next row. This is the essential technique to solve any pattern based problem in Java.  If you remember, I have used them earlier to print Floyd's triangle and Pascal's triangle in Java, two of the most popular pattern based problem 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 printed pyramid pattern of 5 rows and in the next example, we have printed pyramid pattern of 6 rows depending upon user input.

This is rather a simple example of 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 following patterns of alphabets in Java:

How to Print Pyramid Pattern of Alphabets in Java program


That's all about how to print pattern of Alphabets in 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 sieve of Eratosthenes algorithm in Java? (solution)
  • How to implement post-order traversal in Java? (program)
  • How to add two numbers without using 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 binary search tree in Java? (solution)
  • How to implement 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 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 sharp your coding and algorithm skill then you should try to solve problems given in Algorithm Design Manual book by Steve Skiena. That book is the bible to improve your coding, data structure, and algorithm skill. It present you so many different programming challenges which will test your Maths, Physics, Computer Science, logic and algorithmic skill. 

Further Learning
Algorithms and Data Structures - Part 1 and 2
Java Fundamentals, Part 1 and 2
Cracking the Coding Interview - 189 Questions and Solutions

1 comment :

Arif Zuhairi said...

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?

Post a Comment