Java Program to Print Pencil Shape Number Pattern

Program to Print Pencil Shape Number Pattern

In the previous article, we have discussed Java Program to Print Asterisk Number Pattern

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

Example :

When number of  rows : 5

0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
 1 2 3 4 5 
  2 3 4 5 
   3 4 5 
    4 5 
     5

Access the Simple Java program for Interview examples with output from our page and impress your interviewer panel with your coding skills.

Approach:

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

Java Code to Print Pencil Shape Number Pattern

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

Enter the Value for row : 5

0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
 1 2 3 4 5 
  2 3 4 5 
   3 4 5 
    4 5 
     5

C Code to Print Pencil Shape Number Pattern

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

Enter the Value for row : 5

0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
 1 2 3 4 5 
  2 3 4 5 
   3 4 5 
    4 5 
     5

C++ Code to Print Pencil Shape Number Pattern

#include <iostream>
using namespace std;
int main() {
    int r,c,h,row;
    cout<<("Enter the Value for h: ");
    cin>>row;
    for(r=-row; r<=row; r++) 
    {
        h=r;
 
        for(c=0; c<=row; c++)
        {
            if(h<=c)
                cout<< c << " ";
            else
                cout<<(" ");
        }
         cout<<("\n");
    }
}
Output:

Enter the Value for row : 5

0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
 1 2 3 4 5 
  2 3 4 5 
   3 4 5 
    4 5 
     5

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 Number Pattern Programs: