Kernighan and Ritchie C exercises
Learning C gives me that familiar feeling I had when I switched from Classic ASP to PHP many moons ago - what the hell is the equivalent function? It also makes me quite happy at the abstractions PHP provides, which can make life much simpler.
I've been reading through the Kernighan and Ritchie C book, and have decided to code up some of the exercises and post them here. Basically, this is for a few reasons: to have them available to other people, and for the chance to let other programmers give me feedback if they wish.
Also, I might make note that some of the things I do were not taught at that point in the book, but I've simply called on my PHP background to find a solution. I'm also going to skip some of the earlier exercises.
Exercise 1-8
#include <stdio.h>
int main () {
int c, nl, t, b;
nl = t = b = 0;
while ((c = getchar()) != EOF) {
switch (c) {
case '\n':
++nl;
break;
case '\t':
++t;
break;
case ' ':
++b;
break;
}
}
printf("new lines => %d\n", nl);
printf("tabs => %d\n", t);
printf("blanks => %d\n", b);
}Exercise 1-9
#include <stdio.h>
int main () {
int c;
char lastChar;
while ((c = getchar()) != EOF) {
if (c == ' ' && lastChar == ' ') {
continue;
}
lastChar = c;
printf("%c", c);
}
}Exercise 1-10
#include <stdio.h>
int main () {
int c;
printf("\n"); // For readability
while ((c = getchar()) != EOF) {
switch (c) {
case '\t':
printf("\\t");
break;
case '\b':
printf("\\b");
case '\\':
printf("\\\\");
break;
default:
printf("%c", c);
break;
}
}
}So as you can see, I'm not far into the book yet, but I'm taking my time and trying not to rush and forget things. I did end up getting stumped by something obvious on the last exercise. If you have any feedback, please let me know in the comments!
Comments
No comments yet.
Leave a Comment
Note: Your comment may require approval before it is posted to the site.