Murshad Gill Murshad Gill - 3 months ago 9
C Question

Check how many items added in c array?

I have declared a c array of length 100. Now, I place char's into it like this:

char northl2[100];

northl2[0]='1';
northl2[1]='1';


How can I count the number of 1's my program placed into the array?

Answer

You could use a loop like this:

char northl2[100] = {0};

northl2[0]='1';
northl2[1]='1';
int count_one = 0;
for (int i = 0;i<100;++i)
{
    if (northl2[i] == '1')
    {
        ++count_one;
    }
}
std::cout << count_one;

This prints 2 in this case, because there are 2 1's. The code iterates through each element of the arrays, checks it for a value, and increments its count. The char northl2[100] = {0}; sets by-default each element to 0. If you need a different value, use a loop:

char northl2[100];
int main()
{
    int count_one = 0;
    for (int i = 0; i< 100;++i)
    {
         northl2[i] = 'C'; //Or whatever char other than '1'
    }
    northl2[0]='1';
    northl2[1]='1';
    for (int i = 0;i<100;++i)
    {
        if (northl2[i] == '1')
        {
            ++count_one;
        }
    }
}

Also, don't forget to assign the 1's after the loop assigns values to all of the elements, or else, they will be overwritten.