Reputation: 11
So I've written this to print "Yes when the code is in ascending order and "No" when it is not. But if I start with equal values in the beginning, the program prints an incorrect result. I don't understand why the if statement runs even if the condition isn't met.
#include <iostream>
using namespace std;
int main()
{
int N, i;
scanf("%d", &N);
int arr[N];
for(i = 1; i <= N; i++)
{
scanf("%d", &arr[i - 1]);
}
for(i = 1; i <= N; i++)
{
if(arr[i - 1] > arr[i])
{
printf("No");
return 0;
}
}
printf("Yes");
return 0;
}
Upvotes: 1
Views: 69
Reputation: 16876
You have an off by one error where you skip the first element of your array and go one past the last element. If your array has N
elements, it goes from array[0]
to array[N-1]
. Change this here:
for(i = 1; i <= N; i++){
To this here:
for(i = 0; i < N; i++){
The second for(i = 1; i <= N; i++)
where you do the check can start at 1
since you look at arr[i - 1]
within, but it should be i < N
instead of i <= N
nevertheless.
Furthermore, int arr[N];
doesn't work in C++ (some compilers will tolerate it, but not all of them). Try std::vector<int> arr(N);
instead.
Upvotes: 1