home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 7 / 07.iso / c / c220 / 4.ddi / DEMOS / PALIN.C < prev    next >
Encoding:
C/C++ Source or Header  |  1990-12-16  |  1.7 KB  |  59 lines

  1. /*
  2. * This program prints out each prefix of its input that is a palindrome.
  3. * It prints out such a prefix as soon as it is read in; the input is read
  4. * character by character.
  5. * The computation of palindromes is done WITHOUT arrays, records, or
  6. * pointers, but with only simply scalar variables.
  7. * It points out the power of procedural parameters and nested procedures,
  8. * available only in MetaWare High C.
  9.  
  10. * For example, on input
  11.      abcbaxyyxabcba
  12. * the program should print that
  13.      a
  14.      abcba
  15.      abcbaxyyxabcba
  16. * are all palindromes.
  17. */
  18.  
  19. typedef enum{False,True} Boolean;
  20.  
  21. #include <stdio.h>
  22.  
  23. void Palindrome(
  24.     int Ch(int I)!,     /* Extended-lambda:  full procedural parameter. */
  25.     int Depth) {
  26.    /* Read the next char and report if we have a palindrome so far. */
  27.    int C;
  28.    Boolean Is_pal;
  29.    int I;
  30.    do {
  31.       C = getc(stdin);
  32.       if (C == EOF) return;
  33.       }
  34.    while (C == '\n' || C == '\r');
  35.    if (Depth > 140) return;  /* max stack limit exceeded */
  36.    int Ch2(int I) {
  37.       return I == Depth ? C : Ch(I);
  38.       }
  39.    Depth++;
  40.    /* Do we currently have a palindrome? */
  41.    Is_pal = True;
  42.    for (I = 1; I <= Depth && Is_pal; I++)
  43.       if (Ch2(I) != Ch2(Depth-I+1)) {Is_pal = False; break;}
  44.    if (Is_pal) {
  45.       printf("Palindrome discovered:");
  46.       for (I = 1; I <= Depth; I++) printf("%c",Ch2(I));
  47.       printf("\n");
  48.       }
  49.    Palindrome(Ch2,Depth);
  50.    }
  51.  
  52. void main () {
  53.    int Dummy(int I) { return I; }       /* Should never be called. */
  54.    printf("Type in characters, hitting RETURN as often as you wish.\n");
  55.    printf("As I recognize palindromes, I'll tell you.\n");
  56.    printf("Type Control+Z, then RETURN to terminate program.\n");
  57.    Palindrome(Dummy,0);
  58.    }
  59.