×

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program.

To write the code for it, we take the following approach:

  1. Take user input and store it in a variable called row.
  2. To print the pencil, we use a nested loop in which the first loop is responsible for the number of rows and the second loop is responsible for the number of columns.

The pencil pattern is printed in two ways: using the static star character and using the user input character.

Let's look at each one separately to see how we can use static and user-input characters:

Static Star Character

Filename: PencilExample1.java

// Import any necessary classes and packages.
import java.util.Scanner ;  
  
// a class called PencilExample1 should be created to print 
//pencil pattern using static star characters.  
public class PencilExample1{  
      
    // main() method start  
    public static void main(String[] args){  
          
        // declare variables   
        int rows ;  
          
        // make an object of the Scanner class to receive user input.
        Scanner sc = new Scanner(System.in) ;  
        System.out.print("Enter number of rows: ") ;  
          
        //user input is taken and stored in the rows variable. 
        rows = sc.nextInt() ;  
          
        //call drawPencil() method of the Pencil class by creating an instance of the class  
        Pencil b = new Pencil() ;  
        b.drawPencil(rows) ;  
      
        }  
}  
  
// create a separate class for Pencil pattern  
class Pencil{  
          
    // create a user-defined method for drawing pattern  
    public void drawPencil(int rows){  
          
        // declare variables  
        int t ;  
          
        // use for loop from -row to +row  
        for(int i = -rows; i <= rows; i++)   
        {  
            t = i;  
              
            // for loop for columns  
            for(int j = 0; j <= rows; j++)  
            {  
                // check whether the value of t is less than j  
                if(t <= j)  
                    System.out.print("* ") ;  
                else  
                    System.out.print(" ") ;  
            }  
             System.out.println("") ;  
        }  
    }         
}  

Output

Print Pencil Shape Pattern in Java

User Input Character

Program

Filename: PencilExample2.java

import java.util.Scanner ;  
// create class PencilExample2 to print pencil pattern by using user input character   
public class PencilExample2{      
    // main() method start  
    public static void main(String[] args){  
        // declare variables   
        int rows ;  
        // create a Scanner class object to take input from the user  
        Scanner sc = new Scanner(System.in) ;  
        // take input from the user and store it into rows variable  
        System.out.print("Enter number of rows: ") ;  
        rows = sc.nextInt() ;        
        System.out.print("Enter any character : ") ;  
        char c = sc.next().charAt(0) ;  
        //call drawPencil() method of the Pencil class by creating an instance of the class  
        Pencil b = new Pencil() ;  
        b.drawPencil(rows, c) ;  
    }  
}  
// create a separate class for Pencil pattern  
class Pencil{          
    // create a user-defined method for drawing pattern  
    public void drawPencil(int rows, char c){         
        // declare variables  
        int t ;  
        // use for loop from -row to +row  
        for(int i = -rows; i <= rows; i++)   
        {  
            t = i ;  
            // for loop for columns  
            for(int j = 0; j <= rows; j++)  
            {  
                // check whether the value of t is less than j  
                if(t <= j)  
                    System.out.print(c+" ") ;  
                else  
                    System.out.print(" ") ;  
            }  
             System.out.println("") ;  
        }  
    }         
}  

Output 1

Print Pencil Shape Pattern in Java

Explanation

Let's examine how the for loop in the code above that prints the pencil pattern functions in each iteration.

Enter number of rows: 2

Enter any character: *

Iteration-I

  1. The first iteration will begin at i = -2 and continue until i <= 2.
  2. Let's say the t variable will be used to record the value of i, which is -2.
  3. From j = 0 to j <= row, the second for loop will loop through the data.
  4. The condition t <= j determines the star that appears on the screen. As a result, this condition will be met three times in the first iteration of the main for loop, printing three stars on the screen.

Iteration-II

  1. The first iteration will begin with i = -1 and continue until i <= 2.
  2. A variable, let's say t, will be used to record the value of i, which is -1.
  3. From j = 0 to j <= row, the second for loop will loop through the data.
  4. The three stars will appear on the screen if condition t <= j is met three times.

