147k views
5 votes
Write a program to find a peak in an array of ints. Suppose the array is {-1, 0, 2, 5, 6, 8, 7}. The output should be "A peak is at array index 5 and the value is 8." This is because the value 8 is larger than its predecessor 6 and its successor 7 in the given array. Note that 8 occurs at index 5. (The array starts at index 0.) A number at index i in an array X is considered a peak if: X[i]>=X[i-1] and X[i]>=X[i+1]. If i is at the beginning of the array, then peak is if X[i]>=X[i+1]. If i is at end of array, then peak is if X[i]>=X[i-1].

User Lxe
by
5.1k points

1 Answer

3 votes

Answer:

Following are the code to this question:

#include<iostream>//declaring header file

using namespace std;

int main()//main method

{

int n= 6,j=0;//declaring integer variable

int X[n];//defining an array

for(j=0;j<=n;j++)//defining a loop for input value

cin>>X[j];//input value from the user

if(j==0) //defining if block that checks value at beginning

{

if(X[j]>=X[j+1])//defining if block to check to compare first and second value

{

cout<<"A peak is at array index "<<j<<" and the value is "<<X[j];//use print method to largest value with index number

}

}

else//defining else block

{

for(j=0;j<=n;j++)//defining for loop for compare other value

{

if(j==n-1) //use if block that checks next index

{

if(X[j]>=X[j-1])//use if block to compare value

cout<<"A peak is at array index "<<j<<" and the value is "<<X[j];//use print method to largest value with index number

}

else

{

if(X[j]>=X[j-1] && X[j]>=X[j+1])//comapre value

cout<<"A peak is at array index "<<j<<" and the value is "<<X[j];//use print method to largest value with index number

}

}

}

return 0;

}

Output:

please find the attached file.

Step-by-step explanation:

In the given code, inside the main method two integer variable "n and j", is declared, in the next step, an array "x"is defined which input the value from the user end.

  • In the next step, multiple if block is used, in the first if block it comapre the first and second value if it grater then it will print the value with its index number.
  • In the next if block, it comapre is next value and if it grater then it will print the value with its index number.
Write a program to find a peak in an array of ints. Suppose the array is {-1, 0, 2, 5, 6, 8, 7}. The-example-1
User Emmanuel BRUNET
by
4.8k points