Monday, July 9, 2012

Tip: traversing arrays in C-Shell

Below I have described two methods to traverse arrays in C-Shell - one uses the foreach loop and other while loop.
In both cases, the important thing to note is that array index in C-shell starts with '1' instead of '0' as in most programming languages, like C, C++, Java, Perl.


set a = (1 2 3 4)
set b = (5 6 7 8)
 

Method 1 - using the foreach loop, iterating on one array as the foreach index, and the accessing the other array inside the loop body using the index operator "[]"
set i = 1
foreach x ( `echo $a` )
  echo "x = $x b = $b[$i]"
  @ i = $i + 1
end
 

Output: 
x = 1 b = 5
x = 2 b = 6
x = 3 b = 7
x = 4 b = 8

Method 2 - using the while loop. Iterating on the size of array and accessing both the arrays inside the loop body using the index operator "[]"


set i = 1
while ($i <= 4)
  echo "a = $a[$i] b = $b[$i]"
  @ i = $i + 1
end
 

Output:
a = 1 b = 5
a = 2 b = 6
a = 3 b = 7
a = 4 b = 8