Tomas Varas
Tomas Varas

Reputation: 21

How to count the amount of words with more than 3 letters?

I am trying to write a program that counts the amount of words that have more than three letters. The program has to end when a period is entered. My code works, but it fails to count the first word, so, if I enter three words with more than three letters, the output is two.

I tried to do the following: I count letters until the user clicks the spacebar. When that happens, I check whether the counter is larger than three. If it is, it increases the counterLargerThanThree by one. This runs continuously, until the user enters a period. When the user enters a period, the program finishes.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    int cont = 0, aux , counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");

    c = getchar();

    while(c != '.')
    {
        aux = c;
        c = getchar();
        cont++;

        if(aux == ' ')
        {
            if(cont>3)
            {
                counterLargerThanThree++;
            }

            cont = 0;
        }
    }

    printf("%i \n",counterLargerThanThree);


    system("pause");
    return 0;
}

Upvotes: 2

Views: 715

Answers (2)

shubham jha
shubham jha

Reputation: 1480

You are not counting the last word as when period character . comes you break the loop even if word length>3. Try something like this.

#include<stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    int cont = 0, aux , counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");


    while(1)
    {
        c = getchar();
        cont++;

        if(c == ' ' || c=='.')
        {
            if(cont>3)
            {
                counterLargerThanThree++;
            }

            cont = 0;
        }
        if(c=='.'){
            break;
        }
    }


    printf("%i \n",counterLargerThanThree);


    system("pause");
    return 0;
}

Upvotes: 0

user4520
user4520

Reputation: 3457

At the end of your input (i.e. when a dot is encountered), the while loop is skipped, and you never get the chance to count that last word, if it happens to be more than three chars long.

Try this instead:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    int cont = 0, counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");

    do
    {
        c = getchar();
        if (c != ' ' && c != '.')
        {
            ++cont;
        }
        else
        {
            if (cont > 3)
            {
                counterLargerThanThree++;
            }
            cont = 0;
        }
    }
    while (c != '.');

    printf("%i \n", counterLargerThanThree);


    system("pause");
    return 0;
}

Upvotes: 1

Related Questions