Question

Hello I am using Turbo C... I just have some query, I found a code of TC in a book but I'm not satisfied with the given clarification. Here's the code:

main()
{
     int count = -1;                /* why it was initialized as -1? */
     char ch;

     printf("Type in a phrase:\n");
     ch = 'a';                      /* why it was initialized as 'a'? */
     while (ch != '\r')             /* perform while ch is not equal to return */ 
     {
           ch = getche();           
           count++;                 /* increment the count */
     }

 printf("\nCharacter count is %d", count);   /* prints the value of count */

}

Thanks in advance!

Was it helpful?

Solution

Suppose your user types in "abc" and presses enter, so the input buffer contains 'a','b','c','/r' (this last character represents return). There are 4 characters in the buffer, but your user only really typed in 3 (one was return), so you need to subtract one from the count. Or, alternatively, start the count at -1 rather than 0.

You could think of it this way - how many times does this go through the loop?

  • Count starts at -1.
  • First time: read 'a' from string. Go round again as it's not '/r'. count is now 0.
  • Second time: read 'b' from string. Go round again as it's not '/r'. count is now 1.
  • Third time: read 'c' from string. Go round again as it's not '/r'. count is now 2.
  • Fourth time: read '/r' from string, and stop. count is now 3.

On your second point, it doesn't really matter what ch is initialized to, as long as it's not '\r'. This means that you'll go into the loop at least once, and read in the characters.

OTHER TIPS

 int count = -1;                \* why it was initialized as -1? *\

Looks to me as if it's counting characters in a line, excluding the final 'carriage return' character. That's why it starts at -1 - so that the '\r' character won't be part of the count.

 ch = 'a';                      \* why it was initialized as 'a'? *\

Just so the condition in the while loop will be initially true. Anything could have been chosen, just so long as it wasn't '\r', as then the condition would have been false immediately and no characters would be read.

In the first question, count value can be started in anyway. It is not mandatory to start only with -1.

They just did that for their own convenience. We just want to count the numbers from 1 or 0. The same formula will be applied to the alphabets. Sentence and word will be the combination of the alphabets. In order to start in a particular order, we should count like that without any confusion.

If we type any phrase or anything else we need a termination variable like \0, as they were not present in alphabets. To calculate the frquency, we need to increment the count.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top