Slasher - 1 year ago 105

C# Question

How do you **retrieve the last repetition** index of element in array in C#?

For example you have:

`int[] array = { 3, 5, 7, 8, 3, 4, 3 , 9 };`

And you are searching for

element

3 where index of last repetition is 6.

This is what i have for finding first repetition:

`public static int search(int lem, int[] a)`

{

int j = 0;

for (int i = 0; i < a.Length; i++)

{

if (lem == a[i])

{

j = i;

return j;

}

}

return -1;

}

PS: I can't use any functions or methods. I'm allowed to use only arrays.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Try to search from behind. If you search from the first element of the array, you'll definitely need to search until the end of the array. If you search from behind, you can return the value directly once you find it.

```
public static int search(int lem, int[] a)
{
for (int i = a.Length - 1; i >= 0; i--)
{
if (lem == a[i])
{
return i;
}
}
return -1;
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**