Iteration-III

  1. The first iteration will begin with i = 0 and run until  i< = 2.
  2. We'll save the value of i, which is 0, in a variable called t.
  3. From j = 0 to j <= row, the second for loop will loop through the data.
  4. If the condition t <= j is met three times, the screen will display three stars; if not, it will display a space.

Iteration-IV

  1. The first iteration will begin with i = 1 and run until i <= 2.
  2. A variable called t will be used to store the value of i, which is 1.
  3. From j = 0 to j <= row, the second for loop will loop through the data.
  4. If the condition t <= j is met twice, two stars will be printed on the screen; else, space will be printed.

Iteration-V

  1. The first iteration will begin at i = 2 and continue until i <= 2.
  2. A variable called t will be used to record the value of i, which is 2.
  3. From j = 0 to j <= row, the second for loop will loop through the data.
  4. One star will be printed on the screen if condition t <= j is satisfied; otherwise, space will be printed.

The variable i will be 3 after the fifth iteration, and the first for loop condition will be false. The pencil pattern will finally appear on the console.

Output 2

Print Pencil Shape Pattern in Java

Explanation

Let's examine how the for loop in the code above that prints the pencil pattern functions in each iteration.

Enter number of rows: 2

Enter any character: #

Iteration-I

  • The first iteration will begin at i = -2 and continue until i <= 2.
  • Let's say the t variable will be used to record the value of i, which is -2.
  • From j = 0 to j <= row, the second for loop will loop through the data.
  • The condition t <= j determines the hash that appears on the screen. As a result, this condition will be met three times in the first iteration of the main for loop, printing three hash on the screen.

Iteration-II

  • The first iteration will begin with i = -1 and continue until i <= 2.
  • A variable, let's say t, will be used to record the value of i, which is -1.
  • From j = 0 to j <= row, the second for loop will loop through the data.
  • The three hash will appear on the screen if condition t <= j is met three times.

Iteration-III

  • The first iteration will begin with i = 0 and run until  i< = 2.
  • We'll save the value of i, which is 0, in a variable called t.
  • From j = 0 to j <= row, the second for loop will loop through the data.
  • If the condition t <= j is met three times, the screen will display three hash; if not, it will display a space.

Iteration-IV

  • The first iteration will begin with i = 1 and run until i <= 2.
  • A variable called t will be used to store the value of i, which is 1.
  • From j = 0 to j <= row, the second for loop will loop through the data.
  • If the condition t <= j is met twice, two hashes will be printed on the screen; else, space will be printed.

Iteration-V

  • The first iteration will begin at i = 2 and continue until i <= 2.
  • A variable called t will be used to record the value of i, which is 2.
  • From j = 0 to j <= row, the second for loop will loop through the data.
  • One hash will be printed on the screen if condition t <= j is satisfied; otherwise, space will be printed.

The variable i will be 3 after the fifth iteration, and the first for loop condition will be false. The pencil pattern will finally appear on the console.

Pencil Pattern Program in Java

Filename: Main.java

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
    int r,c,t,row ;
    Scanner sc= new Scanner(System.in) ;
    System.out.print("Enter the Value for row : ") ;
    row=sc.nextInt() ;
    
    // this loop will execute from -row to +row
    for(r=-row; r<=row; r++) 
    {
        t=r ;
 
        for(c=0; c<=row; c++)
        {
            if(t<=c)
                System.out.print(c+" ") ;
            else
                System.out.print(" ") ;
        }
         System.out.println("") ;
    }
    }
}

Output

Print Pencil Shape Pattern in Java

Related Topics

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

How to resolve Illegal state exceptions in Java

What is IllegalStateException? When a method is called at the incorrect time, a runtime exception called an IllegalStateException is raised in Java. This exception is utilized to show that a method...

3 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Java Integer floatValue() method

The floatValue() method of Integer class returns a float value for this Integer after a widening primitive conversion. Syntax public float floatValue() Parameters NA Specified by This method is specified by floatValue in class Number Return Value This...

1 minute read.

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

How to check Date Null in Java?

In this section, we will be acknowledged about Date Null in Java. The date null in Java is an entity that is used when there is no specified value for...

3 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.