What is a nested loop?

0 like 0 dislike
asked May 12, 2018 in General by Tarunjaiswal (100 points)

A nested loop is a loop that runs within another loop. Put it in another sense, you have an inner loop that is inside an outer loop. In this scenario, the inner loop is performed a number of times as specified by the outer loop. For each turn on the outer loop, the inner loop is first performed.

commented Jan 21, 2020 by Matillect
Cialis In Canada  http://cialibuy.com - Cialis Kamagra Zoll  <a href=http://cialibuy.com>Buy Cialis</a> Generique Kamagra 25 Mg

1 Answer

0 like 0 dislike
answered May 21, 2018 by MayankSingh (33 points)

nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within either the inner or outer loop would interrupt this process.

# nested-loop.sh: Nested "for" loops.

outer=1             # Set outer loop counter.

# Beginning of outer loop.
for a in 1 2 3 4 5
  echo "Pass $outer in outer loop."
  echo "---------------------"
  inner=1           # Reset inner loop counter.

  # ===============================================
  # Beginning of inner loop.
  for b in 1 2 3 4 5
    echo "Pass $inner in inner loop."
    let "inner+=1"  # Increment inner loop counter.
  # End of inner loop.
  # ===============================================

  let "outer+=1"    # Increment outer loop counter. 
  echo              # Space between output blocks in pass of outer loop.
# End of outer loop.

exit 0
Make sure your Question & Answer should be appropriate and useful to the reader. Don't just copy and paste content from other sources.