aluin

BiggerThan2Neighbours

Jan 6th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. using System;
  2.  
  3. /*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).*/
  4.  
  5. class BiggerThan2Neighbours
  6. {
  7. static void Main()
  8. {
  9. //input
  10. Console.Write("Length of the array: ");
  11. int length = int.Parse(Console.ReadLine());
  12.  
  13. int[] array = new int[length];
  14. for (int i = 0; i < length; i++)
  15. {
  16. Console.Write("arr[{0}]: ", i);
  17. array[i] = int.Parse(Console.ReadLine());
  18. }
  19.  
  20. Console.Write("Position of the element to be compared to its two neighbours: ");
  21. int position = int.Parse(Console.ReadLine());
  22.  
  23. //print
  24. if (position == 0 || position == array.Length - 1)
  25. {
  26. FirstLastPosition(array, position);
  27. }
  28. else if (position < 0 || position > array.Length - 1)
  29. {
  30. Console.WriteLine("Invalid position!");
  31. return;
  32. }
  33. else
  34. {
  35. CompareIntegers(array, position);
  36. }
  37. }
  38.  
  39. private static void CompareIntegers(int[] array, int position)
  40. {
  41. if (array[position] > array[position + 1] && array[position] > array[position - 1])
  42. {
  43. Console.WriteLine("The element {0} at position {1} is bigger than its two neighbours", array[position], position);
  44. }
  45. else if (array[position] > array[position + 1])
  46. {
  47. Console.WriteLine("The element {0} at position {1} is bigger only than its right-hand neighbour", array[position], position);
  48. }
  49. else if (array[position] > array[position - 1])
  50. {
  51. Console.WriteLine("The element {0} at position {1} is bigger only than its left-hand neighbour", array[position], position);
  52. }
  53. else
  54. {
  55. Console.WriteLine("The element {0} at position {1} is NOT bigger than its two neighbours", array[position], position);
  56. }
  57. }
  58.  
  59. // if the element is at first or last position
  60. private static void FirstLastPosition(int[] array, int position)
  61. {
  62. if (position == 0 && (array[position] > array[position + 1]))
  63. {
  64. Console.WriteLine("The element {0} at position {1} is bigger than its only neighbour", array[position], position);
  65. }
  66. else if (position == array.Length - 1 && array[position] > array[array.Length - 2])
  67. {
  68. Console.WriteLine("The element {0} at position {1} is bigger than its only neighbour", array[position], position);
  69. }
  70. else
  71. {
  72. Console.WriteLine("The element {0} at position {1} is NOT bigger than its only neighbour", array[position], position);
  73. }
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment