C#: Using foreach to print out array elements

This entry is part 37 of 71 in the series C#

For array, there is an easy method to print out the array elements.

C# also provides the foreach statement. It provides a simple way to print out the elements of an array.

For this example, the foreach statement will run through the str array, put the elements into iStr and print out each element it encounters.

using System;

namespace ArrayDisplay
{
    class Program
    {
        static void Main()
        {
            string[] str = { "The", "End", "Of", "The", "Innocence" };

            foreach (string iStr in str)
            {
                Console.Write("{0} ", iStr);
            }
            Console.ReadLine();
        }
    }
}

The output from running the above code will be The End Of The Innocence.

Series Navigation<< C#: Using for loop to find array total
C#: Converting foreach program into OOP style >>

Leave a comment

Leave a Reply