CS U111 · Lab-eval ladder · Stage 4
Strings: from counting vowels to parsing input
Twenty-one problems in four rungs, each set up like a Moodle VPL lab evaluation: the program reads silently, prints only the answer, and has 5 test cases. The page opens with the four input-reading facts that decide most string programs. Every solution was compiled with clang -Wall -Wextra -std=c11 (zero warnings), and every expected output was produced by running it.
What this stage covers: Lab Sheet 7 (strings): walking a string to its '\0', <ctype.h> tests, frequency arrays, two pointers, words, and turning text into numbers. None of the problems here is on the sheet; the sheet's own problems are solved on Lab 7 solutions.
What the rungs mean: A · Warm-up is one idea per program. A+ · Input patterns drills the three ways a string eval can hand you input (one word, one line, a number then a line). B · VPL level is five short problems built like the real evals; B is calibrated against the instructor's real evals in the lab-eval bank. C · Beyond the eval is optional: the older, longer problems.
An honest caveat: no real strings lab evaluation has been released yet. The 28 we have cover if/else, loops and functions. So the format here is modelled on the real evals, and the difficulty is our estimate.
A fact about the gap: strings are new to the whole batch. Lecture 9 and Lab 7 were everyone's first contact with fgets, '\0' and <ctype.h>. Only the loop habits from Stages 1–3 carry over, and you have already practised those.
Time budget: the core is about 2¾ hours: input section 20 min, Rung A 30 min, Rung A+ 20 min, Rung B about 1½ h. Split it over two evenings (input + A + A+, then B). Rung C is about 3½ hours more, only if time allows.
How to use it: read the problem, then open an empty file and start. Open Stuck? First move only after 3–4 minutes of not knowing how to begin. Open Plan only if the first move wasn't enough. Run your program on all 5 tests before you open the solution, even if it fails some. Then compare.
Every program on this page reads its input silently and prints only the answer, exactly as VPL expects: no prompt lines asking for input, no debug prints. Each card has 5 tests, compared the way VPL compares (spaces, newlines and letter case are ignored; words and numbers must match). Check one test with Copy input → run your program → paste your output → Check. Or press Download test script, save it next to your .c file and run sh s4-b1-tests.sh b1.c in Terminal to run all five at once (it compiles with cc -Wall -Wextra). The full explanation is in Stage 0. An empty Input box means that test is one empty line.
Input first: where string lab evals are actually lost
In a VPL evaluation the input comes from a test file. If your program reads it wrong, nothing after that matters: the logic can be perfect and every test still fails. There are four facts to learn here, and each one comes with a real run. The runs below show what was on standard input (stdin, what VPL feeds in) and what the program printed (stdout, what VPL compares). The full teaching version is in the strings lesson, section 4.
1 · scanf("%s") stops at the first space
#include <stdio.h>
int main(void) {
char name[50];
scanf("%49s", name);
printf("Stored: [%s]\n", name);
return 0;
}
stdin │ Sardar Patel
stdout │ Stored: [Sardar]
%s reads one word. Use it only when the spec promises a single word with no spaces. Even then, write a width, as in %49s for a 50-char array, so a long word can't overflow the array. No & is needed before an array name.
2 · fgets reads the whole line, and keeps the newline
#include <stdio.h>
#include <string.h>
int main(void) {
char city[50];
fgets(city, sizeof(city), stdin);
printf("Before: [%s] length %d\n", city, (int) strlen(city));
city[strcspn(city, "\n")] = '\0';
printf("After: [%s] length %d\n", city, (int) strlen(city));
return 0;
}
stdin │ Surat
stdout │ Before: [Surat
│ ] length 6
│ After: [Surat] length 5
The first print shows the closing bracket on the next line: the string is "Surat\n", 6 characters. The line s[strcspn(s, "\n")] = '\0'; fixes it. strcspn(s, "\n") returns the index of the first '\n' (or the length, if there is none), and writing '\0' there ends the string one character earlier. Write this line straight after every fgets. If you leave it out, strcmp(city, "Surat") is never 0, the length is one too many, and a palindrome check compares '\n' with the first letter.
3 · scanf("%d") followed by fgets: the leftover newline
#include <stdio.h>
#include <string.h>
int main(void) {
int age;
char name[50];
scanf("%d", &age);
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("Name: [%s], age %d\n", name, age);
return 0;
}
stdin │ 18
stdin │ Asha Rao
stdout │ Name: [], age 18
The name came out empty. Here is why:
scanf("%d") takes the digits 18 and stops at the newline after them. That '\n' is still waiting, so the next fgets reads it as an empty line.Under VPL this trap is more likely, not less. The number's line and the text line arrive back to back from the test file, so fgets grabs the leftover '\n' instantly; there is no pause at a keyboard where you might notice that the program skipped a question.
The fix is to throw away the rest of the number's line before calling fgets:
#include <stdio.h>
#include <string.h>
int main(void) {
int age;
char name[50];
scanf("%d", &age);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* throw away the rest of the age line, including its newline */
}
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("Name: [%s], age %d\n", name, age);
return 0;
}
stdin │ 18
stdin │ Asha Rao
stdout │ Name: [Asha Rao], age 18
Unpack: what is while ((ch = getchar()) != '\n' && ch != EOF) doing?
getchar() reads one character. The loop keeps reading, and doing nothing with what it reads, until it has eaten the '\n'. EOF stops it if the input ends instead. ch is an int because EOF is not a char value. A single getchar(); works only when nothing follows the number on its line; the loop is safe even if the test file has 18 with trailing spaces.
The trap only appears when a number is read before a line. If the program reads the line first and the number second (as the sheet's Caesar example does), nothing goes wrong. scanf("%d") after scanf("%d") is also fine, because %d skips leading whitespace, newlines included.
4 · Cast to unsigned char before any <ctype.h> call
Write isalpha((unsigned char) s[i]), toupper((unsigned char) s[i]) and so on, every time. On this Mac (and on most lab machines) a plain char is signed. A non-English letter such as é in Café arrives as two bytes, and printed with %d they come out as -61 and -87 (a real run). The C standard says passing a negative value (other than EOF) to a ctype function is undefined behaviour. On this Mac it happens to return "not a letter", but some systems crash on it. The cast costs nothing, and it's the form the lab sheet uses.
Using scanf("%s") when the spec says "a line" or "a sentence". A hidden test will have a space in it, and your program will see only the first word. Rule of thumb: if the input could contain a space, use fgets plus the strcspn line.
Syntax you need for this stage
That's all of it. If a row is unfamiliar, the strings notes kit and lesson teach it.
| Write this | It means |
|---|---|
char s[200]; | room for 199 characters plus the '\0' |
fgets(s, sizeof(s), stdin); | read a whole line, spaces included (keeps the '\n') |
s[strcspn(s, "\n")] = '\0'; | chop off that '\n' (needs <string.h>) |
scanf("%49s", w); | read one word, no spaces, at most 49 chars; no & |
for (int i = 0; s[i] != '\0'; i++) | visit every character, stop at the terminator |
int len = strlen(s); | number of characters before '\0' |
isalpha / isdigit / isspace / isalnum / isupper / islower((unsigned char) c) | true/false tests on one character (<ctype.h>) |
toupper((unsigned char) c), tolower(…) | converted letter; non-letters come back unchanged |
c - 'a' · c - '0' | letter → 0..25 (frequency index) · digit character → its value |
int freq[26] = {0}; | one counter per letter, all starting at 0 |
strcmp(a, b) == 0 | same text (never a == b) |
strcpy(dest, src); | copy text (never dest = src) |
char words[100][31]; | 100 strings of up to 30 characters each |
Rung A · Warm-up
Time box: 5–10 minutes each, about 30 minutes in all. Each trains a single idea: walk the string, test a character, change a character, read a number and then a line. If you can write all four from a blank file and pass all five tests without opening anything, skip to Rung A+.
A1 · Length by hand
Read one line of text (it may contain spaces). Without using strlen, count its characters (not counting the newline) and print Length: n.
Input One line, at most 199 characters (it may be empty).
Output Length: followed by the count.
hello world
Length: 11
Length: 0
a
Length: 5
x
Length: 1
BITS Pilani, Hyderabad
Length: 22
Stuck? First move
Declare char s[200];, read it with fgets, and write the strcspn line. Then you need one int counter starting at 0. The loop runs over positions in the string, and it stops when s[counter] is '\0'.
Plan in plain words
- Read the line; strip the newline.
- len = 0.
- While the character at position len is not the terminator, add 1 to len.
- Print len.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; /* drop the newline */
int len = 0;
while (s[len] != '\0') { /* walk until the terminator */
len++;
}
printf("Length: %d\n", len);
return 0;
}
Leaving out the strcspn line gives 12 for hello world, because the '\n' gets counted too. Every test line ends in a newline, so all five tests fail.
A2 · Count the vowels
Read one line. Count the vowels a e i o u in either case and print Vowels: n.
Input One line (it may be empty).
Output Vowels: followed by the count.
Programming in C
Vowels: 4
AEIOU aeiou
Vowels: 10
rhythm
Vowels: 0
Vowels: 0
Queue
Vowels: 4
Stuck? First move
Use the same reading code as A1. Make one counter vowels = 0 and a for loop over s[i] until '\0'. Inside it, turn the character into lowercase first, so you only have five comparisons to write instead of ten.
Plan in plain words
- Read and strip.
- For each character: lowercase it; if it is one of a, e, i, o, u, add 1.
- Print the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int vowels = 0;
for (int i = 0; s[i] != '\0'; i++) {
char c = tolower((unsigned char) s[i]); /* 'A' and 'a' both become 'a' */
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
printf("Vowels: %d\n", vowels);
return 0;
}
Writing if (c == 'a' || 'e' || 'i' …). A bare 'e' is a non-zero number, so the condition is always true and every character counts. Each comparison needs its own c ==.
A3 · Shout it (uppercase in place)
Read one line and convert every letter to uppercase inside the same array. Digits, spaces and punctuation stay as they are. Print Shouted: followed by the result, then on a second line Changed: followed by how many characters actually changed.
(Why the second line: VPL ignores letter case when it compares, so hello and HELLO look the same to it. The count is what lets the tests see whether your conversion really happened.)
Input One line (it may be empty).
Output Two lines: Shouted: … and Changed: n.
hello, World 42
Shouted: HELLO, WORLD 42 Changed: 9
BITS pilani
Shouted: BITS PILANI Changed: 6
Shouted: Changed: 0
ALREADY LOUD
Shouted: ALREADY LOUD Changed: 0
a
Shouted: A Changed: 1
Stuck? First move
Use the same skeleton as A1/A2. Inside the loop, save the old character, then do one assignment back into the array: s[i] = toupper(…). You don't need an if for the conversion, because toupper returns non-letters unchanged. Then compare s[i] with the saved character.
Plan in plain words
- Read and strip; changed = 0.
- For each position i: remember s[i]; replace s[i] by its uppercase version; if it differs from what you remembered, add 1 to changed.
- Print the whole string once, after the loop, then the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int changed = 0;
for (int i = 0; s[i] != '\0'; i++) {
char old = s[i];
s[i] = toupper((unsigned char) s[i]); /* assign it back; non-letters stay */
if (s[i] != old) {
changed++; /* this character really changed */
}
}
printf("Shouted: %s\n", s);
printf("Changed: %d\n", changed);
return 0;
}
Calling toupper(s[i]); on its own line does nothing. It returns the new character and never changes s[i]. You must assign the result back. (This is the sheet's "discarded return value" bug.) Here it shows up as Changed: 0 on Tests 1, 2 and 5.
A4 · A number, then a line
Read an integer k (0 ≤ k ≤ 20) on the first line, then a line of text (it may contain spaces). Print the text k times, each copy on its own line, numbered as 1: text, 2: text, …. For k = 0 print nothing.
Input Line 1: k. Line 2: the text.
Output k numbered lines. (Test 5 has spaces after the number on line 1.)
3 good morning
1: good morning 2: good morning 3: good morning
2 Sardar Patel
1: Sardar Patel 2: Sardar Patel
0 nothing
1 x
1: x
1 end of input
1: end of input
Stuck? First move
Use scanf("%d", &k);, then the getchar loop from fact 3, then fgets + strcspn. The printing is an ordinary counting loop for (int i = 1; i <= k; i++).
Plan in plain words
- Read k.
- Throw away the rest of that line, newline included.
- Read the text line; strip its newline.
- Repeat k times: print the number, a colon, the text.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
int k;
char line[200];
scanf("%d", &k);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* eat the rest of the number's line, newline included */
}
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = '\0';
for (int i = 1; i <= k; i++) {
printf("%d: %s\n", i, line);
}
return 0;
}
Without the getchar loop, the program prints 1:, 2:, 3: with empty text. It compiles cleanly, so only testing catches it. A single getchar(); passes Tests 1–4 and fails Test 5, where spaces follow the number.
Rung A+ · Input patterns
Time box: 5–8 minutes each, about 20 minutes in all. These three train nothing but the input shape. A string eval will hand you one of three things: a single word, a whole line, or a number followed by a line. Each problem below is the smallest program that gets one of them right, with tests aimed at the way it breaks (an empty line, a one-character word, spaces after a number).
A+1 · One word, backwards
Read one word (no spaces, at most 30 characters) and print it backwards.
Input One word.
Output The word with its characters in reverse order.
hello
olleh
a
a
racecar
racecar
ab
ba
C2026
6202C
Stuck? First move
char w[31]; and scanf("%30s", w);: width 30 leaves room for the '\0', and there is no & before an array. The last character is at index strlen(w) - 1, the first at index 0.
Plan in plain words
- Read the word.
- For i from length − 1 down to 0 (inclusive): print w[i].
- Print a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
char w[31];
scanf("%30s", w); /* one word; width 30 leaves room for '\0'; no & */
int len = (int) strlen(w);
for (int i = len - 1; i >= 0; i--) { /* last index is len - 1; stop after index 0 */
putchar(w[i]);
}
printf("\n");
return 0;
}
Writing the loop as i > 0 instead of i >= 0, which drops the first letter: hello becomes olle, and the one-letter word a prints nothing at all (Test 2). Starting at i = len instead of len - 1 prints the '\0' first.
A+2 · One whole line: length and spaces
Read one line (it may contain spaces, or be empty). Print two numbers on one line: its length in characters (not counting the newline), then how many of those characters are spaces.
Input One line, at most 199 characters.
Output Two integers: length, spaces.
hello world
11 1
0 0
3 3
x
1 0
a b c
6 3
Stuck? First move
fgets(s, sizeof(s), stdin); and, on the very next line, s[strcspn(s, "\n")] = '\0';. After that, strlen is safe and a loop counts the spaces.
Plan in plain words
- Read the line; strip the newline.
- Walk it, adding 1 for each
' '. - Print strlen and the count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0'; /* without this, the length is one too many */
int spaces = 0;
for (int i = 0; s[i] != '\0'; i++) {
if (s[i] == ' ') spaces++;
}
printf("%d %d\n", (int) strlen(s), spaces);
return 0;
}
Leaving out the strcspn line makes every length one too many (12 1 for Test 1). Using scanf("%s") instead fails Tests 1, 3 and 5: it stops at the first space, and a line of only spaces leaves it waiting for a word that never comes.
A+3 · A number, then a line: age and name
Read an age (a whole number) on the first line, then a full name on the second line (it may contain spaces). Print the name on one line, then ADULT if the age is 18 or more, otherwise MINOR.
Input Line 1: the age. Line 2: the name. (Test 5 has spaces after the age.)
Output The name, then ADULT or MINOR.
18 Asha Rao
Asha Rao ADULT
17 X
X MINOR
0 New Born
New Born MINOR
45 Sardar Vallabhbhai Patel
Sardar Vallabhbhai Patel ADULT
18 R K Narayan
R K Narayan ADULT
Stuck? First move
Three reading lines in this order: scanf("%d", &age);, the while ((ch = getchar()) != '\n' && ch != EOF) loop from fact 3, then fgets + strcspn. The rest is one if.
Plan in plain words
- Read the age.
- Throw away the rest of that line, newline included.
- Read the name line; strip it.
- Print the name; print ADULT if age ≥ 18, else MINOR.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
int age;
char name[100];
scanf("%d", &age);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* throw away the rest of the age line */
}
fgets(name, sizeof(name), stdin);
name[strcspn(name, "\n")] = '\0';
printf("%s\n", name);
if (age >= 18) printf("ADULT\n");
else printf("MINOR\n");
return 0;
}
No getchar loop at all: the name is empty on every test, and only ADULT/MINOR is printed. A single getchar(); is better but still fails Test 5: it eats one of the spaces after 18, and fgets then reads the remaining spaces as the "name".
Rung B · VPL level
Time box: 15–20 minutes each, about 1½ hours for all five. These are built like the real lab evals: input on stdin, one short answer on stdout (plain numbers or UPPERCASE words), 5 tests aimed at the edges, and 5–15 lines of logic. They train what a VPL test punishes: the wrong reading function, an off-by-one at a boundary, and a rule checked in the wrong order. No real strings eval has been released yet, so the format is modelled on the 28 real evals in the lab-eval bank and the difficulty is our estimate. The checker ignores spacing, as VPL does, so none of these depends on exact spaces.
B1 · Four kinds of character
Read one line of text. Count its uppercase letters, lowercase letters, digits, and all other characters (spaces and punctuation count as "other"; the newline does not count). Print the four counts in that order.
Input One line, at most 299 characters (it may be empty).
Output Four integers on one line: uppercase, lowercase, digits, others.
Hello World 42!
2 8 2 3
0 0 0 0
ABC
3 0 0 0
a1 B2-c3
1 2 3 2
0 0 0 3
Stuck? First move
The input can contain spaces, so read it with fgets and strip the newline. Four int counters at 0, one loop, and inside it one if / else if / else if / else chain, so every character lands in exactly one counter.
Plan in plain words
- Read and strip.
- For each character: uppercase → upper + 1; else lowercase → lower + 1; else digit → digits + 1; else others + 1.
- Print the four counts.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[300];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int upper = 0, lower = 0, digits = 0, others = 0;
for (int i = 0; s[i] != '\0'; i++) {
unsigned char c = (unsigned char) s[i];
if (isupper(c)) upper++;
else if (islower(c)) lower++;
else if (isdigit(c)) digits++;
else others++; /* spaces and punctuation land here */
}
printf("%d %d %d %d\n", upper, lower, digits, others);
return 0;
}
Reading with scanf("%s"). It stops at the first space, so Test 1 sees only Hello and prints 1 4 0 0, and the all-spaces Test 5 never gets a word at all. Four of the five tests fail. The second trap is forgetting the strip: the '\n' then counts as an "other", one too many on every test.
B2 · Pangram check
A pangram is a sentence that uses every letter of the alphabet at least once, in either case. Read one line and print YES if it is a pangram, otherwise NO.
Input One line, at most 299 characters (it may be empty).
Output YES or NO.
The quick brown fox jumps over the lazy dog
YES
abcdefghijklmnopqrstuvwxy
NO
ABCDEFGHIJKLMNOPQRSTUVWXYZ
YES
NO
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
NO
Stuck? First move
Make int seen[26] = {0};. For every letter, set seen[tolower(c) - 'a'] = 1. After the loop, the line is a pangram exactly when all 26 entries are 1.
Plan in plain words
- Read and strip; all 26 flags 0.
- For each character that is a letter: lowercase it and set its flag.
- Count the flags still 0. None → YES; otherwise NO.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[300];
int seen[26] = {0}; /* seen[0] for a, ..., seen[25] for z */
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
for (int i = 0; s[i] != '\0'; i++) {
if (isalpha((unsigned char) s[i])) {
seen[tolower((unsigned char) s[i]) - 'a'] = 1;
}
}
int missing = 0;
for (int j = 0; j < 26; j++) {
if (!seen[j]) missing++;
}
if (missing == 0) printf("YES\n");
else printf("NO\n");
return 0;
}
Counting letters and checking "at least 26". Thirty as pass that test and are not a pangram (Test 5). The question is which letters appeared, not how many. Leaving out tolower is worse: 'A' - 'a' is −32, an index outside the array (Test 3).
B3 · Compress the runs
Read one word made of lowercase letters. Replace every run of the same letter by the letter followed by the run's length, with nothing in between: aaabccdddd becomes a3b1c2d4. A letter that appears again later starts a new run.
Input One word, 1 to 50 lowercase letters.
Output The compressed word, as one token (no spaces).
aaabccdddd
a3b1c2d4
z
z1
abc
a1b1c1
bbbbbbbbbbbb
b12
aabbaa
a2b2a2
Stuck? First move
The input is one word, so scanf("%50s", w) is right here. Use one index i for the whole word. Each round of the outer loop takes c = w[i] and runs an inner loop while (w[i] == c) that counts and moves i forward. When it stops, i is already on the next run.
Plan in plain words
- Read the word; i = 0.
- While w[i] is not '\0': c = w[i]; run = 0; while w[i] == c, add 1 to run and to i; print c and run.
- Print a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
char w[51];
scanf("%50s", w);
int i = 0;
while (w[i] != '\0') {
char c = w[i];
int run = 0;
while (w[i] == c) { /* count this run; stops at a new letter or '\0' */
run++;
i++;
}
printf("%c%d", c, run); /* no space: the answer is one token */
}
printf("\n");
return 0;
}
Unpack: why does the inner loop stop at the end of the word?
At the end, w[i] is '\0', which is never equal to a letter c, so while (w[i] == c) is false. The outer test w[i] != '\0' then ends the whole loop.
Counting each letter's total with a frequency array. That turns aabbaa into a4b2, but the runs are a2b2a2 (Test 5). Second trap: printing a space between pairs. VPL ignores how much space there is, not whether there is any: a3 b1 is two tokens, the expected answer is one, and every test fails.
B4 · Long words
Read a whole number K (K ≥ 1) on the first line, then a line of text. Words are separated by one or more spaces, and there may be spaces at either end. Print how many words have at least K characters.
Input Line 1: K. Line 2: the text (it may be empty).
Output One integer.
4 an apple a day keeps the doctor away
4
3
0
1 hello world
2
5 hello
1
6 hello world
0
Stuck? First move
Reading: scanf, the getchar loop, fgets, strcspn, in that order (A+3). Counting: keep len, the length of the word you are inside. A non-space adds 1 to it. A space or the terminator means a word may have just ended: check len >= k, then reset len to 0.
Plan in plain words
- Read K; eat the rest of its line; read the text line; strip.
- count = 0, len = 0. Walk every character, including the final '\0':
space or '\0' → if len ≥ K, count + 1; len = 0; stop if it was '\0';
anything else → len + 1. - Print count.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
int k;
char s[300];
scanf("%d", &k);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* the line comes straight after the number: eat its newline */
}
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int count = 0, len = 0; /* len = letters in the current word so far */
for (int i = 0; ; i++) {
if (s[i] == ' ' || s[i] == '\0') {
if (len >= k) count++; /* a word just ended */
len = 0;
if (s[i] == '\0') break;
} else {
len++;
}
}
printf("%d\n", count);
return 0;
}
Three ways to lose marks here, each caught by a test. No getchar loop: the line reads as empty and Tests 1, 3 and 4 print 0. Writing len > k: away in Test 1 and hello in Test 4 sit exactly on the boundary. Checking the length only when you meet a space: the last word of a line usually has no space after it, so Test 4 prints 0.
B5 · Username check
Read a proposed username as a whole line. Check these rules in this order and print the message for the first rule broken:
- Length 5 to 12 characters, else
INVALID LENGTH. - The first character is a letter, else
INVALID START. - Every character is a letter, a digit or an underscore
_, elseINVALID CHARACTER. - At least one digit, else
INVALID DIGIT.
If no rule is broken, print VALID.
Input One line, at most 99 characters (it may be empty or contain spaces).
Output VALID, or INVALID followed by one reason word.
coder_42
VALID
ab cd12
INVALID CHARACTER
INVALID LENGTH
9 lives
INVALID START
hello_world1
VALID
Stuck? First move
Use fgets: a space must be seen so rule 3 can reject it, and scanf("%s") would quietly drop it. One loop sets two flags (badChar, hasDigit). After the loop, one if / else if ladder in the rule order decides.
Plan in plain words
- Read and strip; len = strlen.
- Loop: a digit sets hasDigit; anything not a letter, digit or '_' sets badChar.
- Ladder: bad length → LENGTH; else first not a letter → START; else badChar → CHARACTER; else no digit → DIGIT; else VALID.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char u[100];
fgets(u, sizeof(u), stdin); /* a whole line: a space must be seen, not lost */
u[strcspn(u, "\n")] = '\0';
int len = (int) strlen(u);
int badChar = 0, hasDigit = 0;
for (int i = 0; u[i] != '\0'; i++) {
unsigned char c = (unsigned char) u[i];
if (isdigit(c)) hasDigit = 1;
if (!isalnum(c) && c != '_') badChar = 1;
}
if (len < 5 || len > 12) printf("INVALID LENGTH\n"); /* rule 1 first */
else if (!isalpha((unsigned char) u[0])) printf("INVALID START\n");
else if (badChar) printf("INVALID CHARACTER\n");
else if (!hasDigit) printf("INVALID DIGIT\n");
else printf("VALID\n");
return 0;
}
Reading with scanf("%s"): ab cd12 becomes ab and the program says LENGTH instead of CHARACTER (Test 2). Checking rules out of order: 9 lives breaks rules 2 and 3, and only the first one, START, may be printed (Test 4). This is the same "rule priority" idea as the real if/else evals. The empty line (Test 3) must not touch u[0] as a letter: rule 1 catches it first.
Rung C · Beyond the eval (optional)
These are the old lab-sheet-plus-twist problems: longer than any eval we've seen. Do them after B, if time allows; they build fluency for the end-semester lab exam. Time box: C1–C5 about 20–25 minutes each, C6–C9 about 25–40 minutes each. They now read silently and have 5 tests like the rest of the page, but most of their outputs keep the old labelled wording (Result:, Words:, …), which is part of the expected output.
C1 · Palindrome, and where it breaks
Read one line. Ignoring case and every character that is not a letter or digit, decide whether it reads the same both ways. If it does, print Palindrome. If not, print the first mismatching pair, as found from the outside in and in lowercase: Not a palindrome: 'x' vs 'y'. A line with no letters or digits counts as a palindrome.
Input One line (it may be empty).
Output Palindrome, or the Not a palindrome line.
Was it a car or a cat I saw?
Palindrome
Step on no cats
Not a palindrome: 'e' vs 'a'
?!
Palindrome
Palindrome
1 2 3
Not a palindrome: '1' vs '3'
Stuck? First move
This is the sheet's §13 palindrome with one change. Use two int indices: left = 0 and right = strlen(s) - 1. The loop is while (left < right). Each pass does exactly one of three things: skip a junk character on the left, skip one on the right, or compare the two characters.
Plan in plain words
- Read and strip. left = 0, right = length − 1.
- While left < right:
if s[left] isn't a letter/digit, move left forward;
else if s[right] isn't, move right back;
else compare their lowercase versions: different → print the pair and stop; same → move both inward. - If the loop finished, print Palindrome.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int left = 0;
int right = (int) strlen(s) - 1; /* -1 for the empty string: loop never runs */
while (left < right) {
/* skip anything that is not a letter or digit, from each end */
if (!isalnum((unsigned char) s[left])) {
left++;
} else if (!isalnum((unsigned char) s[right])) {
right--;
} else {
char a = tolower((unsigned char) s[left]);
char b = tolower((unsigned char) s[right]);
if (a != b) {
printf("Not a palindrome: '%c' vs '%c'\n", a, b);
return 0; /* first mismatch: we are done */
}
left++;
right--;
}
}
printf("Palindrome\n");
return 0;
}
Unpack: why cast strlen to int?
strlen returns an unsigned type, which can't be negative. For the empty string, strlen(s) - 1 without the cast wraps round to a huge number instead of −1. With the cast, right is −1, left < right is false, and the loop never runs.
Using isalpha instead of isalnum. The spec says letters or digits, so the digits in Test 5 (1 2 1) must be compared, not skipped. Read the spec's exact words.
C2 · Words, and words that start with a vowel
Read one line. Words are separated by one or more spaces, and there may be leading or trailing spaces. Print the number of words, then how many of them start with a vowel (either case).
Input One line (it may be empty).
Output Two lines: Words: n and Starting with a vowel: m.
an apple a day keeps the doctor away
Words: 8 Starting with a vowel: 4
Words: 0 Starting with a vowel: 0
Ice cream
Words: 2 Starting with a vowel: 1
Words: 0 Starting with a vowel: 0
a
Words: 1 Starting with a vowel: 1
Stuck? First move
This is the sheet's §15 word counter. Use a bool inWord = false and two counters. The key moment is "this character is not a space and I wasn't in a word", because that's the first letter of a new word. That is the only place you need to check for a vowel.
Plan in plain words
- Read and strip; words = 0, vowelWords = 0, inWord = false.
- For each character:
space → inWord = false;
otherwise, if not inWord → a word starts here: inWord = true, words + 1, and if this character (lowercased) is a vowel, vowelWords + 1. - Print both counts.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(void) {
char s[300];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int words = 0, vowelWords = 0;
bool inWord = false;
for (int i = 0; s[i] != '\0'; i++) {
if (isspace((unsigned char) s[i])) {
inWord = false;
} else if (!inWord) { /* s[i] is the first letter of a new word */
inWord = true;
words++;
char c = tolower((unsigned char) s[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelWords++;
}
}
}
printf("Words: %d\n", words);
printf("Starting with a vowel: %d\n", vowelWords);
return 0;
}
Counting spaces and adding 1. It gives 10 words for the first test, which has 8, and 4 for a line of three spaces. The flag method is right for any spacing.
C3 · First letter that appears only once
Read one line. Considering letters only and ignoring case, print the first letter (in reading order, as lowercase) whose total count in the line is exactly 1, as First non-repeating letter: x. If none exists, print No non-repeating letter.
Input One line (it may be empty).
Output One of the two lines above.
swiss
First non-repeating letter: w
Programming
First non-repeating letter: p
aAbB cc!
No non-repeating letter
No non-repeating letter
z
First non-repeating letter: z
Stuck? First move
This is the sheet's §16 letter frequency. Use int freq[26] = {0}; and one loop that does freq[tolower(c) - 'a']++ for each letter. Then the new part: a second loop over the string (not over freq), because "first in reading order" means string order.
Plan in plain words
- Read and strip; zero the 26 counters.
- Pass 1: for every letter, add 1 to its counter.
- Pass 2: walk the string again; at the first letter whose counter is 1, print it and stop.
- If pass 2 ends without printing, print the "No …" line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[200];
int freq[26] = {0};
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
/* pass 1: count every letter */
for (int i = 0; s[i] != '\0'; i++) {
if (isalpha((unsigned char) s[i])) {
freq[tolower((unsigned char) s[i]) - 'a']++;
}
}
/* pass 2: walk the string again, in order; first count of 1 wins */
for (int i = 0; s[i] != '\0'; i++) {
if (isalpha((unsigned char) s[i])) {
char c = tolower((unsigned char) s[i]);
if (freq[c - 'a'] == 1) {
printf("First non-repeating letter: %c\n", c);
return 0;
}
}
}
printf("No non-repeating letter\n");
return 0;
}
Doing pass 2 over freq[0..25]. That finds the alphabetically first unique letter, which gives a for Programming instead of p (Test 2).
C4 · Caesar shift for letters and digits, key first
Read an integer key k (it may be negative or larger than 26) on the first line, then a message line. Shift every letter by k places within its own case, wrapping round the alphabet, and every digit by k places within 0–9, wrapping round. Leave every other character unchanged. Print Result: and the new message. A negative key undoes a positive one.
Input Line 1: k. Line 2: the message.
Output Result: followed by the shifted message.
3 Meet at 9pm, gate 7
Result: Phhw dw 2sp, jdwh 0
-3 Phhw dw 2sp, jdwh 0
Result: Meet at 9pm, gate 7
29 Zz 9
Result: Cc 8
0 abc
Result: abc
1 zZ9
Result: aA0
Stuck? First move
Two things are new compared with the sheet's §14 Caesar: the key is read before the line (so you need the getchar loop from fact 3), and digits wrap modulo 10. Write a helper char shift(char c, int k) with three ifs (lower, upper, digit) and a final return c;.
Plan in plain words
- Read k; discard the rest of that line; read the message; strip.
- For each character: lowercase → position c − 'a', add k, wrap into 0..25, back to a letter. Same for uppercase. Digit → c − '0', add k, wrap into 0..9.
- Print the message.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char shift(char c, int k) {
if (islower((unsigned char) c)) return 'a' + ((c - 'a' + k) % 26 + 26) % 26;
if (isupper((unsigned char) c)) return 'A' + ((c - 'A' + k) % 26 + 26) % 26;
if (isdigit((unsigned char) c)) return '0' + ((c - '0' + k) % 10 + 10) % 10;
return c; /* spaces, punctuation unchanged */
}
int main(void) {
int k;
char msg[200];
scanf("%d", &k);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
/* discard the rest of the key line */
}
fgets(msg, sizeof(msg), stdin);
msg[strcspn(msg, "\n")] = '\0';
for (int i = 0; msg[i] != '\0'; i++) {
msg[i] = shift(msg[i], k);
}
printf("Result: %s\n", msg);
return 0;
}
Unpack: why (x % 26 + 26) % 26 and not just x % 26?
In C, % keeps the sign of the left side, so -3 % 26 is -3, not 23. Adding 26 makes it 23 (a valid position), and the second % 26 brings positive values that went over 25 back into range. The same idea with 10 handles digits.
Without the getchar loop, Result: prints with an empty message. Without the + 26, a key of -3 turns a into a non-letter character (Test 2).
C5 · Reverse the word order
Read one line. Print its words in reverse order, on one line, separated by exactly one space, whatever the spacing in the input. The letters inside each word keep their order. (The checker, like VPL, ignores spacing, so the tests mark the word order; the single space is for tidiness.)
Input One line (it may be empty).
Output The words, last first (nothing for an empty line).
the cat sat on the mat
mat the on sat cat the
hello world
world hello
one
one
a b
b a
Stuck? First move
Use one index i that starts at the last character, strlen(s) - 1, and moves left. Each round of the outer loop handles one word, using the sheet's §17 tokenizer run backwards: skip spaces, remember where the word ends, walk to where it starts, then print from start to end.
Plan in plain words
- Read and strip; i = last index; printed = 0.
- While i ≥ 0:
move i left past spaces (if that runs off the front, stop);
end = i; move i left past non-spaces; start = i + 1;
print a space first if printed > 0; print s[start..end]; printed + 1. - Print a newline.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
int main(void) {
char s[300];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int i = (int) strlen(s) - 1; /* start at the last character */
int printed = 0; /* words printed so far */
while (i >= 0) {
while (i >= 0 && s[i] == ' ') i--; /* skip spaces */
if (i < 0) break; /* only spaces were left */
int end = i; /* last letter of this word */
while (i >= 0 && s[i] != ' ') i--; /* walk to just before the word */
int start = i + 1; /* first letter of this word */
if (printed > 0) printf(" ");
for (int j = start; j <= end; j++) putchar(s[j]);
printed++;
}
printf("\n");
return 0;
}
Putting s[i] != ' ' before i >= 0 in the inner while. When i reaches −1, that reads s[-1], which is outside the array. Put the bounds check first, because && stops as soon as the left side is false.
C6 · Password checker that lists every problem
Read a password as a whole line, because spaces must be detected, not lost. The rules are: length 8 to 20, at least one uppercase letter, one lowercase letter, one digit, one special character (anything that is not a letter, a digit or a space), and no spaces. Print one line for every rule broken, in this order and with this wording, followed by Rejected: n problem(s):
- length must be 8 to 20 (yours is n)- needs an uppercase letter- needs a lowercase letter- needs a digit- needs a special character- must not contain spaces
If no rule is broken, print Strong password.
Input One line (it may be empty or contain spaces).
Output Strong password, or the problem lines and the Rejected line.
Lab7@BitsHyd
Strong password
password
- needs an uppercase letter - needs a digit - needs a special character Rejected: 3 problem(s)
my Pass 1!
- must not contain spaces Rejected: 1 problem(s)
Ab1!
- length must be 8 to 20 (yours is 4) Rejected: 1 problem(s)
- length must be 8 to 20 (yours is 0) - needs an uppercase letter - needs a lowercase letter - needs a digit - needs a special character Rejected: 5 problem(s)
Stuck? First move
Read with fgets. Notice that scanf("%s") would turn my Pass 1! into my and hide the space. Make five bool flags, all false, and one loop over the characters that only sets flags. No printing happens inside the loop.
Plan in plain words
- Read, strip, take the length.
- One pass: classify each character as upper / lower / digit / space / other, and set that flag.
- After the loop, check the rules in order; for each one broken, print its line and add 1 to problems.
- problems == 0 → Strong; else → Rejected line.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
int main(void) {
char pw[100];
fgets(pw, sizeof(pw), stdin);
pw[strcspn(pw, "\n")] = '\0';
int len = (int) strlen(pw);
bool hasUpper = false, hasLower = false, hasDigit = false;
bool hasSpecial = false, hasSpace = false;
for (int i = 0; pw[i] != '\0'; i++) {
unsigned char c = (unsigned char) pw[i];
if (isupper(c)) hasUpper = true;
else if (islower(c)) hasLower = true;
else if (isdigit(c)) hasDigit = true;
else if (c == ' ') hasSpace = true;
else hasSpecial = true;
}
int problems = 0;
if (len < 8 || len > 20) {
printf("- length must be 8 to 20 (yours is %d)\n", len);
problems++;
}
if (!hasUpper) { printf("- needs an uppercase letter\n"); problems++; }
if (!hasLower) { printf("- needs a lowercase letter\n"); problems++; }
if (!hasDigit) { printf("- needs a digit\n"); problems++; }
if (!hasSpecial){ printf("- needs a special character\n"); problems++; }
if (hasSpace) { printf("- must not contain spaces\n"); problems++; }
if (problems == 0) printf("Strong password\n");
else printf("Rejected: %d problem(s)\n", problems);
return 0;
}
Printing inside the character loop, which gives one "needs a digit" line per character. Collect facts in the loop and decide after it. This pattern of looping to gather facts and then deciding afterwards also shows up in end-sem questions.
C7 · Which version is newer?
Read two version strings, one per line, such as 1.10.2: non-negative integers separated by dots. Compare them part by part as numbers, so 10 > 9 even though "10" < "9" as text. A missing part counts as 0, so 2.0 equals 2. Print <version> is newer or Same version.
Input Two lines, one version each.
Output The newer version followed by is newer, or Same version.
1.10.2 1.9
1.10.2 is newer
2.0 2
Same version
3.4 3.4.1
3.4.1 is newer
1.2.3 1.2.3
Same version
10 9
10 is newer
Stuck? First move
You can't use strcmp, because it would say 1.9 > 1.10. Use two indices, i into the first string and j into the second. Each round reads one number from each with the digit-building loop x = x * 10 + (a[i] - '0'), compares the two numbers, and steps over the dots.
Plan in plain words
- Read both lines; strip both.
- While either string still has characters left:
x = number starting at a[i] (0 if a has ended); y = same for b at j;
x > y → first is newer, stop; x < y → second is newer, stop;
step i past a '.', step j past a '.'. - Loop ended with no difference → Same version.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char a[60], b[60];
fgets(a, sizeof(a), stdin);
a[strcspn(a, "\n")] = '\0';
fgets(b, sizeof(b), stdin);
b[strcspn(b, "\n")] = '\0';
int i = 0, j = 0; /* where we are in a and in b */
while (a[i] != '\0' || b[j] != '\0') {
int x = 0, y = 0; /* a finished string gives 0 */
while (isdigit((unsigned char) a[i])) {
x = x * 10 + (a[i] - '0'); /* "10" -> 1 -> 10 */
i++;
}
while (isdigit((unsigned char) b[j])) {
y = y * 10 + (b[j] - '0');
j++;
}
if (x > y) { printf("%s is newer\n", a); return 0; }
if (x < y) { printf("%s is newer\n", b); return 0; }
if (a[i] == '.') i++; /* step over the dot */
if (b[j] == '.') j++;
}
printf("Same version\n");
return 0;
}
Unpack: why does a finished string give 0 automatically?
When a has ended, a[i] is '\0', which is not a digit. The digit loop runs zero times, x stays 0, and the '.' test is false, so i stays on the terminator for every later round.
Stopping when either string ends (using && instead of || in the outer loop). That reports 3.4 and 3.4.1 as the same (Test 3).
C8 · Evaluate 12+34-5, with error positions
Read one line containing non-negative integers joined by + and -, with spaces allowed anywhere between them. Print Result: n. If the line breaks that form, print the position (counting from 0 in the line as given) of the first character that is wrong, and what was expected: Error at position p: expected a digit or Error at position p: expected + or -. An empty line is an error at position 0.
Input One line.
Output The Result line or one Error line.
12+34-5
Result: 41
100 - 7 - 3 + 10
Result: 100
12+*3
Error at position 3: expected a digit
12 + 3x
Error at position 6: expected + or -
Error at position 0: expected a digit
Stuck? First move
Think of the line as number, operator, number, operator, …, number. Keep int i (where you are), int result = 0 and char op = '+'. The loop body is in two halves: half 1 reads a number and adds or subtracts it, half 2 reads an operator or finds the end. Each half begins with while (s[i] == ' ') i++;.
Plan in plain words
- Read and strip; i = 0, result = 0, op = '+'.
- Repeat:
skip spaces; if s[i] is not a digit → error "expected a digit" at i, stop;
build num from the digits; apply op to result;
skip spaces; if s[i] is '\0' → finished; if it's not + or − → error "expected + or −" at i, stop;
op = s[i]; i + 1. - Print the result.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void) {
char s[200];
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int i = 0;
int result = 0;
char op = '+'; /* pretend the first number has a '+' before it */
while (1) {
/* 1. expect a number */
while (s[i] == ' ') i++;
if (!isdigit((unsigned char) s[i])) {
printf("Error at position %d: expected a digit\n", i);
return 0;
}
int num = 0;
while (isdigit((unsigned char) s[i])) {
num = num * 10 + (s[i] - '0');
i++;
}
if (op == '+') result += num;
else result -= num;
/* 2. expect an operator, or the end of the line */
while (s[i] == ' ') i++;
if (s[i] == '\0') break; /* clean finish */
if (s[i] != '+' && s[i] != '-') {
printf("Error at position %d: expected + or -\n", i);
return 0;
}
op = s[i];
i++;
}
printf("Result: %d\n", result);
return 0;
}
Treating each digit as a separate number, which gives 1 + 2 + 3 + 4 − 5 = 5 instead of 41. Digits must be accumulated (num * 10 + digit) until a non-digit arrives. That's the same digit-building idea as C7.
C9 · Most frequent word
Read one line. A word is a maximal run of letters, so punctuation and spaces separate words, and words are compared ignoring case. Print the most frequent word in lowercase with its count, as Most frequent: w (n times). On a tie, the word that appeared first wins. If there are no words, print No words. Assume at most 100 different words of at most 30 letters.
Input One line, at most 499 characters (it may be empty).
Output The Most frequent line or No words.
The cat and the dog and THE bird.
Most frequent: the (3 times)
to be, or not to be: that is the question
Most frequent: to (2 times)
...!!
No words
No words
b a b a
Most frequent: b (2 times)
Stuck? First move
You need a 2D array char words[100][31], a parallel int count[100] and int distinct = 0. Each word you cut out goes into a temporary char w[31]. Then do a linear search through words[0..distinct-1] with strcmp: if it's found, add 1 to its count; if not, strcpy it in as a new row.
Plan in plain words
- Read and strip; distinct = 0.
- Walk the line: skip non-letters; copy the letters of one word (lowercased) into w; end w with '\0'.
- Search the table for w: found → count + 1; not found → copy into the next row, count 1.
- No rows → No words. Otherwise, find the row with the largest count, using
>so the earlier row keeps a tie. Print it.
Full solution (clang -Wall -Wextra: no warnings · passes all 5 tests)
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXW 100 /* distinct words we can remember */
#define WLEN 31 /* 30 letters + '\0' */
int main(void) {
char s[500];
char words[MAXW][WLEN];
int count[MAXW];
int distinct = 0;
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
int i = 0;
while (s[i] != '\0') {
if (!isalpha((unsigned char) s[i])) { /* not part of a word */
i++;
continue;
}
/* copy one word, lowercased, into w */
char w[WLEN];
int k = 0;
while (isalpha((unsigned char) s[i])) {
if (k < WLEN - 1) w[k++] = tolower((unsigned char) s[i]);
i++;
}
w[k] = '\0';
/* seen before? */
int found = -1;
for (int j = 0; j < distinct; j++) {
if (strcmp(words[j], w) == 0) { found = j; break; }
}
if (found != -1) {
count[found]++;
} else if (distinct < MAXW) {
strcpy(words[distinct], w);
count[distinct] = 1;
distinct++;
}
}
if (distinct == 0) {
printf("No words\n");
return 0;
}
int best = 0; /* '>' (not '>=') keeps the earliest on a tie */
for (int j = 1; j < distinct; j++) {
if (count[j] > count[best]) best = j;
}
printf("Most frequent: %s (%d times)\n", words[best], count[best]);
return 0;
}
Forgetting w[k] = '\0'; after copying a word. strcmp and strcpy then run past the letters into leftovers from the previous longer word. This is the sheet's "missing terminator" bug, now hidden inside a bigger program. Using >= in the final search breaks the tie rule (Test 5).
Self-test before moving on
- From a blank file, without opening any box, you can write A+3 in under 8 minutes and pass all five tests, Test 5 included (the leftover-newline fix right the first time).
- You can do B4 and B5 from a blank file in under 20 minutes each, with no prompts or debug prints, passing all five tests.
- Of the other three B problems, you pass at least four of five tests on each on your first run.
If B4 or B5 fails, redo it tomorrow before moving on: they combine the input pattern with the boundary and rule-order mistakes VPL tests look for. Rung C is optional; if you have time, C1 and C5 are the best next pair. For more drill on the sheet's own problems, use Lab 7 solutions (attempt each one before reading).
← Stage 3 · ArraysStage 5 · Recursion →
When stuck, paste your own code and ask a narrow question, not "solve this". For example:
- "Here is my C program for [paste problem]. It is auto-graded like Moodle VPL: it reads stdin with no prompts and prints only the answer. For the input
[paste]it prints[paste]but the expected output is[paste]. Don't rewrite it: point to the line that's wrong and explain why, using onlyfgets,<string.h>and<ctype.h>as in a first-semester C lab." - "Give me three tricky test inputs for this string program (including an empty line and a one-character input) and the exact output each should produce. Don't show code."