Loops

Assignment 8

  1. Write a script called loop1 that will loop through the arguments and display each preceeded by a number starting at one and increments each time. Use the $@ variable. For example:
    $ loop1 dog cat mouse
    1: dog
    2: cat
    3: mouse
    

    Solution:

    $int=1
    for val in "$@"
    do
       echo "$int: $val"
       int=$(($int+1))
    done 
    
  2. Repeat question 1 using the automatic arguments feature of the for loop. Call this script loop2.

    Solution:

    $int=1
    for val
    do
       echo "$int: $val"
       int=$(($int+1))
    done 
    
  3. Write a script called loop3 that will start with 1 and multiply it by 2 until the value is greater than 1000. Use a while loop.

    Solution:

    num=1
    while [ "$num" -lt 1000 ]
    do
       echo "$num"
       $num=$(($num*2))
    done
    
  4. Repeat question 3 using an until loop. Call this script loop4.

    Solution:

    num=1
    until [ "$num" -gt 1000 ]
    do
       echo "$num"
       $num=$(($num*2))
    done