How to make the output print the first position of every three identical numbers?

Advertisements

How to make the output print the first position of every three identical numbers? (in this case 4 {position number 3} and 7 {position number 8)?

int counter = new int();
int[] arr = {1,2,3,4,4,4,5,6,7,7,7};
         
for (int i = 0; i < arr.Length; i++)
{
  if (arr[i] == arr[i+1]) // it says "Index was outside the bounds of the array."
  {
    counter++;
    if (counter == 2)
    {
      Console.WriteLine(arr[i] + " "); 
    }
  }
}
Console.ReadKey();

>Solution :

You must iterate through you array and check for equality 3 numbers in a row

int[] arr = { 1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7 };

for (int i = 0; i < arr.Length - 2; i++)
{
    if (arr[i] == arr[i + 1] && arr[i] == arr[i + 2])
    {
        Console.WriteLine("Trio is at:" + i + " Value is" + arr[i]);
    }
}

Console.ReadKey();

Leave a ReplyCancel reply