0

im a beginner, And i want to writing a script ('for' loop) -

  • Requests a number
  • Multiply the number by 2 and start a raw of asterisks And presents as here: (for example the number is 4)
********
 ******
  ****
   **
  ****
 ******
********
4
  • Please clarify further. Nov 20 '20 at 15:54
  • I'm trying to learn and do not understand how to do it at all.
    – MKLLKM
    Nov 20 '20 at 16:19
  • Does your assignment specify which shell to use?
    – spuck
    Nov 20 '20 at 16:21
  • Hi, in ubunto and for or while loops
    – MKLLKM
    Nov 20 '20 at 16:24
1
#!/bin/bash

read -p 'Number please: ' n

{
        for (( i=0; i<n-1; ++i )); do
                printf '%*.*d\n' "$(( 2*n-i ))" "$(( 2*(n-i) ))" 0
        done

        for (( i=n-1; i>=0; --i )); do
                printf '%*.*d\n' "$(( 2*n-i ))" "$(( 2*(n-i) ))" 0
        done
} | tr 0 '*'

The above script reads a number from the user into the variable n. It then creates the shape in two arithmetic for loops.

The first loop creates the top half of the shape, while the second loop creates the middle ** and the lower half of the shape.

The printf statement in each loop is identical, and only the value of i, the loop variable, changes.

The printf format used here, %*.*d, means "allocate space according to the first argument, to print a zero-filled integer with the width of the second argument". The actual integer to print is 0 (the third argument). The 1st and 2nd arguments given to printf causes it to print triangular shapes of 0 as i changes.

The 0 characters are then changed into * characters using tr.

Testing:

$ bash script.sh
Number please: 10
********************
 ******************
  ****************
   **************
    ************
     **********
      ********
       ******
        ****
         **
        ****
       ******
      ********
     **********
    ************
   **************
  ****************
 ******************
********************

See also man printf.

3
  • you can save the second for-loop by storing the first loop result into a temp variable then first print itself next print taced version printf '%s\n' "$tmp"; printf '%s\n' "$tmp"|tac Nov 20 '20 at 16:46
  • @αғsнιη Ah, yes, if I had tac on my non-Linux system... :-) But still, good call. I might investigate it later.
    – Kusalananda
    Nov 20 '20 at 16:47
  • 2
    then you can have tail -r unix.stackexchange.com/a/114043/72456 Nov 20 '20 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.