How to count the number of times a letter appears in string.

Excuse me all. I am having a really hard time understanding how to tackle a homework problem I have.

The problem is:

"A DNA string is an ordered collection of the symbols ’A’, ’C’, ’G’, and
’T’. Given a DNA string s of length at most 1000 symbols, return four
integers (separated by spaces) counting the respective number of times that
the symbols ’A’, ’C’, ’G’, and ’T’ occur in s.

Sample Dataset:
AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTG

Sample Output:
17 9 14 18"

I have a basic understanding of what the question wants, but I have no idea how to actually get started. Can someone give me an idea on what to do? I'm so utterly lost right now. Thank you.

Depending on how you get the DNA and store it there could be multiple ways.

Say we have a string with 100 characters like this

std::string DNA = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTG";

Then we want to loop through the string and add one to the letter count

 
int a = 0 , g = 0 , c = 0 , t = 0;


1
2
3
4
5
6
7
for( int i = 0; i < SIZE; ++i )
{
    //switch of if/else if
   //then increment the letter by one
}

//output the results 


Thank you so much for your help! It definitely put me in the right direction and I was able to complete it today.

Here's the final code:
------------------------------------------------------


#include <iostream>
#include <string>

using namespace std;

int main()
{
int a = 0 , g = 0 , c = 0, t = 0, i = 0, invalid = 0;
string s;
cout << "Please input your DNA sequence: " << endl;
getline(cin, s);
for (i = 0; i < s.length() && i < 1000; ++i)
{
//using switch construct
switch (tolower(s[i]))
{
case 'a':
a=a+1;
break;
case 'g':
g=g+1;
break;
case 'c':
c=c+1;
break;
case 't':
t=t+1;
break;
default:
invalid=invalid+1 ;
break;
}

}

if (invalid > 0)
{
cout<< "invalid input. It contains characters other than a, A, g, G, c, C, t, T"<< endl;
cout << " or a space" << endl;
}

else
{
cout << "the count of each nucleotides (Adenine: A, Guanine: G, Cytosine: C, and Thymine: T) in the input is: " << endl ;
cout << "Adenine (A) = " << a << endl ;
cout << "Cytosine (C) = " << c << endl ;
cout << "Guanine (G)= " << g << endl ;
cout << "Thymine (T) = " << t << endl ;
}

return (0);
}
another thing to mention. a = a + 1 is equivilant to a += 1; ( += is the compound of left hand side value + right hand value then assign to left hand ).

You can also use ++ operator which increments a value by 1.


1
2
3
4
5
a = a + 1;
//==
a += 1;
/==
++a; //or a++; 
Topic archived. No new replies allowed.