Home>

Entered string (this timeabcdabcdThe following program that displays the number of letters a contained in) was executed.

#include<stdio.h>
int find_a (const char s []) {
    int i = 0;
    int count = 0;
    while (s [i])
        if (s [i] =='a')
            count ++;
        i ++;
    return count;
}
int main (void) {
    char str [100];
    printf ("Please type in a word:");
    scanf ("% s", str);
    printf ("Number of'a' is% d", find_a (str));
    return 0;
}


However, in the terminal

Please type in a word: abcdabcd


Was displayed, and nothing was displayed after that.
Please tell me why it behaves like this.

c
  • Answer # 1

    while (s [i])
       if (s [i] =='a')
           count ++;
       i ++;

    This is the same as writing:

    while (s [i]) {
       if (s [i] =='a') {
           count ++;
       }
    }
    i ++;

    Since the value of i does not change during the loop, it is in an infinite loop.