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
It's been fun following along with you.
ReplyDeleteHere 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;
}
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
DeleteRealised I made a mistake my my code.
ReplyDeleteIf I put multiple spaces or tabs in keeps creating new lines :S
I realised I made a mistake with the code I sent you :S
ReplyDeleteIf there are multiple spaces of tabs it keeps creating new lines.
I realised I made a mistake with the code I sent you :S
ReplyDeleteIf there are multiple spaces of tabs it keeps creating new lines.
I realised I made a mistake with the code I sent you :S
ReplyDeleteIf there are multiple spaces of tabs it keeps creating new lines.