0

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?

rustyx
  • 80,671
  • 25
  • 200
  • 267

3 Answers3

0

You can initialize the array with a default value, e.g. 0:

char northl2[100] = { 0 };

then after you added your '1' chars go through in a loop and increment a counter variable for each '1' you find.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

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.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
0

The only way to keep the number of actual elements in an array that does not have a sentinel value is to define a variable that will store the number of actual values in the array.

Take into account that if this declaration

char northl2[100];

is a block scope declaration then the array is not initialized and has indeterminate values.

If you are storing values in a character array as a string (that is the array has sentinel value '\0')then you can just apply standard C function std::strlen.

You could define the array the following way

char northl2[100] = {};

initially initializing all elements of the array to zeroes.

In this case you could write

char northl2[100] = {};

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

//...

std::cout << "The number of added values to the array is " 
          << std::strlen( northl2 )
          << std::endl;

provided that values are added sequentially without gaps in the array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335