C#: Check whether an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both
C# Sharp Basic Algorithm: Exercise-119 with Solution
Write a C# Sharp program to check whether an array of integers contains a 3 next to a 3 or a 5 next to a 5 or both.
Visual Presentation:
Sample Solution:
C# Sharp Code:
using System; // Importing the System namespace
namespace exercises // Defining a namespace called 'exercises'
{
class Program // Defining a class named 'Program'
{
static void Main(string[] args) // The entry point of the program
{
// Outputting the result of the 'test' method with different integer arrays as arguments
Console.WriteLine(test(new[] { 5, 5, 5, 5, 5 })); // Testing the method with an array containing all 5s
Console.WriteLine(test(new[] { 1, 2, 3, 4 })); // Testing the method with an array containing consecutive numbers
Console.WriteLine(test(new[] { 3, 3, 5, 5, 5, 5 })); // Testing the method with an array containing both consecutive 3s and 5s
Console.WriteLine(test(new[] { 1, 5, 5, 7, 8, 10 })); // Testing the method with an array containing 5s, but not consecutive
}
// Method to check if an array contains either consecutive 3s or consecutive 5s
static bool test(int[] numbers)
{
for (int i = 0; i < numbers.Length - 1; i++) // Loop through the array except for the last element
{
// Check if two consecutive elements are both 3s or both 5s
if ((numbers[i] == 3 && numbers[i + 1] == 3) || (numbers[i] == 5 && numbers[i + 1] == 5))
return true; // Return true if consecutive 3s or 5s are found
}
return false; // Return false if no consecutive 3s or 5s are found in the array
}
}
}
Sample Output:
True False True True
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to check whether a given array of integers contains no 3 or a 5.
Next: Write a C# Sharp program to check a given array of integers and return true if the given array contains two 5's next to each other, or two 5 separated by one element.
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://w3resource.com/csharp-exercises/basic-algo/csharp-basic-algorithm-exercises-119.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics