Advertisement
tvarbanov

CSharp2-03-06

Jan 4th, 2014
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.23 KB | None | 0 0
  1. using System;
  2.  
  3. class IndexOfNumBiggerThanneighbours
  4. {
  5.     //Write a method that returns the index of the first element in array that is bigger than its neighbors, or -1, if there’s no such element.
  6.  
  7.     static int CheckNeighbors(int[] array)
  8.     {
  9.         int returnIndex = -1; //if there is no number in the criteria returns -1
  10.         for (int i = 1; i < array.Length - 1; i++)
  11.         {
  12.             if (array[i] > array[i + 1] && array[i] > array[i - 1]) //Checks the two neighbors
  13.             {
  14.                 returnIndex = i;
  15.                 return returnIndex;
  16.             }
  17.         }
  18.         return returnIndex;
  19.     }
  20.  
  21.     static void Main()
  22.     {
  23.         //Predefined array for test
  24.         int[] arrayOfNums = { 1, 5, 4, 9, 5, 3, 1, 8, 6, 4, 6, 9, 2, 8, 3, 4, 9 };
  25.         int result = CheckNeighbors(arrayOfNums); //Get the index
  26.         Console.WriteLine("The array : " + string.Join(", ", arrayOfNums));
  27.         if (result == -1)
  28.         {
  29.             Console.WriteLine("There is no number that fits the criteria of the program!");
  30.         }
  31.         else
  32.         {
  33.             Console.WriteLine("Number {0} at position {1} is bigger than his two neighbours!",arrayOfNums[result],result);
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement