Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

13

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading