w3resource

C#: Find the pair of adjacent elements that has the highest product of an given array of integers


Max Product of Adjacent Integers

Write a C# program to find the pair of adjacent elements that has the highest product of an array of integers.

Sample Solution:

C# Sharp Code:

using System;

public class Example
{
    // Function to find the maximum product of adjacent elements in an array
    public static int adjacent_Elements_Product(int[] input_Array)
    {
        // Initialize the maximum product with the product of the first two elements in the array
        int max = input_Array[0] * input_Array[1];

        // Loop through the array to find the maximum product of adjacent elements
        for (int x = 1; x <= input_Array.Length - 2; x++)
        {
            // Update the max variable with the maximum of the current max and the product of the current and next elements
            max = Math.Max(max, input_Array[x] * input_Array[x + 1]);
        }

        // Return the maximum product of adjacent elements
        return max;
    }

    // Main method to test the adjacent_Elements_Product function
    public static void Main()
    {
        // Testing the adjacent_Elements_Product function with different input arrays
        Console.WriteLine(adjacent_Elements_Product(new int[] {1, -3, 4, -5, 1})); // Output: 20
        Console.WriteLine(adjacent_Elements_Product(new int[] {1 , 3, 4, 5, 2})); // Output: 20
        Console.WriteLine(adjacent_Elements_Product(new int[] {1 , 3, -4, 5, 2})); // Output: 15
        Console.WriteLine(adjacent_Elements_Product(new int[] {1 , 0, -4, 0, 2})); // Output: 0
    }
}

Sample Output:

-3
20
10
0

Flowchart:

Flowchart: C# Sharp Exercises - Find the pair of adjacent elements that has the highest product of an given array of integers

For more Practice: Solve these Related Problems:

  • Write a C# program to find the maximum product of any two adjacent elements that are both prime numbers.
  • Write a C# program to return the index pair of the adjacent integers that produce the highest product.
  • Write a C# program to return the second highest product of adjacent elements from an integer array.
  • Write a C# program to find the maximum product of any two elements, whether adjacent or not.

Go to:


PREV : Check Palindrome String.
NEXT : Complete Missing Numbers in Range.

C# Sharp Code Editor:



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.