Can 'while' loop be used to iterate through all elements in an array?

QuestionsQuestions8 SkillsProDec, 20 2025
0139

Yes, absolutely! You can definitely use a while loop to iterate through an array, though it requires a bit more manual setup than a for loop.

To do this, you use an index variable (usually starting at 0) to access each element one by one.

Example Code

Here is how you would rewrite the for loop example using a while loop:

#!/bin/bash

NAMES=("Alice" "Bob" "Charlie" "David")
i=0  # Start at index 0

# ${#NAMES[@]} gives you the total number of elements in the array
while [ $i -lt ${#NAMES[@]} ]; do
  echo "Hello, ${NAMES[$i]}!"
  i=$((i + 1))  # Manually increment the index
done

Why would you do this?

While a for loop is usually cleaner for arrays, a while loop is useful if:

  1. Skipping elements: You want to skip certain indices based on a complex condition (e.g., i=$((i + 2))).
  2. Multiple Arrays: You want to iterate through two arrays of the same length simultaneously using the same index i.
  3. Dynamic changes: You need to check a condition other than just "reaching the end of the list" while you are iterating.

Comparison

  • for loop: Automatically handles picking up each item. It's concise and less prone to errors (like forgetting to increment the counter).
  • while loop: Requires you to manage the counter (i=0 and i=$((i + 1))) yourself. If you forget to increment i, you'll create an infinite loop!

So, while for is the "standard" way for arrays, while gives you more manual control if you need it.

0 Comments

no data
Be the first to share your comment!