Week 08 Tutorial Questions
1. How are you going with assignment 1?
2. Consider the program below:
#include <stdio.h> int main(void) { char str[10]; str[0] = 'H'; str[1] = 'i'; printf("%s", str); return 0; }
- What will happen when the above program is compiled and executed?
- How do you correct the program?
3. Name 3 errors in this program:
#include <stdio.h> #define MAX_LINE 4096 int main(void) { char line[MAX_LINE]; int i; while (fgets(line, MAX_LINE, stdin) != NULL) { i = MAX_LINE; while (line[i] != '\n') { i = i - 1; } printf("the line is %d characters long\n", i); } return 0; }
4. Write a program line_length.c
which reads lines from its input and prints how many characters each line contains.
The only functions you can use are fgets
and printf
.
You can assume lines contain at most 4096 characters.
For example:
./line_length Andrew Rocks line 12 characters long A very long line. line 17 characters long short line 5 characters long line 0 characters long
5. Write a program strip_comments.c
which reads lines from its input and prints them after removing any C // style comments.
In other words, if the line contains //, it does not print the // or anything after it.
The only functions you can use are fgets
and printf
.
You can assume lines contain at most 4096 characters.
For example:
./strip_comments x = x + 1; // This means add one to the variable x x = x + 1;Also - is that a good comment to add to a C program?
6. Write a program filter_empty_lines.c
which reads lines from its input and prints them only if they contain a non-white-space character.
In other words, remove lines that are empty or contain only white-space.
The only functions you can use are fgets
and printf
.
You can assume lines contain at most 4096 characters.
You can assume there are only 3 white space characters: space, tab, and newline.
For example:
./filter_empty_lines full line full line another non-empty line another non-empty line
7. Write a C program reverse.c
which reads lines and writes them out with the characters of each line in reverse order.
It should stop when it reaches the end of the input.
For example:
./reverse The quick brown fox jumped over the lazy dog. .god yzal eht revo depmuj xof nworb kciuq ehT It was the best of times. It was the worst of times. .semit fo tsrow eht saw tI .semit fo tseb eht saw tI This is the last line. .enil tsal eht si sihT
8. Strlen is a function that returns the length of a string. Write your own C function to do the same.
int myStrlen(char *string);