K&R - Exercise 1-9 - Removing Spaces

Viewed 769

I recently started learning C using the K&R book (2nd ed.) and I'm just having trouble wrapping my mind around this solution to exercise 1-9 which is:

Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

I found the following solution online and it mostly makes sense except for that semi-colon above putchar(' ');. Without it the program doesn't perform its function properly, what function does that semi-colon serve?

#include <stdio.h>

int main(void)
{
  int c;

  while ((c = getchar()) != EOF) {
    if(c  == ' ') {
      while((c = getchar()) == ' ')
      ;
      putchar(' ');
    }
    putchar(c);
  }
}

Thanks in advance.

2 Answers
Related