Exercise 1-19 (Reverse, getline)

Chapter_1     Exercise_1-18 Extern_longest_line     Exercise_1-20







Exercise 1-19     K&R, p. 31


Exercise 1-19. 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.




reverse.c         download


#include <stdio.h> // for getchar(), putchar(), printf(), EOF

#define MAXLINE 1000 // maximum input line length

int getLine(char line[], int maxline); // getline() is declared in stdio.h
void reverse(char line[], int length);

// reverse each line
int main()
{
int len; // current line length
char line[MAXLINE]; // current input line
// line containing only '\n' has length 1:
while((len = getLine(line, MAXLINE)) > 0)
{
reverse(line, len);
printf("%s", line);
if (line[len-1] != '\n') {putchar('\n');}
}

return 0;
}

// getLine(): read a line into s[] up to LENGTH chars, return length
int getLine(char s[], int lim)
{
int c = EOF; // initialize
int i;
// getchar() is only executed if (i < (lim-1)):
for (i = 0; i < (lim-1) && (c = getchar()) != EOF && c != '\n'; i++)
{ // from 0 to lim-2; s[lim-2]='\n', s[lim-1]='\0'
s[i] = c;
}
if (c == '\n') // i < (lim-1), getchar() executed
{
s[i] = c; // '\n'
i++;
}
s[i] = '\0'; // the null character ends a string

return i; // max(i) == (lim-1)
}

// reverse a string of characters, knowing its length
void reverse(char line[], int len)
{
int start, end;
int temp; // temporary value

start = 0; // first char position in line[]
end = len-1; // last char before ending '\0'

if (line[end] == '\n')
{end--;} // do not put '\n' on position 0

while (start < end)
{
temp = line[start];
line[start] = line[end];
line[end] = temp;
start++, end--;
}
}
/*
gcc reverse.c -o reverse
./reverse // input from the keyboard
ana
ana
anna
anna
ab
ba
a
a
abc
cba
abcd
dcba
12345
54321
// Ctrl+D in Linux, Ctrl+Z then Enter in Windows (EOF)

./reverse < reverse.c // source file

./reverse < reverse // binary file
*/





Note:  A function  void reverse(line[])  would have to compute first the length of  line[]:
int len;
for(len = 0; line[len] != '\0'; len++) {}









Chapter_1     Exercise_1-18 BACK_TO_TOP Extern_longest_line     Exercise_1-20



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo