Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*5. Write a method that checks if the element at given position in given array of integers is bigger than its two neighbors (when such exist).*/
- class BiggerThan2Neighbours
- {
- static void Main()
- {
- //input
- Console.Write("Length of the array: ");
- int length = int.Parse(Console.ReadLine());
- int[] array = new int[length];
- for (int i = 0; i < length; i++)
- {
- Console.Write("arr[{0}]: ", i);
- array[i] = int.Parse(Console.ReadLine());
- }
- Console.Write("Position of the element to be compared to its two neighbours: ");
- int position = int.Parse(Console.ReadLine());
- //print
- if (position == 0 || position == array.Length - 1)
- {
- FirstLastPosition(array, position);
- }
- else if (position < 0 || position > array.Length - 1)
- {
- Console.WriteLine("Invalid position!");
- return;
- }
- else
- {
- CompareIntegers(array, position);
- }
- }
- private static void CompareIntegers(int[] array, int position)
- {
- if (array[position] > array[position + 1] && array[position] > array[position - 1])
- {
- Console.WriteLine("The element {0} at position {1} is bigger than its two neighbours", array[position], position);
- }
- else if (array[position] > array[position + 1])
- {
- Console.WriteLine("The element {0} at position {1} is bigger only than its right-hand neighbour", array[position], position);
- }
- else if (array[position] > array[position - 1])
- {
- Console.WriteLine("The element {0} at position {1} is bigger only than its left-hand neighbour", array[position], position);
- }
- else
- {
- Console.WriteLine("The element {0} at position {1} is NOT bigger than its two neighbours", array[position], position);
- }
- }
- // if the element is at first or last position
- private static void FirstLastPosition(int[] array, int position)
- {
- if (position == 0 && (array[position] > array[position + 1]))
- {
- Console.WriteLine("The element {0} at position {1} is bigger than its only neighbour", array[position], position);
- }
- else if (position == array.Length - 1 && array[position] > array[array.Length - 2])
- {
- Console.WriteLine("The element {0} at position {1} is bigger than its only neighbour", array[position], position);
- }
- else
- {
- Console.WriteLine("The element {0} at position {1} is NOT bigger than its only neighbour", array[position], position);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment