I have to print the number of stars that increases on each line from the minimum number until it reaches the maximum number, and then decreases until it goes back to the minimum number. After printing out the lines of stars, it should also print the total number of stars printed.
I have tried using shell scripting and worked. But is there any other simplified and generic way to achieve this
echo "enter the mininum number "
read min
echo "enter the maximum number "
read max
for (( i=$min;i<=$max;i++))
do
for (( j=$max;j>=i;j-- ))
do
echo -n " "
done
for (( c=1;c<=i;c++ ))
do
echo -n " *"
sum=`expr $sum + 1`
done
echo ""
done
d_max=`expr $max - 1`
for (( i=$d_max;i>=$min;i--))
do
for (( j=i;j<=$d_max;j++ ))
do
if [ $j -eq $d_max ]
then
echo -n " "
fi
echo -n " "
done
for (( c=1;c<=i;c++ ))
do
echo -n " *"
sum=`expr $sum + 1`
done
echo ""
done
echo "Total No. : " $sum
Because the OP showed a diamond for every valid inputted value, AND, he thanked my post #8.
Also it calls dash so should work on just about any shell.
The code using various values, Linux Mint 19, default terminal calling 'dash'...
I was demonstrating how the original code we were asked to simplify in Post #1 works .
I believe this was indicated as doing what was required.
Here is a solution using dash. I make use of a function fill. fill's first argument is the total length of output required and the 2nd (optional) argument specifies the string to use (single space being the default).
As an example fill 3 gives 3 spaces, and fill 5 "AB" gives ABABA .
This function can be used to output a diamond in this fashion:
fill 3 ; fill 2 '* ' ; echo
fill 2 ; fill 4 '* ' ; echo
fill 1 ; fill 6 '* ' ; echo
fill 0 ; fill 8 '* ' ; echo
fill 1 ; fill 6 '* ' ; echo
fill 2 ; fill 4 '* ' ; echo
fill 3 ; fill 2 '* ' ; echo
And here is the full dash solution using this method:
#!/bin/dash
fill ()
{
# fill string to width of count from string chars
#
# usage:
# fill count [chars]
#
# if count is zero (or less) a blank string is output
# chars defaults to a space
#
local width=$(( ($1) ))
local str="${2:- }"
while [ $width -gt 0 ]
do
while [ ${#str} -gt $width ]
do
str=${str%?}
done
width=$((width-${#str}))
printf "%s" "$str"
done
}
printf "Enter the mininum number: "
read MIN
printf "Enter the maximum number: "
read MAX
STARS=0
N=$MIN
while [ $N -le $((MAX*2-MIN)) ]
do
A=$((N-MAX))
W=$(($MAX-${A#-}))
fill MAX-W ; fill W*2 '* ' ; echo
STARS=$((STARS+W))
N=$((N+1))
done
echo "Total stars: $STARS"