Reputation: 3
I have been trying to understand the out of bound error for the following code but I'm unable to figure out. The original problem is https://codeforces.com/contest/148/problem/A . I don't know why I am stuck and can you tell me how I can avoid similar type of errors.
#include <iostream>
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
int k,l,m,n,d,count=0;
cin>>k>>l>>m>>n>>d;
int arr[d]={0};
for (int i = 0; i < d; ++i){
int k1=k*(i+1); k1--;
int l1=l*(i+1); l1--;
int m1=m*(i+1); m1--;
int n1=n*(i+1); n1--;
if(arr[k1]==0 && k1<d){
arr[k1]=1; count++;
}
if(arr[l1]==0 && l1<d){
arr[l1]=1; count++;
}
if(arr[m1]==0 && m1<d){
arr[m1]=1; count++;
}
if(arr[n1]==0 && n1<d){
arr[n1]=1; count++;
}
}
cout<<count;
return 0;
}
Upvotes: 0
Views: 62
Reputation: 11410
You need to check the bounds first, in:
if(arr[k1]==0 && k1<d)
with:
if(k1<d && arr[k1]==0)
The second condition will not be tested if the first one is false. But the counterpart is not true. The first condition will always be tested.
Upvotes: 1