Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my letter counter display 0 when put in a function

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);




}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading