Tuesday, October 13, 2009

c Kernighan & Ritchie exercise

Lately im into c programming, really newbie, so im reading Kernighan & Ritchie famous book.
Here a funny exercise that reverse an input line string:

"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."

i change the params as you can see..


#include <stdio.h>

#define MAXLEN 30

int getline(char s[], int lim);
void reverse(char s[], char r[], int len);

int main()
{
int len;
char line[MAXLEN];
char reversed[MAXLEN];

len = 0;

while((len = getline(line, MAXLEN)) > 0)
{
reverse(line, reversed, len);
printf("\nReversed = %s\n\n", reversed);
}

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;
++i;
}
s[i] = '\0';
return i;
}

void reverse(char s[], char r[], int len)
{
int i;

for(i = 0; i < len; i++)
r[i] = 0;

for(i = 0; i < len; i++)
{
/* -2 will strip \n in the original string (-1 the original end of string */
r[i] = s[len-i-2];
}
r[len] = '\0';
}