EXERCISES ON CHARACTERS AND STRINGS 1. What does the following code fragment print out. #include <stdio.h> int main(void) { char c1 = 'A', c2 = '8'; int m = 66, n; printf("'A' : %c %d\n", c1, c1); printf("'8' : %c %d\n", c2, c2); printf("66 : %c %d\n", m, m); printf("'A' + 2 : %c %d\n", c1 + 2, c1 + 2); n = (c2 - '0') * m; printf("n = %d\n", n); return 0; } 2. Which of the following sets i to the length of the string a? (a) i = strlen(a); (b) i = 0; while (a[i] != '\0') ++i; (c) i = 0; while (a[i] != '\0') i++; (d) for (i = 0, b = a; *b != '\0'; b++) i++; (e) for (i = 0; a[i] != '\0'; i++) ; (f) b = a; while (*b++) ; i = b-a-1; (g) b = a; while (*b) b++; i = b-a; 3. What is wrong with the following program for printing out the length of a word from standard input? #include <stdio.h> int main(void) { int n; char a[101]; scanf("%s", a); for (n = 0; *a != '\0'; a++) n++; printf("%d %s\n", n, a); return 0; } 4. Explain what the following program does. #include <stdio.h> #include <string.h> int main(void) { int i, N; char word[101]; while (scanf("%s", word) != EOF) { N = strlen(word); for (i = 0; i < N; i++) if (word[i] <= word[i+1]) break; if (i == N) printf("%d %s\n", N, word); } } return 0; } 5. Write a program that prints out any words in its input that are palindromes (read the same forwards and backwards). 6. Write a C function that takes a string as an argument and modifies the string so as to remove all consecutive duplicate characters, e.g., mississippi -> misisipi. 7. (a) Write a C program that takes a filename as a command line input, copies the contents of the file into a string, and prints the string. (b) Modify your solution to part (a) so that it discards all characters except {a, c, g, t} when copying into the string. (c) Modify your solution to part (a) so that it discards all characters except {A, B, ..., Y} when copying into the string.