# Thread: Counting how many chars are in a string...

1. ## Counting how many chars are in a string...

Alright, so, I was kind of messing around and I noticed that this:
Code:
```#include <iostream>
#include <cstring>

using namespace std;

int main()
{
char a = 'x';
char b[10] = "xxaxxaxa";
int matchcount = 0;
int len = strlen(b);

cout<<len<<endl;

for (int c = 0; c == len; c++)
{
if (a == b[c]) matchcount++;
}

cout<<matchcount;
cin.get();

return 0;
}```
Doesn't work...

matchcount returns 0 no matter what. Could somebody please enlighten me as to why it's not working?

2. think of for loops like a while loop, the condition needs to be true..

so while c < len do..

you had while c = len do.

Code:
```for (int c = 0; c < len; c++) {
// dostuff
}```
I've just started learning c++, after years of other languages, so please correct me someone if i'm wrong... also a word of advice..

to test anything I always declare a variable
Code:
` int test = 0;`
at the top of the page, and put cout << test++; everywhere to see where my logic stalls..

Thanks

3. Code:
`for (int c = 0; c == len; c++)`
You set c to 0, first. Your condition then says "if c is equal to len" but it since it is not equal, the condition is not verified and the for loop isn't executed. Thus, matchcount isn't incremented.

4. Wolves, think this: "while this is true, loop and increment, if it's not don't."

For (int c=0; c == x; ++c) // while (c==x) loop & increment c, else don't
// c != x at this point, no loop

Intended method:
For (int c=0; c < x; ++c) // while (c < x) loop & increment c, else don't
// c < x at this point, loop

or <= if you want c to tend to x, instead of x-1.

I see you said c==x which makes me believe you're trying to count up to 10 (the array size). Keep in mind that if you set an array of [n=]10 values, you do NOT need to loop to the number 10, you only have to go through 10 values, which is 0->9, we always start at 0, so all loops which involve arrays should be told to tend to n-1. You could say that the loop starts at 1 and go through 10, but then you'll read outside of the array bounds (array[9] is '10th' value), which if you insist on this case then you should do something like;

For (int c=1; c<10; ++c)
array[c-1];

I hope this example more clearly illustrates the issue and reasoning.

5. Schwoops, that's what I get for not using logic. Thanks all.