Exercise 5-1 - CBD page 198 - Kurt Nørmark

Solution index                   Textual C program


#include <stdio.h>
#include <ctype.h>

void putch(char, int);

int main(void){
  char c;

  while((c = getchar()) != EOF) {
    if (isalpha(c)){
      putch(c,3); putchar('\n'); }
    else if (c!='\n')
      putch(c,1);
    else ;   /* Empty - do no print newlines */
  }
  return 0;
}

void putch(char ch, int n){
  int i;
  for(i = 1; i <= n; i++) putchar(ch);
}

This program differs from Lone's solution in the interpretation of what letters mean. In this version letters are recognized by the isalpha abstraction.
 

  while((c = getchar()) != EOF) {
    if (isalpha(c)){
      putch(c,3); putchar('\n'); }
    else if (c!='\n')
      putch(c,1);
    else ;   /* Empty - do no print newlines */
  }
A while loop which reads a character c by getchar(). It stops when the EOF (End of File) mark is encountered. This is the last character in the file. The logical expression in the while loop is a C idiom, seen again and again. Please be sure you understand the details!
 

    if (isalpha(c)){
      putch(c,3); putchar('\n'); }
    else if (c!='\n')
      putch(c,1);
    else ;   /* Empty - do no print newlines */
The body of the while loop. The if else chain within the loop which handles letters, non-letters (apart from newlines), and newlines in different ways. Letters are printed three times followed by a newline. Non-letters are just echoed. If we encounter the final else part, we know for sure that isalpha(c) is false, and even more useful, that c == '\n'. Explain! Therefore, the program ignores newlines.
 

void putch(char ch, int n){
  int i;
  for(i = 1; i <= n; i++) putchar(ch);
}
To enhance both readability and generality, we introduce the function putch, which prints its first parameter a number of times determined by the second parameter. If we change our minds with respect to the multiplicity of the printed characters, it is very easy to modify the actual parameters of putch in main. Seen in retrospect, we should have found a better name to this function, such as multiputchar or mputchar.
 


Generated: Wednesday, March 29, 2006, 12:33:25
This program dissection page is generated from an XML-in-LAML source file