1

Hi guys i just wronte this small program in C using the Notepad++ and Cygwin. So the code is the following:

#include <stdio.h>

int main()
{
        int c, i, countLetters, countWords;
        int arr[30];

        countLetters = countWords = 0;
        for(i = 0; i < 30; ++i)
            arr[i] = 0;

        while(c = getchar() != EOF)
                if(c >= '0' && c <= '9')
                    ++arr[c - '0'];

                else if (c == ' ' || c == '\n' || c == '\t')
                    ++countWords;

                else
                    ++countLetters;

        printf("countWords = %d, countLetters = %d\n",
        countWords, countLetters );
}

but instead of counting words the program counts words as letters and print them as letters and words = 0... where am i wrong because even my teacher couldn`t give me an answer...

3 Answers 3

8

Try using curly brackets and the c = getchar() needs parentheses.

while((c = getchar()) != EOF) {
      ^             ^
     /* Stuff. */
}
Sign up to request clarification or add additional context in comments.

Comments

6

The error is here:

while(c = getchar() != EOF)

You need to enclose the assignment in parentheses, like so:

while( (c = getchar()) != EOF)    /*** assign char to c and test if it's EOF **/

Otherwise, it is interpreted as:

while(c = (getchar() != EOF))    /** WRONG! ***/

i.e. c is 1 for each char read until the end of file.

Comments

2

The solution:

change while(c = getchar() != EOF), to while((c = getchar()) != EOF)

Reason:

!= has higher priority than =

Hence ,

getchar() != EOF

evaluates to be false and thus becoming

while(c=1) ==> while(0).

Hence, the loop gets iterated with c=1 ,what ever your input be. (except EOF).

In this case Your expression is always evaluates to be false.

since,

if(c >= '0' && c <= '9') is if(1>=48 && 1<=57) and it is always false.

Also,

else if (c == ' ' || c == '\n' || c == '\t')

will evaluated to be false.

Hence the else part countLetters++ will be executed for all inputs!

Resulting in the case as you prescribed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.