Link Search Menu Expand Document

ad


foreach loop

The foreach statement repeats statement(s) for each element in an array.

  • Write the following code :
using System;

namespace LearnCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = { "Jane", "Sue", "Lisa", "Mary" };
            foreach (string item in names)
            {
                if (item == "Mary")
                {
                    Console.WriteLine("Hey, Mary was found !");
                }
                else
                {
                    Console.WriteLine("Looking for Mary ...");
                }
            }
        }
    }
}
  • Run the application in the Console Window

Output in Console Window

Looking for Mary ...
Looking for Mary ...
Looking for Mary ...
Hey, Mary was found !

ad



Copyright © 2020 Ray Consulting Limited - Coding Skills.IO.