Help me to understand

Fir DNA storage problem with even inputs why doesn’t the following code work plz explain some1…

include <bits/stdc++.h>
using namespace std;

int main() {
// your code goes here
int t,i,n;
string S;
cin>>t>>n>>S;

while(t--){
    for(i = 0;i < n;i = i+2){
        if(S[i] == '0' && S[i+1] == '0'){
            cout<<'A';
        }
        else if(S[i] == '0' && S[i+1] == '1'){
            cout<<'T';
        }
        else if(S[i] == '1' && S[i+1] == '0'){
            cout<<'C';
        }
        else{
            cout<<'G';
        }
    }
     cout<<endl;
}

return 0;

}
problem link:CodeChef: Practical coding for everyone

Hey, a couple of things.

First it would be better if you initialize the variables that are used in the loop within the loop itself. It helps in curbing unnecessary initializing issues.

Secondly, in your for loop, every time your increment by 2, so for an array of odd length say 3, i gets initialized to 0. Then in the next iteration it gets initialized to 2, and your loop tries to access i+1 , which is basically non- existing here ( as i+1 = 3, and an array of size would’ve index till 2 only.)

here is the corrected code. Hope it helps🐻

int main() {
// your code goes here
int t;

cin>>t;

while(t--){
    int n;
    string S;
    cin>>n;
    cin>>S;
    
    for(int i = 0;i < n-1;i = i+2){
        if(S[i] == '0' && S[i+1] == '0'){
            cout<<'A';
        }
        else if(S[i] == '0' && S[i+1] == '1'){
            cout<<'T';
        }
        else if(S[i] == '1' && S[i+1] == '0'){
            cout<<'C';
        }
        else{
            cout<<'G';
        }
    }
     cout<<endl;
}

return 0;
}
1 Like

thnx a lott bro…

1 Like