w3resource

C#: Check a given array of integers and return true if the array contains three increasing adjacent numbers


Check for Three Increasing Adjacent Numbers

Write a C# Sharp program to check a given array of integers and return true if the array contains three increasing adjacent numbers.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Check a given array of integers and return true if the array contains three increasing adjacent numbers.

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 results of the 'test' method with different integer arrays as arguments
            Console.WriteLine(test(new[] { 1, 2, 3, 5, 3, 7 })); // Testing the method with an array
            Console.WriteLine(test(new[] { 3, 7, 5, 5, 3, 7 })); // Testing the method with an array
            Console.WriteLine(test(new[] { 3, 7, 5, 5, 6, 7, 5 })); // Testing the method with an array   
        }               

        // Method to check if there are three consecutive elements in the array
        static bool test(int[] numbers)
        {
            for (int i = 0; i <= numbers.Length - 3; i++) // Loop through the array elements until the third-to-last element
            {
                // Checking if three consecutive elements form a sequence (incrementing by 1)
                if (numbers[i] == numbers[i + 1] - 1 && numbers[i] == numbers[i + 2] - 2)
                {
                    return true; // Return true if a sequence of three consecutive elements is found
                }
            }
            return false; // Return false if no sequence of three consecutive elements is found
        }    
    } 
}

Sample Output:

True
False
True

Flowchart:

C# Sharp: Flowchart: Check a given array of integers and return true if the array contains three increasing adjacent numbers.

Go to:


PREV : Check Equal Elements at Start and End.
NEXT : Shift Elements Left 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.