Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.19 on page 31

Write a function reverse(s) that reverses the character string s . Use it to write a program that reverses its input a line at a time.

Solution by Richard Heathfield

#include <stdio.h>

#define MAX_LINE 1024

void discardnewline(char s[])
{
  int i;
  for(i = 0; s[i] != '\0'; i++)
  {
    if(s[i] == '\n')
      s[i] = '\0';
  }
}

int reverse(char s[])
{
  char ch;
  int i, j;

  for(j = 0; s[j] != '\0'; j++)
  {
  }

  --j;

  for(i = 0; i < j; i++)
  {
    ch   = s[i];
    s[i] = s[j];
    s[j] = ch;
    --j;
  }

  return 0;
}

int getline(char s[], int lim)
{
  int c, i;

  for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i)
  {
    s[i] = c;
  }

  if(c == '\n')
  {
    s[i++] = c;
  }

  s[i] = '\0';

  return i;

}

int main(void)
{
  char line[MAX_LINE];

  while(getline(line, sizeof line) > 0)
  {
    discardnewline(line);
    reverse(line);
    printf("%s\n", line);
  }
  return 0;
}


Solution by Amarendra Godbole

#include <stdio.h>

#define MAXLINE 1000

/* reverse a line, discard empty lines */

int
getline(char s[], int max);
void
reverse(char s[]);

int
main(void)
{
    int len, i;
    char line[MAXLINE], longest[MAXLINE];

    while ((len = getline(line, MAXLINE)) != 0) {
        if (len > 1) {
            reverse(line);
            printf("%s\n", line);
        }
    }

    return 0;
}

int
getline(char s[], int max) {
    int i, c;
    for (i=0; i<max-1 && (c=getchar())!=EOF && c!='\n'; ++i) {
        s[i] = c;
    }
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void
reverse(char s[]) {
    int i, j;
    char temp;

    for (j = 0; s[j] != '\0'; ++j)
        ;
    --j;

    if (s[j] == '\n') {
        s[j] = '\0';
        --j;
    }

    for (i = 0; i < j; i++) {
        temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        --j;
    }
}

Pilcrow 22:33, 4 July 2011 (UTC)

>h.oidts< edulcni#
4201 ENILXAM enifed#

)mil tni ,][s rahc(enilteg tni
{
;i ,c tni

)i++ ;'n\' =! c && FOE =! ))(rahcteg=c( && 1-mil < i ;0 = i( rof
;c = ]i[s
)'n\' == c( fi
;c = ]++i[s
;'0\' = ]i[s
;i nruter
}

)nel tni ,][taht rahc(esrever diov
{
;y ,x tni
;t rahc

)'n\' == ]1-nel[taht(fi
;'0\' = ]nel--[taht
{ )++y ,--x ;y>x ;0=y ,1-nel = x(rof
;]x[taht = t
;]y[taht = ]x[taht
;t = ]y[taht
}
;nruter
}

)diov(niam tni
{
;]ENILXAM[s rahc
;nel tni
;x tni

{ )0 > ))ENILXAM ,s(enilteg = nel((elihw
;)nel ,s(esrever
;)s,"n\s%"(ftnirp
}
;0 nruter
}
Personal tools
Personal tools
Tidy_icons
not logged in