CS U111 · Lab 7 · Strings and integrated programming
Lab 7, every problem worked
All four dry runs, all five debugging exercises, all nine practice problems, the Caesar-breaking challenge, the Archivist's grid and the four bonus problems. Each question appears as set, followed by the answer, the reasoning, and the output the program actually printed. Every program on this page was compiled with clang -Wall -Wextra and run against the sheet's own sample inputs, plus an empty line and at least one awkward input.
Most of this sheet repeats Lecture 9: '\0', fgets keeping the newline, strlen vs sizeof, strcmp instead of ==, and the ctype.h tools. The strings lesson and strings notes already cover all of it. If any of those feel shaky, spend 20 minutes there first.
The sheet adds six things that Lecture 9 deferred. Section 1 below teaches them: strings passed to functions, arrays of strings, the strcspn trim, the scanf-then-fgets fix, strtok and sprintf. None of these is taught in school, so this is new for everyone in the room, including the JEE crowd. The problems themselves reuse patterns you already have. Problem 5 is your Lab 6 bubble sort with two lines changed, and Problem 8 is mostly code from earlier in the sheet.
Why it matters for marks: lab evaluations are unannounced and open book (10% across the semester), and the end-semester lab exam is open book at a keyboard (25%). This sheet ties strings, arrays and functions together, which makes it the closest sheet so far to what a lab exam can ask.
- 20 min: section 1, the six new tools. Read each one, then try its check box.
- 15 min: the four dry runs. Write your prediction on paper before you open the answer.
- 15 min: the five debugging exercises. Say the bug in one sentence, then write the fix.
- 60 min: four practice problems at the keyboard, shortest first: 1 (statistics), 2 (title case), 9 (roll number) and 5 (sorting names). Type your own version first, then compare it with the one here.
- 10 min: the what we found box as a last skim.
Problems 4, 3, 6, 7 and 8 come next in that order. The challenge, the grid and the bonus problems are for a free evening. Skip them if time is short.
- Six things Lab 7 adds to Lecture 9
- Dry runs 1–4
- Debugging exercises 1–5
- Practice problems, shortest first: 1 · statistics · 2 · title case · 9 · roll number · 5 · sort names · 4 · RLE decoder · 3 · Vigenère · 6 · CSV record · 7 · find and replace · 8 · menu
- Challenge · breaking the Caesar cipher
- Advanced · the Archivist's grid
- Bonus challenges 1–4
- What we found when we ran the sheet
1 · Six things Lab 7 adds to Lecture 9
Lecture 9 said that passing strings to functions and strtok would wait until after pointers. The lab sheet uses both now, so here is just enough of each to read and write the sheet's programs. You don't need pointers for any of it.
A · A string passed to a function is not copied
Recall Lab 5a: pass an int to a function and the function gets a copy. Change the copy and the caller's variable stays the same. Arrays work differently. When you pass name, C passes where the array lives in memory, not a copy of its contents. So the function works on the caller's own boxes, and its changes stick.
#include <stdio.h>
#include <string.h>
void show(char s[]) {
printf("inside: sizeof = %d, strlen = %d\n", (int) sizeof(s), (int) strlen(s));
}
void shout(char s[]) { s[0] = 'J'; }
int main(void) {
char name[20] = "Amit";
printf("in main: sizeof = %d, strlen = %d\n", (int) sizeof(name), (int) strlen(name));
show(name);
shout(name);
printf("%s\n", name);
return 0;
}
% ./a.out
in main: sizeof = 20, strlen = 4
inside: sizeof = 8, strlen = 4
Jmit
This explains three lines in sheet §9:
- Changes are visible to the caller.
shoutturned"Amit"into"Jmit"without returning anything. That's how a function "returns" a string: it writes into a buffer the caller owns. sizeofinside the function is 8, not 20. The function only received a location, and a location takes 8 bytes on a 64-bit machine. clang warns you: sizeof on array function parameter will return size of 'char *' instead of 'char[]'. Inside a function, usestrlento measure the text and walk to'\0'. This is the same trap as the arrays notes card onsizeofinside a function.constmeans "I only read this". Writeint countVowels(const char s[])and any accidental write such ass[0] = 'x';becomes a compile error. clang says read-only variable is not assignable.
char s[] and char *s mean the same thing in a parameter list. The sheet uses both forms.
B · Arrays of strings are 2D char arrays
char names[5][20] is five rows of 20 boxes, one name per row. names[i] is a whole row, so you use it anywhere a string goes: printf("%s", names[i]), strcmp(names[i], names[j]), fgets(names[i], sizeof(names[i]), stdin). names[i][j] is one character in that row. Rows can't be assigned with =, so swapping two names takes three strcpy calls through a spare buffer. That's the whole of Problem 5.
Each row needs room for its '\0'. Dry run 4 shows what happens when one doesn't have it.
C · The one-line newline trim: strcspn
strcspn(s, "\n") counts how many characters come before the first '\n'. If there is no '\n', it counts up to the '\0'. Both cases give exactly the index you want to overwrite:
fgets(line, sizeof(line), stdin); /* "Surat\n" -> strcspn gives 5 */
line[strcspn(line, "\n")] = '\0'; /* line[5] = '\0' -> "Surat" */
It does the same job as the sheet's four-line if (len > 0 && line[len-1] == '\n') trim. It is also safe on an empty line: strcspn("", "\n") is 0, so line[0] = '\0' changes nothing. Every program on this page uses it.
D · scanf("%d") followed by fgets
scanf("%d") takes the digits and leaves the Enter key, '\n', waiting. The next fgets reads up to and including the first '\n'. That is the leftover one, so the program gets an empty line and doesn't wait for typing. Here it is happening (mix.c: scanf("%d", &n); then fgets(line, …)):
% ./a.out
Age: 19
City: [
] len=1
The program ended before you could type the city. The fix from sheet §6 is one line between the two reads, which throws characters away up to and including the newline:
scanf("%d", &n);
while (getchar() != '\n'); /* empty loop body: just keep reading */
fgets(line, sizeof(line), stdin);
The semicolon at the end of the while line is the whole loop body. The condition does all the work. Problem 8's menu needs this line.
E · strtok cuts a line into pieces
The first call is strtok(line, ",") and gives the first piece. Each later call is strtok(NULL, ","). Here NULL means "carry on with the same line". When no pieces are left, it returns NULL. Two facts that matter:
- It changes your string. It works by writing
'\0'over each separator. After tokenising"read the whole line", printinglineshows justread. Copy the line first if you still need it. - It returns a
char *, which you can read as "where this piece starts". You can print it with%slike any string. That is all the pointer knowledge Problem 6 needs.
F · sprintf prints into a string
sprintf(buf, "%d", 12) works like printf, but it writes "12" into buf instead of the screen. It returns how many characters it wrote, here 2. The sheet's compression example (§18) uses that return value to move its write position forward. It's in an optional section, and no problem on the sheet requires it.
Check yourself: void f(char s[]) { s[0] = 'X'; } is called as f(word) with char word[] = "cat";. What does printf("%s", word) print afterwards? And what would sizeof(s) be inside f?
Xat. The function wrote into the caller's own array, because arrays are passed by location, not copied. Inside f, sizeof(s) is 8, the size of a location on a 64-bit machine, not 4. Compare an int parameter: changing it inside f would not change anything in the caller.
| Rule | Tested by |
|---|---|
A string ends at '\0'. sizeof counts the boxes and strlen counts the characters before the 0. A copy loop that stops at strlen must write the 0 itself. | Dry 1, Dry 4, Debug 2 |
A char is a small number. %c shows the character and %d shows its code. Letters are consecutive, so c - 'a' is a position from 0 to 25. | Dry 2, Debug 4, P3, P4 |
strcmp gives a sign, not a yes/no. 0 means equal, negative means "sorts first" and positive means "sorts after". | Dry 3, P5 |
toupper/tolower return the answer; they don't change the character. | Debug 3, P2 |
fgets keeps the Enter key. Trim it before you compare, count or print. | Debug 5, every problem |
| Swap from both ends, but only to the middle. | Debug 1, P8 |
2 · The four dry runs
Write your answer down first, then open the box. Every answer below was confirmed by compiling the exact code from the sheet.
char s[] = "ABC";
printf("%d %d\n", (int) sizeof(s), (int) strlen(s));Question: What is printed?
Dry run 1: sizeof vs strlen
4 3. char s[] = "ABC" lets the compiler size the array, and it reserves one box per letter plus one for the '\0': 4. strlen counts characters before the '\0': 3. The two numbers differ by exactly one whenever the array is sized automatically like this.
char s[] = "cat";
printf("%c %d %c\n", s[0], s[0], s[0] + 1);Question: What is printed?
Dry run 2: one character, three formats
c 99 d. %c prints the character itself, %d prints its code ('a' is 97, so 'c' is 99), and s[0] + 1 is 100, which %c prints as the next letter, d. The sheet's §3 rule is all you need: letters are consecutive, and you don't need the ASCII table beyond 'a' = 97.
printf("%d\n", strcmp("apple", "apricot"));
printf("%d\n", strcmp("apple", "apple"));
printf("%d\n", strcmp("banana", "apple"));Question: What are the three values, and what do their signs mean?
Dry run 3: what strcmp really returns
On a Mac with clang the exact code prints -1, 0, 1. The signs mean:
- negative:
"apple"sorts before"apricot". They agree onap, and then'p'<'r'. - zero: the strings are equal.
- positive:
"banana"sorts after"apple", because'b'>'a'at the very first letter.
Only the sign is guaranteed. Put the same words into char arrays and the same machine prints -2 0 1, because 'p' − 'r' = −2. The sheet's own myStrcmp (§12) also returns −2. With the literal strings, the compiler works out the answer in advance and writes in −1. So write if (strcmp(a, b) < 0), never == -1.
char words[3][5] = {"one", "two", "three"};
printf("%s %c %d\n", words[2], words[1][0], (int) strlen(words[0]));Question: What is printed? Is there a problem with this declaration?
Dry run 4: a row with no room for '\0'
The intended answer is three t 3, and the compiled program did print that. But yes, there is a problem. "three" needs 6 boxes (5 letters + '\0') and each row has 5. C allows this initialiser and simply leaves the '\0' out, so words[2] is not a string. %s keeps reading past the end of the array until it happens to meet a 0 byte somewhere in memory. On this run the very next byte happened to be 0, so the output looked correct. That was luck, not correct code. clang warns:
warning: initializer-string for character array is too long, array size is 5 but initializer has size 6 (including the null terminating character)
The fix: char words[3][6], where the column size is the longest word + 1.
%s on words[2] walks right until it finds a 0 byte, and the only 0 it can find is outside the array.3 · The five debugging exercises
Answer each one in two parts: what the program actually does, then the change that fixes it. The warnings shown are the real ones from clang on a Mac. For two of these bugs, -Wall -Wextra warns you before you even run the program.
Debugging exercise 1
Double reversal
This program is supposed to reverse a string in place.
char s[] = "stressed";
int len = strlen(s);
for (int i = 0; i < len; i++) {
char temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
printf("%s\n", s);Task: It prints stressed, not desserts. Explain why, then fix it by changing one thing.
What happens. The loop runs over the whole string, so every pair gets swapped twice. With len = 8, the step i = 0 swaps boxes 0 and 7, and the step i = 7 swaps boxes 7 and 0 back again. By the time the loop ends, every swap has been undone and the string is back to how it started.
Fix, changing one thing: stop at the middle.
for (int i = 0; i < len / 2; i++) { /* stop at the middle */
char temp = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = temp;
}
Now it prints desserts. For an odd length, len / 2 rounds down, so the middle character stays where it is, which is correct.
Debugging exercise 2
Missing terminator on copy
char src[] = "Hello";
char dest[20];
for (int i = 0; i < strlen(src); i++) {
dest[i] = src[i];
}
printf("Copied: %s\n", dest);Task: Sometimes it prints Copied: Hello, sometimes Copied: Hello@#$k!?. Explain and fix.
What happens. The loop copies the 5 letters, but stops before the '\0', which sits at index 5. dest is a local array that was never initialised, so boxes 5–19 hold whatever was in that memory before. %s prints Hello and then keeps going until it meets a 0 byte. If the leftover junk happens to start with a 0, the output looks right. If it doesn't, you get garbage. Our first run printed Copied: Hello* followed by unreadable bytes.
Fix: write the terminator yourself, exactly like line 15 of the sheet's myStrcpy ("do not forget this line"):
int len = strlen(src); /* call strlen once */
for (int i = 0; i < len; i++) {
dest[i] = src[i];
}
dest[len] = '\0'; /* the line that was missing */
Calling strlen once and storing it also removes a warning. clang flags i < strlen(src) with comparison of integers of different signs: 'int' and 'unsigned long'. Writing i <= strlen(src) would also work, because it copies the '\0' as the last step.
Debugging exercise 3
Discarded return value
char msg[] = "hello world";
for (int i = 0; i < strlen(msg); i++) {
toupper(msg[i]);
}
printf("%s\n", msg);Task: It prints hello world unchanged. Why?
What happens. toupper(msg[i]) returns the uppercase letter. It doesn't change msg[i], because it got a copy of the character (pass by value, Lab 5a). The returned value is never stored, so it's thrown away. This is the same idea as Lab 5a's "answer that was computed and thrown away". clang catches it at compile time: warning: ignoring return value of function declared with pure attribute.
Fix: store the result back.
msg[i] = toupper((unsigned char) msg[i]); /* keep the answer */
Output: HELLO WORLD. The (unsigned char) cast is the sheet's §8 advice.
Debugging exercise 4
Missing wraparound logic
char text[] = "xyz";
int shift = 5;
for (int i = 0; text[i] != '\0'; i++) {
text[i] = text[i] + shift;
}
printf("%s\n", text);Task: This prints }~ and a strange character instead of cde. Explain what went wrong and fix it.
What happens. Adding 5 to a character code doesn't know about the alphabet. 'x' is 120, so 125 is }. 'y' + 5 = 126 is ~. 'z' + 5 = 127 is the invisible "delete" control character. That's the strange character. The alphabet should wrap from z back to a, but the code never tells it to.
Fix: convert to a position 0–25, shift, wrap with % 26, then convert back to a letter.
text[i] = 'a' + (text[i] - 'a' + shift) % 26; /* position, shift, wrap, back to a letter */
'x': position 23, + 5 = 28, 28 % 26 = 2, and 'a' + 2 = 'c'. Output: cde. This one-liner assumes lowercase letters and a positive shift. The sheet's shiftChar (§14) handles uppercase, non-letters and negative shifts too. Use that version in real code.
Debugging exercise 5
Invisible newline character
#include <stdio.h>
#include <string.h>
int main(void) {
char scanned[20];
char registered[20] = "U23CS045";
printf("Scan roll number: ");
fgets(scanned, sizeof(scanned), stdin);
printf("Scanned: %s\n", scanned);
printf("Expected: %s\n", registered);
if (strcmp(scanned, registered) == 0) {
printf("Present\n");
} else {
printf("Absent\n");
}
printf("Scanned length: %d\n", (int) strlen(scanned));
printf("Expected length: %d\n", (int) strlen(registered));
return 0;
}Task: Predict the output when the scanner sends U23CS045. Explain why the comparison disagrees with your eyes.
What happens. The scanner "presses Enter" after the code, and fgets keeps that '\n'. So scanned holds "U23CS045\n", 9 characters, while registered holds 8. strcmp compares every character, and the extra newline makes them different. Notice the blank line after Scanned:: that is the stored newline being printed, plus the format's own \n.
% ./a.out
Scan roll number: U23CS045
Scanned: U23CS045
Expected: U23CS045
Absent
Scanned length: 9
Expected length: 8
Fix: trim right after reading.
fgets(scanned, sizeof(scanned), stdin);
scanned[strcspn(scanned, "\n")] = '\0'; /* trim the Enter key */
Now it prints Present, and both lengths are 8. The sheet's debugging habit, printf("[%s]\n", s), would have shown the problem at once: [U23CS045 on one line and ] on the next.
4 · The nine practice problems, shortest first
The sheet asks for test cases before code: a normal case, an edge case and the empty string. Each problem below lists the ones we ran, and every one of them printed what we expected. Every solution starts with the same three lines (fgets, then the strcspn trim), so the empty-line case is handled from the start.
Problem 1 · about 10 minutes
Sentence statistics in one pass
Read one line of text. In a single pass over the string, compute and print: total characters (excluding the newline), letters, digits, spaces, vowels, and words.
Sample Execution:
Enter a line: This lab has 5 words!
Characters: 21
Letters: 15
Digits: 1
Spaces: 4
Vowels: 4
Words: 5ifs. Vowels are counted inside the letter branch, after tolower. Words use the sheet's inWord flag from §15: count a word at the moment you step from a space onto a non-space.#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(void) {
char line[200];
printf("Enter a line: ");
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
int chars = 0, letters = 0, digits = 0, spaces = 0, vowels = 0, words = 0;
bool inWord = false;
for (int i = 0; line[i] != '\0'; i++) {
char c = line[i];
chars++;
if (isalpha((unsigned char) c)) {
letters++;
char l = tolower((unsigned char) c);
if (l == 'a' || l == 'e' || l == 'i' || l == 'o' || l == 'u') vowels++;
} else if (isdigit((unsigned char) c)) {
digits++;
}
if (c == ' ') spaces++;
if (isspace((unsigned char) c)) {
inWord = false;
} else if (!inWord) {
inWord = true;
words++;
}
}
printf("Characters: %d\n", chars);
printf("Letters: %d\n", letters);
printf("Digits: %d\n", digits);
printf("Spaces: %d\n", spaces);
printf("Vowels: %d\n", vowels);
printf("Words: %d\n", words);
return 0;
}
% ./a.out
Enter a line: This lab has 5 words!
Characters: 21
Letters: 15
Digits: 1
Spaces: 4
Vowels: 4
Words: 5
Tests run. Empty line: every counter is 0. Three spaces only: Spaces: 3, Words: 0. That is the case a "count the spaces and add 1" shortcut gets wrong (it would say 4 words).
Problem 2 · about 10 minutes
Title case converter
Convert a line so that the first letter of every word is uppercase and the rest are lowercase. Must survive multiple spaces and leading spaces.
Sample Execution:
Enter text: the GREAT gatsby
Title case: The Great GatsbystartOfWord is true at the beginning and after every space. The first non-space character after it gets toupper, and the rest of the word gets tolower. Spaces are left alone, so the spacing survives untouched.#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
void titleCase(char s[]) {
bool startOfWord = true;
for (int i = 0; s[i] != '\0'; i++) {
if (isspace((unsigned char) s[i])) {
startOfWord = true;
} else if (startOfWord) {
s[i] = toupper((unsigned char) s[i]);
startOfWord = false;
} else {
s[i] = tolower((unsigned char) s[i]);
}
}
}
int main(void) {
char text[200];
printf("Enter text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
titleCase(text);
printf("Title case: %s\n", text);
return 0;
}
% ./a.out
Enter text: the GREAT gatsby
Title case: The Great Gatsby
Tests run. Empty line → Title case: with nothing after it. o'NEILL's x-RAY → O'neill's X-ray: only spaces start a new word, so the letter after ' or - is lowercased. That matches the sheet's definition. Real title-casers argue about these cases, and the sheet doesn't ask you to.
Problem 9 · about 12 minutes
Roll number validator
A roll number in this institute has a fixed format: the letter U, then two digits, then two uppercase letters, then three digits. U23CS045 is valid.
Read a roll number and either accept it or report the first position at which it fails, counting from 0.
Sample Execution:
Enter roll number: U23CS045
Valid roll number
Enter roll number: U23cs045
Invalid at position 3: expected an uppercase letter
Enter roll number: U23CS45
Invalid: expected 8 characters, found 7U; 1, 2 = digit; 3, 4 = uppercase; 5, 6, 7 = digit. Check the length before the positions, as the third sample does. Then loop over 0–7 and stop at the first failure.#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char roll[50];
printf("Enter roll number: ");
fgets(roll, sizeof(roll), stdin);
roll[strcspn(roll, "\n")] = '\0';
int len = strlen(roll);
if (len != 8) {
printf("Invalid: expected 8 characters, found %d\n", len);
return 0;
}
for (int i = 0; i < 8; i++) {
char c = roll[i];
if (i == 0 && c != 'U') {
printf("Invalid at position %d: expected the letter U\n", i);
return 0;
}
if ((i == 1 || i == 2 || i >= 5) && !isdigit((unsigned char) c)) {
printf("Invalid at position %d: expected a digit\n", i);
return 0;
}
if ((i == 3 || i == 4) && !isupper((unsigned char) c)) {
printf("Invalid at position %d: expected an uppercase letter\n", i);
return 0;
}
}
printf("Valid roll number\n");
return 0;
}
% ./a.out
Enter roll number: U23cs045
Invalid at position 3: expected an uppercase letter
% ./a.out
Enter roll number: U23CS45
Invalid: expected 8 characters, found 7
Tests run. U23CS045 → valid. X23CS045 → position 0. U2ACS045 → position 2, expected a digit. U23CS04A → position 7. Empty line → found 0. U23CS0456 → found 9. The return 0; inside the loop is the "first position" rule: once one position fails, nothing after it is checked.
Problem 5 · about 15 minutes
Sorting a list of names
Read five names into a two-dimensional char array, one per line, then print them in alphabetical order.
You already know how to sort — you wrote bubble sort in Lab 6. The only thing that changes is the comparison. Instead of a[j] > a[j+1], you compare two strings, and instead of assigning with =, you copy with strcpy.
Sample Execution:
Enter 5 names, one per line:
Meera
Arjun
Zoya
Bhavna
Karthik
Sorted:
Arjun
Bhavna
Karthik
Meera
Zoyaa[j] > a[j+1] becomes strcmp(names[j], names[j+1]) > 0, and each = in the swap becomes strcpy. If the sort itself is hazy, the arrays lesson has a step-through widget.#include <stdio.h>
#include <string.h>
#define N 5
#define LEN 50
int main(void) {
char names[N][LEN];
char temp[LEN];
printf("Enter %d names, one per line:\n", N);
for (int i = 0; i < N; i++) {
fgets(names[i], sizeof(names[i]), stdin);
names[i][strcspn(names[i], "\n")] = '\0';
}
for (int pass = 0; pass < N - 1; pass++) {
for (int j = 0; j < N - 1 - pass; j++) {
if (strcmp(names[j], names[j + 1]) > 0) { /* was a[j] > a[j+1] */
strcpy(temp, names[j]); /* was temp = a[j] */
strcpy(names[j], names[j + 1]);
strcpy(names[j + 1], temp);
}
}
}
printf("Sorted:\n");
for (int i = 0; i < N; i++) printf("%s\n", names[i]);
return 0;
}
% ./a.out
Enter 5 names, one per line:
Meera
Arjun
Zoya
Bhavna
Karthik
Sorted:
Arjun
Bhavna
Karthik
Meera
Zoya
strcmp compares character codes, and every uppercase letter (65–90) comes before every lowercase one (97–122). Type meera, Arjun, zoya, Bhavna, karthik and the output is Arjun Bhavna karthik meera zoya: both capitalised names come first. The sheet's sample avoids this by capitalising every name. If an examiner types lowercase, either say so in a comment or compare lowercase copies.
Problem 4 · about 12 minutes
RLE decoder
Given a compressed string like a3b12c1, reconstruct the original. Counts can be more than one digit.
Sample Execution:
Enter compressed string: a3b12c1
Original: aaabbbbbbbbbbbbcb12 into a b once, followed by a broken pair 2c. Build the number the way Lab 4 built one from digits: count = count * 10 + digit.#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char in[200], out[1000];
printf("Enter compressed string: ");
fgets(in, sizeof(in), stdin);
in[strcspn(in, "\n")] = '\0';
int i = 0, k = 0;
while (in[i] != '\0') {
char c = in[i]; /* the letter */
i++;
int count = 0;
while (isdigit((unsigned char) in[i])) { /* read ALL the digits */
count = count * 10 + (in[i] - '0');
i++;
}
for (int r = 0; r < count && k < (int) sizeof(out) - 1; r++) {
out[k++] = c;
}
}
out[k] = '\0';
printf("Original: %s\n", out);
return 0;
}
% ./a.out
Enter compressed string: a3b12c1
Original: aaabbbbbbbbbbbbc
Unpack this step: how count = count * 10 + (in[i] - '0') reads "12"
count starts at 0. Reading '1': 0 × 10 + 1 = 1. Reading '2': 1 × 10 + 2 = 12. Then 'c' isn't a digit, so the loop stops. in[i] - '0' turns the character '2' (code 50) into the number 2, as in sheet §3.
Tests run. The output above has 3 + 12 + 1 = 16 letters, and a Python check confirms it equals the expected string. x10 → ten x's. Empty line → empty result. The k < (int) sizeof(out) - 1 guard stops a huge count such as a9999 from writing past the 1000-box output buffer.
Problem 3 · about 15 minutes
The Vigenère cipher
A Caesar cipher uses one shift for the whole message, which is why it is easy to break. A Vigenère cipher uses a keyword: the first letter of the key shifts the first letter of the message, the second shifts the second, and the key repeats when it runs out. Non-letters are left alone and do not consume a key letter.
Sample Execution:
Enter message: attack at dawn
Enter key: lemon
Encrypted: lxfopv ef rnhri walks the message, and k counts key letters used so far. k moves on only when a letter is encrypted. That's how "spaces don't consume a key letter" becomes code. key[k % klen] makes the key repeat. The shift for a key letter is its position: l → 11.| message | a | t | t | a | c | k | ␣ | a | t | ␣ | d | a | w | n |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| key letter | l | e | m | o | n | l | – | e | m | – | o | n | l | e |
| shift | 11 | 4 | 12 | 14 | 13 | 11 | 4 | 12 | 14 | 13 | 11 | 4 | ||
| result | l | x | f | o | p | v | ␣ | e | f | ␣ | r | n | h | r |
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void vigenere(char s[], const char key[]) {
int klen = strlen(key);
int k = 0; /* which key letter is next */
for (int i = 0; s[i] != '\0'; i++) {
if (!isalpha((unsigned char) s[i])) continue; /* does not use up a key letter */
int shift = tolower((unsigned char) key[k % klen]) - 'a';
if (islower((unsigned char) s[i]))
s[i] = 'a' + (s[i] - 'a' + shift) % 26;
else
s[i] = 'A' + (s[i] - 'A' + shift) % 26;
k++;
}
}
int main(void) {
char msg[200], key[50];
printf("Enter message: ");
fgets(msg, sizeof(msg), stdin);
msg[strcspn(msg, "\n")] = '\0';
printf("Enter key: ");
fgets(key, sizeof(key), stdin);
key[strcspn(key, "\n")] = '\0';
if (strlen(key) == 0) {
printf("Key must not be empty\n");
return 1;
}
vigenere(msg, key);
printf("Encrypted: %s\n", msg);
return 0;
}
% ./a.out
Enter message: attack at dawn
Enter key: lemon
Encrypted: lxfopv ef rnhr
Tests run. Attack at Dawn! with key LEMON → Lxfopv ef Rnhr!: case is kept, the key's case doesn't matter, and ! passes through. Empty key → refused, because k % 0 divides by zero and crashes the program. That's the edge case to name if asked.
Problem 6 · about 15 minutes
CSV record parser
A line contains a student record: Name,Roll,Marks1,Marks2,Marks3. Split it on commas, then print the name, the total, the average, and the letter grade using the grading rules from Lab 3.
Sample Execution:
Enter record: Priya Shah,U23CS045,78,91,66
Name : Priya Shah
Roll : U23CS045
Total: 235
Avg : 78.33
Grade: Cstrtok calls, one per field. Use "," as the separator, not " ,", because the name contains a space. The marks arrive as text ("78"), so convert them with atoi. Divide by 3.0, not 3, so the average keeps its decimals.#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char grade(double avg) {
if (avg >= 90) return 'A';
if (avg >= 80) return 'B';
if (avg >= 70) return 'C';
if (avg >= 60) return 'D';
return 'F';
}
int main(void) {
char line[200];
printf("Enter record: ");
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
char *name = strtok(line, ",");
char *roll = strtok(NULL, ",");
char *m1 = strtok(NULL, ",");
char *m2 = strtok(NULL, ",");
char *m3 = strtok(NULL, ",");
if (m3 == NULL) {
printf("Expected 5 comma-separated fields\n");
return 1;
}
int total = atoi(m1) + atoi(m2) + atoi(m3);
double avg = total / 3.0;
printf("Name : %s\n", name);
printf("Roll : %s\n", roll);
printf("Total: %d\n", total);
printf("Avg : %.2f\n", avg);
printf("Grade: %c\n", grade(avg));
return 0;
}
% ./a.out
Enter record: Priya Shah,U23CS045,78,91,66
Name : Priya Shah
Roll : U23CS045
Total: 235
Avg : 78.33
Grade: C
Unpack this step: atoi, and why 3.0
atoi("78") (from <stdlib.h>) turns the text "78" into the number 78. It does the same job as Problem 4's digit loop. 235 / 3 with two ints is 78, because integer division drops the fraction. 235 / 3.0 is 78.333…, which %.2f prints as 78.33.
We don't have Lab Sheet 3, so the bands above are the common 90/80/70/60 scale. It gives C for 78.33, matching the sample. Swap in Lab 3's exact bands if they differ, since the rest of the program doesn't change. If you have your Lab 3 sheet, send it and this note will be corrected.
Tests run. A,B,1,2 (only four fields): the fifth strtok returns NULL, and the program says so instead of crashing on atoi(NULL).
Problem 7 · about 20 minutes
Find and replace
Replace every occurrence of one word with another inside a sentence. The replacement may be longer or shorter than the original.
Sample Execution:
Enter sentence: the cat sat on the mat
Find: the
Replace with: a
Result: a cat sat on a mati and write into out with k. At each position, if the find-word starts here as a whole word, copy the replacement and jump i past the old word. Otherwise copy one character. The two indexes move at different speeds, which is how "longer or shorter" takes care of itself.#include <stdio.h>
#include <string.h>
#include <stdbool.h>
/* true if find[] sits at s[i] as a whole word */
bool wordAt(const char s[], int i, const char find[], int flen) {
for (int j = 0; j < flen; j++) {
if (s[i + j] != find[j]) return false; /* stops at s's '\0' too */
}
bool startOk = (i == 0) || s[i - 1] == ' ';
bool endOk = s[i + flen] == '\0' || s[i + flen] == ' ';
return startOk && endOk;
}
int main(void) {
char s[200], find[50], rep[50], out[1000];
printf("Enter sentence: ");
fgets(s, sizeof(s), stdin); s[strcspn(s, "\n")] = '\0';
printf("Find: ");
fgets(find, sizeof(find), stdin); find[strcspn(find, "\n")] = '\0';
printf("Replace with: ");
fgets(rep, sizeof(rep), stdin); rep[strcspn(rep, "\n")] = '\0';
int flen = strlen(find), rlen = strlen(rep);
int i = 0, k = 0;
while (s[i] != '\0') {
if (flen > 0 && wordAt(s, i, find, flen)) {
for (int j = 0; j < rlen; j++) out[k++] = rep[j]; /* copy the replacement */
i += flen; /* skip the old word */
} else {
out[k++] = s[i++]; /* copy one character */
}
}
out[k] = '\0';
printf("Result: %s\n", out);
return 0;
}
% ./a.out
Enter sentence: the cat sat on the mat
Find: the
Replace with: a
Result: a cat sat on a mat
% ./a.out
Enter sentence: then the other theme
Find: the
Replace with: THE BIG
Result: then THE BIG other theme
Why "whole word". The sheet says "word". A plain substring replace would turn then into an and other into oar. The startOk/endOk tests check for a space or the string's end on both sides. If your instructor wants substring replacement, delete those two lines. Either way, state your choice in a comment, because the sheet's sample can't tell the two versions apart.
The comparison loop in wordAt is safe near the end of the sentence. If s runs out, s[i + j] is '\0', which doesn't match any letter of find, so the loop returns false before reading past the end.
Problem 8 · about 25 minutes (mostly reused code)
Text utility menu
A menu-driven program using switch that reads one line of text and then repeatedly offers:
1. Reverse the text
2. Convert to UPPERCASE
3. Count words
4. Remove all vowels
5. Check palindrome
6. Enter new text
0. ExitEach option must be implemented as its own function.
You have already written most of these earlier in the lab. This problem is about collecting them into named functions and driving them from one menu, not about solving them again.
Sample Execution: the menu above, then
Enter text: hello
Select option: 1
Result: ollehreverse = Debug 1 fixed. toUpperCase and countWords = sheet §9 and §15. isPalindrome = sheet §13 with break turned into return false. removeVowels is the only new one. It uses a "keep" index k that copies only consonants forward, the same two-speed idea as Problem 7. The loop is a do … while (choice != 0), and the getchar line from section 1 D sits after the scanf, because option 6 calls fgets.#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
void readText(char s[], int size) {
printf("Enter text: ");
fgets(s, size, stdin);
s[strcspn(s, "\n")] = '\0';
}
void reverse(char s[]) {
int len = strlen(s);
for (int i = 0; i < len / 2; i++) {
char t = s[i];
s[i] = s[len - 1 - i];
s[len - 1 - i] = t;
}
}
void toUpperCase(char s[]) {
for (int i = 0; s[i] != '\0'; i++) s[i] = toupper((unsigned char) s[i]);
}
int countWords(const char s[]) {
int words = 0;
bool inWord = false;
for (int i = 0; s[i] != '\0'; i++) {
if (isspace((unsigned char) s[i])) inWord = false;
else if (!inWord) { inWord = true; words++; }
}
return words;
}
void removeVowels(char s[]) {
int k = 0; /* where the next kept char goes */
for (int i = 0; s[i] != '\0'; i++) {
char l = tolower((unsigned char) s[i]);
if (l != 'a' && l != 'e' && l != 'i' && l != 'o' && l != 'u') s[k++] = s[i];
}
s[k] = '\0';
}
bool isPalindrome(const char s[]) {
int left = 0, right = strlen(s) - 1;
while (left < right) {
while (left < right && !isalnum((unsigned char) s[left])) left++;
while (left < right && !isalnum((unsigned char) s[right])) right--;
if (tolower((unsigned char) s[left]) != tolower((unsigned char) s[right])) return false;
left++;
right--;
}
return true;
}
void printMenu(void) {
printf("1. Reverse the text\n2. Convert to UPPERCASE\n3. Count words\n");
printf("4. Remove all vowels\n5. Check palindrome\n6. Enter new text\n0. Exit\n");
}
int main(void) {
char text[200], work[200];
int choice;
printMenu();
readText(text, sizeof(text));
do {
printf("Select option: ");
if (scanf("%d", &choice) != 1) break;
while (getchar() != '\n'); /* throw away the rest of the line */
strcpy(work, text); /* options 1, 2, 4 change a copy */
switch (choice) {
case 1: reverse(work); printf("Result: %s\n", work); break;
case 2: toUpperCase(work); printf("Result: %s\n", work); break;
case 3: printf("Result: %d\n", countWords(text)); break;
case 4: removeVowels(work); printf("Result: %s\n", work); break;
case 5: printf("Result: %s\n", isPalindrome(text) ? "Palindrome" : "Not a Palindrome"); break;
case 6: readText(text, sizeof(text)); break;
case 0: printf("Bye\n"); break;
default: printf("No such option\n");
}
} while (choice != 0);
return 0;
}
% ./a.out
1. Reverse the text
2. Convert to UPPERCASE
3. Count words
4. Remove all vowels
5. Check palindrome
6. Enter new text
0. Exit
Enter text: hello
Select option: 1
Result: olleh
Select option: 2
Result: HELLO
Select option: 3
Result: 1
Select option: 4
Result: hll
Select option: 5
Result: Not a Palindrome
Select option: 6
Enter text: Never odd or even
Select option: 5
Result: Palindrome
Select option: 3
Result: 4
Select option: 0
Bye
A design choice to state. Options 1, 2 and 4 work on a copy (work). That way hello reversed and then uppercased gives HELLO, not OLLEH. The sheet doesn't say which it wants. Either is fine if you say so in a comment. Delete the getchar line and option 6 breaks: fgets reads the leftover newline and the "new text" is empty.
5 · Challenge · breaking the Caesar cipher
A Caesar cipher has only 25 useful keys, which makes it easy to encrypt — and, it turns out, easy to break. You are given a message that someone encrypted with a Caesar cipher, but you are not given the key.
You could decrypt with all 25 possible shifts and read them yourself to see which one is English. Your task is to make the program do the reading for you.
The idea is statistical. In ordinary English text, ‘e’ is by far the most common letter, followed by ‘t’ and ‘a’. A wrong shift scrambles those proportions; the right shift restores them. So for each of the 25 candidate shifts, decrypt the message, measure how closely its letter frequencies match English, and report the shift that fits best.
Enter encrypted text: wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj
Best shift (encryption key): 3
Decrypted: the quick brown fox jumps over the lazy dogThink Before You Code. 1. If a message was encrypted with shift k, what shift decrypts it? 2. How will you measure "how English does this look" as a single number, so that the program can compare 25 candidates? 3. Should you compare raw counts or percentages? What changes if the message is 20 characters instead of 2000? 4. Which candidate wins — the highest score or the lowest? 5. What happens to your measurement if the message contains no letters at all?
The five questions answered first, as the sheet insists:
- Shift −k, or equivalently 26 − k. The sheet's
caesar(text, -key)in §14 already does it. - One number: the chi-squared score. For each letter, take the count you got, subtract the count English would predict, square it, and divide by the predicted count. Then add up all 26 of these. It's 0 for a perfect match and grows as the text looks less like English.
- Percentages, scaled to this message. A 20-letter message can't have 12.7 e's, and a 2000-letter one would dwarf any table of raw counts. So convert the English percentages to expected counts for this length:
expected = percent / 100 × letters. - The lowest, because chi-squared measures distance from English. The code says
if (sc < bestScore), and getting that the wrong way round always picks the worst shift. - Every expected count becomes 0, and the score becomes 0/0. Check for "no letters" first and say so.
Unpack this step: why square the difference, and why divide?
Squaring makes "3 too many" and "3 too few" count the same, instead of cancelling out. Dividing by the expected count makes a miss on a rare letter matter more. Being 3 off on z (expected 0.07) is far stranger than being 3 off on e (expected 12.7).
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* percentage of each letter a..z in ordinary English text */
const double ENGLISH[26] = {
8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.15, 0.77, 4.0, 2.4,
6.7, 7.5, 1.9, 0.095, 6.0, 6.3, 9.1, 2.8, 0.98, 2.4, 0.15, 2.0, 0.074
};
char shiftChar(char c, int shift) {
if (islower((unsigned char) c)) return 'a' + ((c - 'a' + shift) % 26 + 26) % 26;
if (isupper((unsigned char) c)) return 'A' + ((c - 'A' + shift) % 26 + 26) % 26;
return c;
}
/* how un-English is the text after shifting by 'shift'? smaller = more English */
double score(const char s[], int shift) {
int count[26] = {0};
int letters = 0;
for (int i = 0; s[i] != '\0'; i++) {
char c = shiftChar(s[i], shift);
if (isalpha((unsigned char) c)) {
count[tolower((unsigned char) c) - 'a']++;
letters++;
}
}
double total = 0;
for (int i = 0; i < 26; i++) {
double expected = ENGLISH[i] / 100.0 * letters; /* percentages, scaled to this length */
double diff = count[i] - expected;
total += diff * diff / expected; /* chi-squared */
}
return total;
}
int countLetters(const char s[]) {
int n = 0;
for (int i = 0; s[i] != '\0'; i++) if (isalpha((unsigned char) s[i])) n++;
return n;
}
int main(void) {
char text[500];
printf("Enter encrypted text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0';
if (countLetters(text) == 0) {
printf("No letters: nothing to measure\n");
return 0;
}
int bestKey = 1;
double bestScore = score(text, -1);
for (int key = 2; key <= 25; key++) {
double sc = score(text, -key); /* encrypted with key k -> decrypt with -k */
if (sc < bestScore) { /* LOWEST wins */
bestScore = sc;
bestKey = key;
}
}
for (int i = 0; text[i] != '\0'; i++) text[i] = shiftChar(text[i], -bestKey);
printf("Best shift (encryption key): %d\n", bestKey);
printf("Decrypted: %s\n", text);
return 0;
}
% ./a.out
Enter encrypted text: wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj
Best shift (encryption key): 3
Decrypted: the quick brown fox jumps over the lazy dog
Tests run. 123 !! → No letters: nothing to measure. We also encrypted "Meet me at the library at noon" with key 10 using the sheet's own Caesar program, and the breaker recovered 10. "Programming in C is fun once you get the hang of it" with keys 1, 5, 13 and 25 was recovered correctly every time. Very short messages can fool it (two or three words carry too little statistics), which is worth saying if asked.
6 · Advanced · the Archivist's grid
A damaged manuscript has been digitized as an n × n grid of single letters. Scholars believe a codeword was hidden inside it, written in a straight line in any of the eight compass directions — left to right, right to left, top to bottom, bottom to top, or along any of the four diagonals.
Write a program that reads n, reads the grid, reads a codeword, and reports every place the codeword appears: the starting row and column (counting from 0) and the direction. If it appears nowhere, print NOT FOUND.
Enter n: 5
Enter grid:
C O D E X
A B C D E
T R E E S
S U N N Y
M A P L E
Enter codeword: CAT
Found at (0,0) going downk at (r + k·dr, c + k·dc) for every start cell and every direction. That gives one loop instead of eight copy-pasted blocks.CAT runs down column 0 from (0,0). Right: each direction is a (row step, column step) pair. Rows grow downwards, so "up" is −1.#include <stdio.h>
#include <string.h>
#define MAX 20
int main(void) {
char g[MAX][MAX];
char word[MAX + 1];
int n;
/* the eight directions as (row step, column step) */
int dr[8] = { 0, 0, 1, -1, 1, 1, -1, -1};
int dc[8] = { 1, -1, 0, 0, 1, -1, 1, -1};
const char *name[8] = {"right", "left", "down", "up",
"down-right", "down-left", "up-right", "up-left"};
printf("Enter n: ");
scanf("%d", &n);
printf("Enter grid:\n");
for (int r = 0; r < n; r++)
for (int c = 0; c < n; c++)
scanf(" %c", &g[r][c]); /* the space skips blanks and newlines */
printf("Enter codeword: ");
scanf("%20s", word);
int len = strlen(word);
int found = 0;
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
for (int d = 0; d < 8; d++) {
int k = 0;
while (k < len) {
int rr = r + k * dr[d], cc = c + k * dc[d];
if (rr < 0 || rr >= n || cc < 0 || cc >= n) break; /* fell off the grid */
if (g[rr][cc] != word[k]) break;
k++;
}
if (k == len) {
printf("Found at (%d,%d) going %s\n", r, c, name[d]);
found++;
}
}
}
}
if (found == 0) printf("NOT FOUND\n");
return 0;
}
% ./a.out
Enter n: 5
Enter grid:
C O D E X
A B C D E
T R E E S
S U N N Y
M A P L E
Enter codeword: CAT
Found at (0,0) going down
Tests run. TREES → (2,0) going right. DOG → NOT FOUND. EE → six hits. A two-letter word that reads the same both ways (a palindrome) is found twice per pair, once in each direction: (2,2) right and (2,3) left. The sheet says "every place". If your instructor wants each placement once, say so and drop one direction of each pair. The scanf(" %c") with a leading space skips the blanks and newlines between letters, which is why the grid can be typed with spaces.
7 · Bonus challenges, briefly
All four compiled and tested. Each idea fits in one sentence, so the code is folded. Try each one yourself first.
1 · Text detective
Read one line and report: whether it is a pangram (uses every letter of the alphabet), how many sentences it contains, the longest word, the average word length, and the least frequent letter that still appears at least once.
Idea: one pass with a frequency array, as in sheet §16. A "word" is a run of letters, so remember where the current run started, and when it ends, compare its length with the best so far. Count . ! ? as sentence ends. The loop runs one extra step onto the '\0' so the last word gets closed.
The compiled program and its run
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(void) {
char s[500];
printf("Enter text: ");
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int freq[26] = {0}, sentences = 0, words = 0, letterTotal = 0;
int bestStart = 0, bestLen = 0, start = 0, wlen = 0;
for (int i = 0; ; i++) {
char c = s[i];
if (isalpha((unsigned char) c)) {
freq[tolower((unsigned char) c) - 'a']++;
if (wlen == 0) start = i;
wlen++;
letterTotal++;
} else {
if (wlen > 0) { /* a word just ended */
words++;
if (wlen > bestLen) { bestLen = wlen; bestStart = start; }
wlen = 0;
}
if (c == '.' || c == '!' || c == '?') sentences++;
}
if (c == '\0') break;
}
bool pangram = true;
int least = -1;
for (int i = 0; i < 26; i++) {
if (freq[i] == 0) pangram = false;
else if (least == -1 || freq[i] < freq[least]) least = i;
}
printf("Pangram: %s\n", pangram ? "yes" : "no");
printf("Sentences: %d\n", sentences);
printf("Longest word: ");
for (int j = 0; j < bestLen; j++) putchar(s[bestStart + j]);
printf("\n");
printf("Average word length: %.2f\n", words ? (double) letterTotal / words : 0.0);
if (least != -1) printf("Least frequent letter: %c (%d)\n", 'a' + least, freq[least]);
return 0;
}
% ./a.out
Enter text: The quick brown fox jumps over the lazy dog. Pack my box!
Pangram: yes
Sentences: 2
Longest word: quick
Average word length: 3.67
Least frequent letter: d (1)
Ties: quick, brown and jumps are all 5 letters, and the first one wins because the test is >, not >=. Average word length = 44 letters / 12 words = 3.67.
2 · Number to words
Convert an integer up to 9999 into English: 3421 → three thousand four hundred twenty one.
Idea: split the number into thousands, hundreds and the last two digits (/ 1000, / 100 % 10, % 100). Store the words in two arrays of strings: 0–19 (these are irregular) and the tens. Below 20, look the number up directly. From 20 up, print tens then ones.
The compiled program and its run
#include <stdio.h>
const char *ones[] = {"zero", "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen",
"fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
const char *tens[] = {"", "", "twenty", "thirty", "forty", "fifty",
"sixty", "seventy", "eighty", "ninety"};
int main(void) {
int n;
printf("Enter a number (0-9999): ");
scanf("%d", &n);
if (n < 0 || n > 9999) { printf("Out of range\n"); return 0; }
if (n == 0) { printf("zero\n"); return 0; }
int th = n / 1000, h = n / 100 % 10, rest = n % 100;
int printed = 0; /* to put spaces between parts */
if (th > 0) { printf("%s thousand", ones[th]); printed = 1; }
if (h > 0) { printf("%s%s hundred", printed ? " " : "", ones[h]); printed = 1; }
if (rest > 0) {
if (printed) printf(" ");
if (rest < 20) printf("%s", ones[rest]);
else {
printf("%s", tens[rest / 10]);
if (rest % 10 > 0) printf(" %s", ones[rest % 10]);
}
}
printf("\n");
return 0;
}
% ./a.out
Enter a number (0-9999): 3421
three thousand four hundred twenty one
Also tested: 0 → zero, 15 → fifteen, 100 → one hundred, 1010 → one thousand ten, 2005 → two thousand five, 70 → seventy, 9999 → nine thousand nine hundred ninety nine. The printed flag stops a stray leading space when the thousands part is missing.
3 · Anagram checker
Read two lines and decide whether they are anagrams of each other — the same letters in a different order. Ignore case, spaces and punctuation, so Dormitory and Dirty Room count as anagrams. Build a frequency array for each and compare them.
Idea: exactly what the sheet says. One function fills a 26-box count array from a string. Call it twice and compare the arrays box by box. Arrays are passed to functions by location, so the function fills the caller's array directly.
The compiled program and its run
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
void countLetters(const char s[], int freq[]) {
for (int i = 0; i < 26; i++) freq[i] = 0;
for (int i = 0; s[i] != '\0'; i++)
if (isalpha((unsigned char) s[i])) freq[tolower((unsigned char) s[i]) - 'a']++;
}
int main(void) {
char a[200], b[200];
int fa[26], fb[26];
printf("First: "); fgets(a, sizeof(a), stdin);
printf("Second: "); fgets(b, sizeof(b), stdin);
countLetters(a, fa);
countLetters(b, fb);
bool same = true;
for (int i = 0; i < 26; i++) if (fa[i] != fb[i]) same = false;
printf(same ? "Anagrams\n" : "Not anagrams\n");
return 0;
}
% ./a.out
First: Dormitory
Second: Dirty Room
Anagrams
Also: Listen! / Silent → Anagrams. abc / abd → Not anagrams.
4 · Morse decoder
Given a line of Morse code where letters are separated by single spaces and words by a forward slash, decode it back into text. Store the 26 letter patterns in a 2D char array indexed by letter - 'a'.
Idea: collect dots and dashes into a small buffer. When a space, a / or the end arrives, close the buffer with '\0' and look it up with strcmp against the 26 patterns. The index of the match + 'a' is the letter. A / also prints a space.
The compiled program and its run
#include <stdio.h>
#include <string.h>
char morse[26][5] = {
".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--", "--.."
};
char decodeLetter(const char code[]) {
for (int i = 0; i < 26; i++)
if (strcmp(code, morse[i]) == 0) return 'a' + i;
return '?';
}
int main(void) {
char line[500], code[10];
printf("Enter Morse: ");
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
int k = 0; /* length of the code being collected */
for (int i = 0; ; i++) {
char c = line[i];
if (c == '.' || c == '-') {
if (k < 9) code[k++] = c;
} else { /* space, slash or end: letter is done */
if (k > 0) {
code[k] = '\0';
putchar(decodeLetter(code));
k = 0;
}
if (c == '/') putchar(' ');
if (c == '\0') break;
}
}
printf("\n");
return 0;
}
% ./a.out
Enter Morse: .... . .-.. .-.. --- / .-- --- .-. .-.. -..
hello world
Each row is 5 boxes because the longest pattern has 4 symbols, plus '\0'. This is Dry run 4's lesson put to use.
8 · What we found when we ran the sheet
Every sample output on the sheet was reproduced exactly. All the worked examples (§12–§19) compile without warnings and do what the sheet claims. char *d = "Hello"; d[0] = 'J'; really does compile and then crash: on a Mac the program dies with a bus error. Points worth knowing:
- Dry run 4's declaration is broken (no room for
'\0'in"three"). The printed answer comes out right only by luck. See above. - Dry run 3's values aren't fixed. The same comparison gives −1 or −2 on the same machine depending on how it's written. Only the sign is reliable. See above.
- Problem 6 needs Lab 3's grading rules, which aren't in our files. We used a 90/80/70/60 scale, which matches the sample's C.
- Three problems leave a choice open: whole-word or substring replace (P7), whether menu options change the stored text (P8), and whether a palindromic codeword counts once or twice (grid). In a lab evaluation, pick one and state it in a comment.
- §4's memory picture shows
?after"Amit\0". That's true only for an array that was never initialised.char name[10] = "Amit";fills boxes 5–9 with'\0', the same correction as Lecture 9's slide 5 on the strings notes. - Debugging exercises 2 and 3 compile with warnings under
-Wall -Wextra(sign comparison, ignoredtoupperresult). Compile with those flags in the lab. The compiler finds half of Exercise 3 for you.