Hi everyone. I am trying to write a simple function that counts the number of times a number appears in a given string. The function keep returning a very large negative number. Am I perhaps making a mistake with where I am declaring variables?
Code:
- #include <stdio.h>
- #include <string.h>
- char line[100];
- int count(int number, char array[], int length);
- int search_num;
- int array_length;
- int main()
- {
- printf("Enter a series of numbers: ");
- fgets(line, sizeof(line), stdin);
- printf("Enter a number to check occurence of: ");
- scanf("%d", &search_num);
- array_length = strlen(line);
- printf("The number %d appeared %d times in this array\n",
- search_num, count(search_num, line, array_length));
- return 0;
- }
- int count(int number, char array[], int length)
- {
- int i;
- int number_count;
- for (i = 0; i < length; i++)
- {
- if (array[i] == number)
- number_count++;
- else
- continue;
- }
- return (number_count);
- }