Search code examples
cturbo-c

Turbo C 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!


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.