The solution is executed with error 'out of bounds' on the line 7
I have received this bound error though the sample input and output match. I tried several ways to solve this error, but I couldn't. Please help me to overcome this problem. And also please, explain why what is the main reason for this error. My Code:
#include <iostream>
using namespace std;
int main(){
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
string s;
cin >> s;
int sum = 0;
for(int i =0; i<s.size(); i++){
if(s[i]=='1'){
sum=sum+a[1];
}
else if(s[i]=='2'){
sum+=a[2];
}
else if(s[i]=='3'){
sum+=a[3];
}
else if(s[i]=='4'){
sum+=a[4];
}
}
cout << sum << endl;
}
Sample input:
1 2 3 4
123214
Output:
13
First of all, this is not correct
int a[4];
for(int i=1; i<=4; i++){
cin >> a[i];
}
arrays in C++ are indexed from 0, so it should be if you want to have a[1] = 1
int a[5];
for(int i = 0; i < 5; i++){
cin >> a[i];
}
Side note. You dont need the "look-up array". To sum numbers, you can just do:
sum += (s[i] - '0');
Array indexes start at 0
so a[4]
is out of bounds in your case.\
Since we're here I recommend to not use C arrays. Use std::array
or std::vector
instead.
Also it's better to use the range for.