Thread: Clarification on loops

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    11

    Clarification on loops

    I was trying to solve question 1.12 of k&r which asked me to write a c program that prints its input one word per line.
    This is the code I wrote :
    Code:
    #include <stdio.h>
    
    int main() {
        int c;
        while((c=getchar())!='\n')
        {
            if ( c == ' ' || c == '\t'){
                putchar('\n');
            while (c == ' ' || c== '\t')
                c = getchar();
            }
            else {
                putchar(c);
            }
        }
    }
    My problem with these lines :
    Code:
    while (c == ' ' || c== '\t')
                c = getchar();
    What's the use of this line in the program? Doesn't the code
    while ((c=getchar()) != EOF) ensures that it keeps on getting char?

    And why the program doesn't work if I put the putchar(c) outside the while?
    Last edited by Noobpati; 02-22-2017 at 08:41 AM.

  2. #2
    Registered User
    Join Date
    Feb 2017
    Posts
    1

    Loop Clarification

    In your code the outer while statement loops over each character in your input. At each character, a check is done to identify whether it is a whitespace:
    • if it is, then we print a newline, and drop every consequent whitespace.
    • if the character is not a whitespace, we print it.

    This repeats until a newline is met.

    Note how if we move the print newline outside of the main while loop, it means that the program just iterates over each character in the input, and prints a newline if it is a whitespace character (No printing occurs).

    However, if you look at the logic in your program, you might notice that there's a slight issue - the inner while loop repeatedly retrieves characters until the character is not a whitespace, at which point, the if statement ends, and the condition for the outer while loop is run, retrieving a new value (overwriting the character stored in c, which is not a whitespace).

    Have you tried running the program? It misses out the first character of every word. Also if there are spaces before the newline, the program doesn't terminate.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ programing , Loops , infinite loops issue
    By Ibrahim Lawleit in forum C++ Programming
    Replies: 15
    Last Post: 07-14-2014, 03:41 PM
  2. Replies: 3
    Last Post: 06-01-2011, 04:19 PM
  3. Clarification....
    By CommonTater in forum C Programming
    Replies: 4
    Last Post: 09-23-2010, 05:39 PM
  4. Help! Need some clarification.
    By jaro in forum C Programming
    Replies: 2
    Last Post: 04-08-2006, 11:44 AM
  5. need clarification on something...
    By EvBladeRunnervE in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 03-08-2004, 09:45 AM

Tags for this Thread