Tuesday, May 24, 2011

The while statement

A while statement conditionally executes a statement zero or more times – as long as a boolean test is true.
using System;
class Test
{
    static int Find(int value, int[] arr) {
        int i = 0;
        while (arr[i] != value) {
            if (++i > arr.Length)
                throw new ArgumentException();
        }
        return i;   
    }
    static void Main() {
        Console.WriteLine(Find(3, new int[] {5, 4, 3, 2, 1}));
    }
}
uses a while statement to find the first occurrence of a value in an array.