public void ElementSearch()
{
int[] eleArray = new int[5]{4,1,8,5,9}; // Assign values to array
int valSearch = 5; //Search for a value
int counter = 0; // Set a counter, if the value doesn''t exist in an array
for(int i=0; i<=4; i++) //Iterate to all elements in an array
{
if (eleArray[i] == valSearch)// Check each value is equal to value to search
{
Console.WriteLine("Value found and is in index " + i + " of an array");
}
else //if value not found, increment the counter
{
counter++;
if (counter == eleArray.Length) //counter reach arraylength, value notfound.
{
Console.WriteLine("Sorry! Value not found");
}
}
}
}
Output: Value found and is in index 3 of an array
No comments:
Post a Comment