Java Program to Print Pencil Character Pattern

Print Pencil Shape Character Pattern

In the previous article, we have discussed Java Program to print Back Slash Character Pattern

In this article we are going to see how to print the Pencil character  pattern.

Example:
When height is taken as 3
A B C D 
A B C D 
A B C D 
A B C D 
 B C D 
  C D 
   D

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Approach:

  • Enter total row and store it an integer variable say row.
  • Here height refers to -row to +row
  • Take first for loop to print all the rows.
  • Take inner loop to print the column values.

Java Code to Print Pencil Character Pattern

import java.util.Scanner;
public class Main
 {
    public static void main(String[] args){
    int r,c,h,row;
    // starting ASCII value taken 64
    int ascii=65;
    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++) 
    {
        h=r;
 
        for(c=0; c<=row; c++)
        {
            if(h<=c)
                System.out.print((char)(c+ascii)+" ");
            else
                System.out.print(" ");
        }
         System.out.println("");
    }
   }
}
Output:

Enter the Value for height : 3

A B C D 
A B C D 
A B C D 
A B C D 
 B C D 
  C D 
   D

C Code to Print Pencil Character Pattern

#include <stdio.h>
int main() {
    int r,c,h,row;
    int ascii=65;
    printf("Enter the height: ");
    scanf("%d",&row);
    for(r=-row; r<=row; r++) 
    {
        h=r;
 
        for(c=0; c<=row; c++)
        {
            if(h<=c)
                printf("%c ",(c+ascii));
            else
                printf(" ");
        }
         printf("\n");
    }
}
Output:

Enter the Value for height: 3

A B C D 
A B C D 
A B C D 
A B C D 
 B C D 
  C D 
   D

C++ Code to Print Pencil Character Pattern

#include <iostream>
using namespace std;
int main() {
    int r,c,h,row;
    // starting ASCII value taken 64
    int ascii=65;
    cout<<("Enter the Value for height: ");
    cin>>row;
    for(r=-row; r<=row; r++) 
    {
        h=r;
 
        for(c=0; c<=row; c++)
        {
            if(h<=c)
                cout<<(char)(c+ascii) << " ";
            else
                cout<<(" ");
        }
         cout<<("\n");
    }
}
Output:

Enter the Value for height: 3

A B C D 
A B C D 
A B C D 
A B C D 
 B C D 
  C D 
   D

Are you seeking professional help for coding in the Java programming language? The tutorial of Java Programming Examples for beginners and experts will strongly improve your coding skills then you can program for any logic in Java.

Related Java Character Pattern Programs: