Moh'd H Moh'd H - 2 months ago 8x
C Question

Code not assessing peaks correctly

i have a code that prints out the number of peaks and their given magnitudes. the input is in the form of a single line that contains random integers separated by white space. a peak is only defined to be so when it is directly preceded and followed by a smaller value.

0 4 18 18 26 40 40 29 25 2 0 //has one peak of magnitude 40.
20 10 20 /*has no peaks, because both 20's are either not
preceded or followed by a smaller number.*/

the code fails to behave correctly when the input data,
, begins with a declining set of numbers.
for example, the input:
9 8 7 6 5 4
returns a peak of "9", when it shouldn't return any magnitude.
another situation where it's behaving incorrectly is when we have the following input:
10 10 10 5 5 5 12 12 12 -1
. its returning a magnitude of "10", while again, it shouldn't return any magnitude because it doesn't fulfill the conditions of a peak .

the following is the code:

#include <stdio.h>
int main(void)

int a = 0;
int b = 0;
int c = 0;
int counter = 0;

scanf("%d", &c);
printf("Number Magnitude\n");

while (c >= 0){

if ((b > a) && (b > c)) { //to check if we have a peak
printf("%4d%11d\n", counter, b);
a = b;
b = c;
scanf("%d", &c);


else if ((a < b) && (b == c)) {
b = c;
scanf("%d", &c);
else {
a = b;
b = c;
scanf("%d", &c);


i prefer to keep the level of coding as minimum as possible, as i haven't done more than loops and if statements at this stage.


The issue is being caused because you initialize your boundary values to the minimum possible value. Any possible peak value will test positive when compared to that boundary value.

A small change fixes it, both boundary values should be set to a value that tests negative when compared to any possible peak value:

int a = INT_MAX;
int b = INT_MAX;

You will however to detect new lines and reset your values if you want to be able to do multiple lines of input, but I believe this is an existing problem