Issue with loop for counting certain characters in a string

Hi, I'm a beginner programmer and I'm trying to create a loop that counts the number of C's and G's in a string. The program seems to return only around half the actual C's/G's. I think the issue might be a looping problem... not too sure. Can anyone help?

Here is a loop and the declared variables. The code compiles without error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string seq; int numc; int numg;
cin >> seq;

for (int i=0; i<(seq.length() - 1); i++)
{
	if (seq[i]=='c' || seq[i]=='C')
		{
			numc++;
			i++;
		}
	else if (seq[i]=='g' || seq[i]=='G') 
		{
			numg++;
			i++;
		}
	else i++;
}
1) You forgot to initialize variables numc and numg with zero.
2) the condition in the loop should look

for ( string::size_type i = 0; i < seq.length(); i++ )

3) You should not change control variable i within the loop body because it is changed in the control statement of the loop. As the result the else statement shall be removed together with all statements i++.
Ah! I totally forgot about the control variable i changing within the body of the loop. I used seq.length()-1 because I didn't want the null terminator to come up and create issues. But it doesn't matter. That's what late night coding does to you. With the amended code, it functions as wanted. Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string seq; int numc=0; int numg=0;
cin >> seq;

for (int i=0; i<seq.length(); i++)
{
	if (seq[i]=='c' || seq[i]=='C')
		{
			numc++;
		}
	if (seq[i]=='g' || seq[i]=='G') 
		{
			numg++;
		}
}
Last edited on
Member function length returns the number of actual characters stored in the string. Also it seems you forgot to place if and else-if in your code.
Topic archived. No new replies allowed.