Wednesday, October 7, 2009

Shell Script To Print Pyramid - Using while Loop


#!/bin/bash
# Usage: scriptname argument
# Here argument is height of pyramid
# Output would be pyramid pattern of stars
# 0 *
# 1 ***
# 2 *****
# 3 *******
# 4 *********
# 5 ***********
# 6 *************
# . ***************
# . *****************
# . *******************
# n-1 *********************
# ---\/--- | ---\/---
# n - 1 n - 1
#

clear
n=$1
row=1;
echo -e "\033[47m"
while [[ $row -le $n ]]
do
loop=1;
spaces=$((n-row))
stars=$((2*row - 1))

while [[ $loop -le $spaces ]]
do
echo -n ' '
let loop++
done
loop=1;
while [[ $loop -le $stars ]]
do
echo -e '\033[43m*\033[47m\c'
let loop++
done
loop=1;
while [[ $loop -le $spaces ]]
do
echo -n ' '
let loop++
done
echo
let row++
done
echo -e "\033[0m"
unset row loop spaces stars n
Output:
[root@localhost blog]# sh while_pyramid 22

3 comments:

  1. row="***********************************************************"
    row=$row$row$row
    base=${1:-20}
    n=$base
    r=1
    while [ $n -gt 0 ]
    do
    l=$(( $n + $base / 2 ))
    printf "%${l}s\033[43m%s\033[0m\n" "" "${row:0:$(( r++ * 2 - 1 ))}"
    n=$(( $n - 1 ))
    done

    ReplyDelete
  2. "I very much enjoyed this article.Nice article thanks for given this information. i hope it useful to many pepole.php jobs in hyderabad.
    "

    ReplyDelete