O'Reilly logo

C# Primer Plus by Klaus Michelsen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Traversing an Entire Array with the foreach Statement

Instead of using the for loop to traverse an entire array, you can apply C#'s foreach statement as a convenient alternative. For example, to print every array element value of the array childbirths declared and defined as

uint [] childbirths =  { 1340, 3240, 1003, 4987, 3877} ;

you can write the following foreach statement:

foreach (uint temp in childbirths)
{
      Console.WriteLine(temp);
}

to provide the following output:

					1340
3240
1003
4987
3877

This deserves a closer look. The foreach statement consists of a header and a loop body (see Figure 10.4). The loop body can either be a single statement or a compound statement. The first two words inside the parentheses of the header must consist ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required