dimanche 21 février 2021

How to get the if statement out of the loop if it satisfies the condition?

I have written a code that prints out how many a's there are in a user input string.

I want the program to print out "There is a total of 1 a" instead of "There are a total of 1 a's".

I tried writing an if statement, but it prints out the length of the string in every loop. How can I adjust this? I've tried some things, but I did not get that far.

#include <stdio.h>
#include <cs50.h>
#include <string.h>

int main(void){
    int count = 0;
    string input = get_string("Write something and I'll tell you how many a's there are: ");

    for (int i = 0, n = strlen(input); i < n ; i++){
        if (input[i] == 'a' || input[i] == 'A'){
             count++;
        }
        if (count == 1){
            printf("\nThere is a total of %i a", count);
        }
    }

    printf("\nThere are a total of %i a's", count);
}

Aucun commentaire:

Enregistrer un commentaire