×

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 hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Producer Consumer Problem in Java Using Synchronized Block

The producer-consumer dilemma is a well-known instance of a multi-process synchronization issue in computing. Two processes—the producer and the consumer—are described in the issue, and they share a single, fixed-size...

4 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java InetAddress class

InetAddress class The InetAddress class refers to the IP address, both IPv4 and IPv6.An instance of an InetAddress consists of an IP address and possibly its corresponding hostname. It provides a method to get the...

9 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java List Implementations

ArrayList and LinkedList are the two implementations of List that are for general-purpose. You'll probably utilise an array list the majority of the time because it's quick and provides constant-time...

3 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.