Count number of ones in a array of characters

1.2k views Asked by At

I am trying to count the number of ones in an array of characters that represent a binary number with a recursive type program. However, it seems as if my program is just counting the number of characters in the array. I do not know if I am just comparing wrong or not but I can't seem to find the problem

#include <stdio.h>
# include <stdlib.h>
#include <string.h>
#define SIZE 20

int determine (char array[SIZE], int count, int track );

int main()
{ 
int answer = 0; 
char input[SIZE]={"1001001"};
int count = 0;
int track = 0;

answer = determine(input, count, track);

 printf("The number of 1's is %d ", answer);

system("PAUSE");
return 0;
 }

 int determine(char array[], int count, int track)
{   

 if (array[track] != '\0')
 {
    if ( array[track] == '1');
    {
         count++;
    }
    return determine(array, count, track = track+1);    
 }
 else 
 {
      return count;
 }
}
3

There are 3 answers

0
Gopi On BEST ANSWER
if ( array[track] == '1');

should be

if ( array[track] == '1')

remove the ;

If you have the ; then irrespective of the condition evaluation result (TRUE or FALSE) count++ will get executed

0
mazhar islam On

In method determine():

if ( array[track] == '1');

remove the semicolon ;. The semicolon makes the if condition to execute an empty block. So the count++ will always execute whether the if condition succeeded(true) or not(false).

I run your code with ; and get the output:

The number of 1's is 7

And without ; :

The number of 1's is 3

0
Bryan Glauser On

Have you tried a simple countif function?

=sum if (range="1")