Reputation: 109
I'm trying to solve this: http://codeforces.com/problemset/problem/888/A
I wrote the following code:
#include <stdio.h>
int main(void)
{
int a, i, q, count;
scanf("%d ", &q);
int ar[q];
for (i = 0; i < q; i++)
{
scanf("%d ", &ar[i]);
}
for (i = 0; i < q; i++)
{
if (i != q - 1 && i != 0)
{
if (((ar[i] < ar[i + 1]) && (ar[i] < ar[i - 1])))
{
count++;
}
else if (((ar[i] > ar[i + 1]) && (ar[i] > ar[i - 1])))
{
count++;
}
}
}
printf("%d", count);
return 0;
}
And when I run the program with the first test case, it prints random numbers. When I run it again, it prints DIFFERENT random numbers.
I looked up the solution: https://github.com/Waqar-107/Codeforces/blob/master/A-set/888A.Local%20Extrema.py
Isn't that code exactly what I wrote ? Why is my code printing strange things ? Thanks in advance.
Upvotes: 0
Views: 296
Reputation: 96
You should initialize the variable count
to zero:
#include <stdio.h>
int main(void)
{
int a, i, q, count=0;
scanf("%d ", &q);
int ar[q];
for (i = 0; i < q; i++)
{
scanf("%d ", &ar[i]);
}
for (i = 0; i < q; i++)
{
if (i != q - 1 && i != 0)
{
if (((ar[i] < ar[i + 1]) && (ar[i] < ar[i - 1])))
{
count++;
}
else if (((ar[i] > ar[i + 1]) && (ar[i] > ar[i - 1])))
{
count++;
}
}
}
printf("%d", count);
return 0;
}
Upvotes: 1