Array.IndexOf
Learn to find an element's index with Array.IndexOf.
Array.IndexOf
Array.IndexOf searches an array for an element and returns the first index it finds. If the element is not present, it returns -1. The search goes from the start to the end.
For example, on the array int[] nums = { 10, 20, 30 };, the call Array.IndexOf(nums, 20) returns 1 because 20 sits at the second position (indices start at 0).
Equality and LastIndexOf
Array.IndexOf starts searching from the front; if the same element appears more than once, it returns the first match. To search from the end, use Array.LastIndexOf.
The comparison uses the == operator; elements must be equal by type. Case sensitivity applies to strings: Array.IndexOf(names, "ayse") will not match "Ayşe".
Exercise Search in a city array
On the given string[] cities = { "İzmir", "Ankara", "Bursa" }; array, find the index of "Ankara" with Array.IndexOf(cities, "Ankara") and print it with Console.WriteLine.
Show example solution
Find the index with int idx = Array.IndexOf(cities, "Ankara");, then print with Console.WriteLine(idx);.
Example solution:
using System;
class Program
{
static void Main()
{
string[] cities = { "İzmir", "Ankara", "Bursa" };
// Find the index of Ankara and print it
int idx = Array.IndexOf(cities, "Ankara");
Console.WriteLine(idx);
}
}
Test yourself
-
Match each expression to its meaning
- Array.IndexOf(nums, 5)
- Index of 5
- -1
- Not found
- nums[0]
- First element
- Array.Sort(nums)
- Sorts
-
IndexOf call
int[] nums = { 10, 20, 30 }; int idx = ____; Console.WriteLine(idx);Show answer
int[] nums = { 10, 20, 30 }; int idx = Array.IndexOf(nums, 20); Console.WriteLine(idx); -
What does IndexOf print for a missing element?
int[] nums = { 10, 20, 30 }; Console.WriteLine(Array.IndexOf(nums, 25));- 0
- -1
- 25
- 3
Show answer
-1 — Correct. 25 is not in the array, so IndexOf returns -1.