Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - error after for() cicle

Tags:

c

for-loop

I've been coding in C to solve a problem in ROSALIND's website. The code is really simple, and because it's so simple, it's very hard to correct this error.(I guess) Here is my code:

    /* A string is simply an ordered collection of symbols selected from some alphabet and formed into a word; the length of a string is the number of symbols that it contains.

An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG."

Given: A DNA string s of length at most 1000 nt.

Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s. */

#include <stdio.h>

int main(){
    char nt;
    int nA, nC, nG, nT;
    for(int i = 0, nA = nC = nG = nT = 0; i < 1000; i++){
        nt = getchar();
        if(nt == 'A'){
            nA++;
        }else if(nt == 'C'){
            nC++;
        }else if(nt == 'G'){
            nG++;
        }else if(nt == 'T'){
            nT++;
        }else{
            break;
        }
    }
    printf(" %d %d %d %d", nA, nC, nG, nT);
}

And when I test this code:

AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC

It should give:

20 12 17 21

But my computer gives:

4200624 12 17 21

I've put printf() functions to find where the error is located. I've seen that in the moment right before getting out of the cicle nA = 20, but the moment right after it nA = 4200624 . What can I do?

like image 208
DMaxter Avatar asked Dec 15 '22 08:12

DMaxter


2 Answers

I believe this is due to the fact that you are redeclaring the variables in the for header, where you set the variable to 0. Since you declare nA right after i, you have created a new variable with the same name, but with different scope. This one is only visible in the for loop itself, but is destroyed after it ends. The other variables are properly initialised due to your chain of assignments. I.e. they are initialised, not redeclared. Initialising the variables in the same line as you have declared them, would solve the issue.

like image 114
Yannick Stoffers Avatar answered Dec 26 '22 05:12

Yannick Stoffers


Turn up your compiler warnings. You have two variables named "nA", one which is local to the loop, and one which is uninitialized and that you are printing as a result.

like image 38
William Pursell Avatar answered Dec 26 '22 04:12

William Pursell