C#: Count the number of two 5's are next to each other in an array of integers
C# Sharp Basic Algorithm: Exercise-38 with Solution
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:
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 Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to create a new string of the characters at indexes 0,1, 4,5, 8,9 ... from a given string.
Next: Write a C# Sharp program to check if a triple is presents in an array of integers or not. If a value appears three times in a row in an array it is called a triple.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/basic-algo/csharp-basic-algorithm-exercises-38.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics