Moh&#39;d H - 1 year ago 153
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.
examples:

``````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,
`c`
, 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
counter++;
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.

``````int a = INT_MAX;