w3resource

C#: Check whether one of the first 4 elements in an array of integers is equal to a given element


Element in First 4 Positions of Array

Write a C# Sharp program to check whether one of the first 4 elements in an array of integers is equal to a given element.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Check if one of the first 4 elements in an array of integers is equal to a given element.

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 arrays and integer inputs
            Console.WriteLine(test(new[] {1,2,9,3}, 3));    // Output: True
            Console.WriteLine(test(new[] {1,2,3,4,5,6}, 2));// Output: True
            Console.WriteLine(test(new[] {1,2,2,3}, 9));   // Output: False
            Console.ReadLine(); // Keeping the console window open
        }   

        // Method to check if an integer array contains a specific integer 'n' in the first 4 elements
        public static bool test(int[] numbers, int n)
        {
            // Using a ternary operator to check if the length of 'numbers' is less than 4
            // If the length of 'numbers' is less than 4, use 'Contains' to check if 'n' is present in 'numbers'
            // Otherwise, use 'Take(4)' to consider only the first 4 elements of 'numbers' and check if 'n' is present
            return numbers.Length < 4 ? numbers.Contains(n) : numbers.Take(4).Contains(n);
        }
    }
}

Sample Output:

True
True
False

Flowchart:

C# Sharp: Flowchart: Check if one of the first 4 elements in an array of integers is equal to a given element.

For more Practice: Solve these Related Problems:

  • Write a C# program to verify whether a specified number occurs exactly once within the first 4 elements of an array.
  • Write a C# program to check if a given number is the maximum among the first 4 elements of an array.
  • Write a C# program to find if a specified number appears in the first 4 or the last 4 elements of an array.
  • Write a C# program to return true if the target value is in the first 4 elements and appears again later in the array.

Go to:


PREV : Check if Element Present in Array.
NEXT : Check Sequence 1, 2, 3 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.