in Doing Books

The C Programming Language (TCPL): Chapter 1

This is definitely my most favorite C book and probably one of the best programming books ever written. If you want to dive into C, this is the perfect book. However, I won’t recommend it if you don’t know the basics.
In this series I will post my solutions for some more interesting exercises.

Exercise 1-9. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

#include

int main()
{
char c;
while((c = getchar()) != EOF)
{
if (c == ' ')
{
putchar(c);
while((c = getchar()) == ' ')
{
;
}
}

putchar(c);
}
return 0;
}

Exercise 1-19. Write a function reverse(s) that reverses the character string s.

#include

int length(char s[])
{
int i;
for(i = 0; s[i] != ''; i++)
;
return i;
}

void switchchar(char s[], int i, int j)
{
char tmp;

tmp = s[i];
s[i] = s[j];
s[j] = tmp;

}

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

len = length(s) - 1;

for(i = 0; i < (len / 2); i++) { switchchar(s, i, (len - i)); } }int main() { char s[] = "abcdefghi"; reverse(s);return 0; }

Write a Comment

Comment