Sep 13, 2015

K & R : Exercise 1.12 - Print word per line

Problem Statement:

Exercise 1-12: Write a program that prints its input one word per line.



Solution:

We need to print one word per line. Hence we need to detect the start of word and add a newline. Lets store the inputted character in variable c. Lets use a variable flag to detect the start of new word so that new line could be inserted.


#include <stdio.h>

int main()
{
   int c;
   int flag = 0;

   while((c = getchar()) != EOF) {
      if((c == ' ') || (c == '\t')) {
         flag = 1;
      }
      if((flag == 1) && (c != ' ') && (c != '\t')) {
         printf("\n%c", c);
         flag = 0;
      }else {
         printf("%c", c);
      }
   }
   return 0;
}

Output of the above program is


$ ./a.out
Mary had little lamb
Mary
had
little
lamb
^C
$





Next Article - K & R : Exercise 1.13 - Horizontal histogram [Part 1]
Previous Article - K&R : Exercise 1.11 - Testing word count
All Articles - K & R Answers

No comments :

Post a Comment