w3resource

C#: Count the number of two 5's are next to each other in an array of integers


Count 5's Next to Each Other

Write a C# Sharp program to count the number of two 5's next to each other in an array of integers. Count the situation where the second 5 is actually a 6.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Count the number of two 5's are next to each other in an array of integers.

Sample Solution:-

C# Sharp Code:

using System;
using System.Linq;

namespace exercises
{
    // Class declaration
    class Program
    {
        // Main method - entry point of the program
        static void Main(string[] args)
        {
            // Calling the 'test' method with different integer arrays
            Console.WriteLine(test(new[] { 5, 5, 2 }));         // Output: 1
            Console.WriteLine(test(new[] { 5, 5, 2, 5, 5 }));  // Output: 2
            Console.WriteLine(test(new[] { 5, 6, 2, 9 }));     // Output: 0
            Console.ReadLine(); // Keeping the console window open
        }

        // Method to count occurrences of specific number patterns in an integer array
        public static int test(int[] numbers)
        {
            var ctr = 0; // Counter to track occurrences
            for (var i = 0; i < numbers.Length - 1; i++) // Loop through the array till the second-to-last element
            {
                // Check for the pattern '5, 5' or '5, 6'
                if (numbers[i].Equals(5) && (numbers[i + 1].Equals(5) || numbers[i + 1].Equals(6)))
                {
                    ctr++; // Increment the counter if the pattern is found
                }
            }
            return ctr; // Return the count of occurrences
        }
    }
}

Sample Output:

1
2
1

Flowchart:

C# Sharp: Flowchart: Count the number of two 5's are next to each other in an array of integers.

For more Practice: Solve these Related Problems:

  • Write a C# program to count how many times the number 5 is followed by another 5 or a 6 at any position in the array.
  • Write a C# program to count consecutive identical numbers in an array including pairs like 5-5, 7-7, etc.
  • Write a C# program to count how many times the number 5 is followed by any even number in an array.
  • Write a C# program to count the number of 5-6 or 5-7 combinations in a given integer array.

Go to:


PREV : Characters at Index 0,1,4,5,....
NEXT : Check Triple in Array.

C# Sharp Code Editor:



Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.