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

6 comments :

  1. It's been fun following along with you.
    Here is what I came up with.

    int main()
    {
    int c;

    while ((c = getchar()) != EOF)
    {
    if (c == ' ' || c == '\t')
    putchar('\n');
    else
    putchar(c);
    }

    return 0;
    }

    ReplyDelete
    Replies
    1. Hope you are liking the solutions. I have resumed solving Chapter 2. You have a look into here https://www.harishnote.com/p/my-k-r-answers.html

      Delete
  2. Realised I made a mistake my my code.
    If I put multiple spaces or tabs in keeps creating new lines :S

    ReplyDelete
  3. I realised I made a mistake with the code I sent you :S
    If there are multiple spaces of tabs it keeps creating new lines.

    ReplyDelete
  4. I realised I made a mistake with the code I sent you :S
    If there are multiple spaces of tabs it keeps creating new lines.

    ReplyDelete
  5. I realised I made a mistake with the code I sent you :S
    If there are multiple spaces of tabs it keeps creating new lines.

    ReplyDelete