Home > front end >  Why does my letter counter display 0 when put in a function
Why does my letter counter display 0 when put in a function

Time:10-05

I'm very new to C and trying to create a counter for how many times the letter "a" appears in a string. I get it working by putting it directly into main, however when I put it into a function, my printf outputs 0.

#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 50

void letter_counter(char input[STRING_LENGTH], int count, char letter ) {
    int i;
    for (i = 0; i < strlen(input); i  ){
    if (input[i] == letter) {
        count  ;
}
}
}


int main() {

    int a1 = 0;
    char a = 'a';

    printf("Please write a word\n");

    char input[STRING_LENGTH] = {0};
    fgets(input,STRING_LENGTH,stdin);
    input[strlen(input) - 1] = 0;

    letter_counter(input, a1, a);
    printf("%i\n", a1);




}

CodePudding user response:

You are not returning the value of what you have counted. It looks like you think that a1 is going to contain the total, but it's not.

Your letter_counter function needs to return an int value, not void.

int letter_counter(char input[STRING_LENGTH], char letter ) {
    int i;
    int count = 0;

    for (i = 0; i < strlen(input); i  ){
    if (input[i] == letter) {
        count  ;
    }

    return count;
}

Then you need to assign the return value of the function to a variable:

a1 = letter_counter(input, a);
  •  Tags:  
  • c
  • Related