Doubt regarding Run Error

I have solved two questions in bitmasking i.e unique number2 and playing with bits. I use Xcode to code.
According to me I have programmed them correctly, but I am getting run error while submitting the code.
I am not able to figure out my error.

Code for unique number2
#include
using namespace std;

int setbits(int m,int n){
int temp=m;int i=0;int ans=0; int a[10];
while(m<=n){
a[i]=m;
m++;
i++;
}
m=temp;
for(i=0;i<=(n-m);i++){
while(a[i]>0){
if((a[i]&1)==1){
ans++;
}
a[i]=a[i]>>1;
}
}
return ans;
}

int main(){
int a[10];int m,n;int i=0;int q;
cin>>q;
for(i=0;i<q;i++){
cin>>m;
cin>>n;
a[i]=setbits(m,n);
}
for(i=0;i<q;i++){
cout<<a[i]<<endl;
}

return 0;

}

code for playing with bits:
#include
using namespace std;

int setbits(int m,int n){
int temp=m;int i=0;int ans=0; int a[10];
while(m<=n){
a[i]=m;
m++;
i++;
}
m=temp;
for(i=0;i<=(n-m);i++){
while(a[i]>0){
if((a[i]&1)==1){
ans++;
}
a[i]=a[i]>>1;
}
}
return ans;
}

int main(){
int a[10];int m,n;int i=0;int q;
cin>>q;
for(i=0;i<q;i++){
cin>>m;
cin>>n;
a[i]=setbits(m,n);
}
for(i=0;i<q;i++){
cout<<a[i]<<endl;
}

return 0;

}

@Nikhil-Singh-3031841156877674
You are taking the array of fixed size 10, but it actually depends upon the value of q.
so take it as int a[q]; but first take the input for q.

1 Like

@Nikhil-Singh-3031841156877674
the runtime error is because you have take some size for array but in actual it is trying to access some index which is more than its size. So correct that thing in your code and please from next share the ide link of your code, that is more readable.

1 Like