C#: Check whether the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere
Check Sequence 1, 2, 3 in Array
Write a C# Sharp program to check whether the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.
Visual Presentation:
Sample Solution:-
C# Sharp Code:
using System;
using System.Linq;
// Namespace declaration
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[] {1,1,2,3,1})); // Output: True
Console.WriteLine(test(new[] {1,1,2,4,1})); // Output: False
Console.WriteLine(test(new[] {1,1,2,1,2,3})); // Output: True
Console.ReadLine(); // Keeping the console window open
}
// Method to check if an array contains the sequence 1, 2, 3 in consecutive positions
public static bool test(int[] nums)
{
// Loop through the array elements except the last two
for (var i = 0; i < nums.Length-2; i++)
{
// Check if the current element and the next two elements form the sequence 1, 2, 3
if (nums[i] == 1 && nums[i + 1] == 2 && nums[i + 2] == 3)
return true; // Return true if the sequence is found
}
return false; // Return false if the sequence is not found
}
}
}
Sample Output:
True False True
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a C# Sharp program to check if one of the first 4 elements in an array of integers is equal to a given element.
Next: Write a C# Sharp program to comapre two given strings and return the number of the positions where they contain the same length 2 substring.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics