can anyone tell me how to do the pyramid like in the attached file :-

i want it simple program with explanation how it works if you can.

PLEASE HELP.:icon_cry::icon_cry::icon_cry:

Recommended Answers

All 2 Replies

I would think about how to do this for a given line, then call it for each size in turn. For simplicity, lets do it without indenting correctly first:

function triline() {
  item=1                 # keep track of what to 'store' next
  linesofar=""           # keep track of what is already stored
  while [ "$item" -le "$1" ]; do # standard while loop starting from arg1
    linesofar="$linesofar $item" # store the next item
    item=$(( item + 1 ))         # advance the counter
  done
  item=$(( item - 1 ))           # the counter is too big. Reduce
  while [ "$item" -gt 1 ] ; do   # standard while loop down to 1
    item=$(( item - 1 ))         # pre-decrement
    linesofar="$linesofar $item" # store the next item
  done
  echo $linesofar        # echo the result
}

Now you have two remaining tasks:

  1. Figure out how to loop through the required number of lines
  2. Figure out how to indent

Hint for #1: Use arithmetic as on lines 6, 8 and 10
Hint for #2: linesofar doesn't have to start empty

rows=${1:-5}               ## Number of rows
max=$(( $rows * 4 + 1 ))   ## Length of longest row

## If too many rows (or line too long) for window reduce number of rows
while [ $max -gt $COLUMNS ] || [ $rows -gt $LINES ]
do
  rows=$(( $rows - 1 ))
  max=$(( $rows * 4 + 1 ))
done

## Build string of stars that is long enough for longest row
stars='*   *   *   *   *   *   *   *   *   *   *   '
while [ ${#stars} -lt $max ]
do
  stars=$stars$stars$stars
done

n=0
while [ $(( n += 1 )) -le $rows ]
do
  indent=$(( ($rows - $n) * 2 ))
  len=$(( $n * 4 ))
  printf " %${indent}s%$len.${len}s\n" '' "$stars"
done
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.