Wednesday, October 7, 2009

Shell Script To Print Pyramid-Using for 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
echo -e "\033[47m" #used for colourizing output
for ((row=1;row<=n;row++))
do
spaces=$((n-row))
stars=$((2*$row - 1))
for ((i=1;i<=spaces;i++))
do
echo -n ' '
done
for ((i=1;i<=stars;i++))
do
echo -e '\033[43m*\033[47m\c'
done
for ((i=1;i<=spaces;i++))
do
echo -n ' '
done
echo
done
echo -e "\033[0m"
unset n i spaces stars row
# Unset variables is a good programming practice

Output:
[root@localhost blog]# sh for_pyramid 22

6 comments: