Number of numbers in a character array
I am trying to count the number of ones in a character array that represent a binary number with a recursive type program. However, it seems that my program is just counting the number of characters in the array. I don't know if I am just comparing wrong or not, but I cannot 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 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;
}
}
source to share
In the method determine()
:
if ( array[track] == '1');
remove the semicolon ;
. The semicolon makes the condition if
for the block to be executed empty
. Thus, count++
it will always execute whether the condition if
( true
) was met or not ( false
).
I run your code with ;
and get the output:
Number 1 is 7
And without ;
:
Number 1 is 3
source to share