12 January 2014

Shell Script to print Pyramid of Numbers

9 comments


Q. How do I print pyramid of numbers in Bash


Ans.
how to print number pyramid in ubuntu

Before writing bash script lets understand how we going to print this pattern. We do it in two part, first we are going to print part 1 and then we print the part 2. As you can notice from above figure that, in 2nd part we are printing number in reverse order till 1.

#!/bin/bash

#Taking input
read -p "Enter Number:" number

#Outer loop for printing number of rows in pyramid
for((row=1;row<=number;row++))
do

    #Loop for printing required spaces
    for((spaces=row;spaces<=number;spaces++))
    do
        echo -ne " "
    done

    #Loop for printing 1st part
    for((j=1;j<=row;j++))
    do
        echo -ne "$j"
    done

    #Loop for printing 2nd part
    for((l=(row-1);l>=1;l--))
    do
        echo -ne "$l"
    done

    #echo for printing new line
    echo 
done
    

Output


how to print number pyramid in bash script

Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

9 comments:

  1. Replies
    1. same as
      *
      **
      ***
      ****
      for above pyramid we print "row" alphabet.. to get the pyramid asked by you should print the "2nd" alphabet and initiate it by "1".

      Delete
  2. printNum()
    {
    for((i=1;i<=n;i++))
    do
    for((k=1;k<=i;k++))
    do
    echo -ne "$k";
    done
    echo
    done
    }

    ReplyDelete
  3. How to print:
    0
    0 2
    0 2 4
    0 2 4 16
    0 2 4 16 256

    ReplyDelete
    Replies
    1. I have posted a relevent answer to your question. Correct me if I'm wrong. Happy to help :P

      Delete
    2. I have posted a relevent answer to your question. Correct me if I'm wrong. Happy to help :P

      Delete
  4. #!/bin/bash

    read -p "N? : " n

    for((i = 0; i < n; i++))
    do
    k=0
    key=0
    while((k < $((i+1))))
    do
    if((k == 0))
    then
    echo -e "$key \c"
    key=2
    k=$((k+1))
    else
    echo -e "$key \c"
    key=$(echo "$key^2" | bc)
    k=$((k+1))
    fi
    done

    echo " "
    done

    ReplyDelete
  5. #!/bin/bash

    read -p "N? : " n

    for((i = 0; i < n; i++))
    do
    k=0
    key=0
    while((k < $((i+1))))
    do
    if((k == 0))
    then
    echo -e "$key \c"
    key=2
    k=$((k+1))
    else
    echo -e "$key \c"
    key=$(echo "$key^2" | bc)
    k=$((k+1))
    fi
    done

    echo " "
    done

    ReplyDelete