A challenging, application-focused C practice set based on the supplied Lecture 1–7 syllabus: input/output, arithmetic, selection, switch, while/for/do-while, nested loops, break/continue, 1D arrays, and 2D arrays.
These are original practice problems, not official exam questions. Scenarios use fictional rules where applicable. No solution code is included, so you can attempt each problem independently.
- Write a separate C program for each problem.
- Use standard input and output. Do not print prompts or extra labels.
- Whitespace separates input tokens unless stated otherwise. Print integer lists with one space between values.
- Inputs satisfy the stated constraints except for cases that a problem explicitly asks you to validate.
- Use 1-based positions in output when specified; C array indices are still 0-based.
- Use double for real calculations and long long when integer totals may overflow int. Print decimal results with printf("%.2f", value).
- All problems can be solved with the listed syllabus topics. Recursion, structs, dynamic allocation, and advanced data structures are unnecessary.
- Each problem contains a task, input/output contract, constraints, at least two sample cases, and additional edge cases to test.
- Suggested time limits are practice targets, not official exam limits. Trace a small case by hand, implement it, then check the boundary cases.
- First session: Problems 01–08 — arithmetic, decisions, and simulation.
- Second session: Problems 09–18 — nested loops and 1D arrays.
- Third session: Problems 19–24 — 2D arrays and integrated problems.
- If time is short, prioritize 02, 05, 07, 09, 10, 13, 16, 19, 22, and 24.
- Mock exam A (150 minutes): 02 (20 points), 07 (25), 14 (25), 19 (30).
- Mock exam B (150 minutes): 05 (20 points), 10 (20), 18 (25), 24 (35).
- Suggested marking per problem: 60% correct algorithm, 25% boundary/tie cases, 10% exact I/O, 5% readable code.
- 01–06: numerical decisions and basic search.
- 07–12: loop simulation, counting, and patterns.
- 13–18: 1D arrays and persistent state.
- 19–24: 2D arrays, updates, and matrix applications.
Sample outputs were checked against reference calculations for all 57 sample cases.
01. Mixed-Unit Temperature Controller
Topics: Variables • double • if/else
Difficulty: Hard | Suggested time: 25 minutes
A food container receives one temperature in C, F, or K. Convert it to Celsius: F uses (x-32)*5.0/9.0; K uses x-273.15. Print INVALID if the unit is unsupported or the input is below absolute zero (C: -273.15, F: -459.67, K: 0). Otherwise classify the unrounded Celsius value: below 0 = FREEZE; 0 through 4 = SAFE; above 4 through 10 = WARN; above 10 = DANGER. To accommodate conversion error, treat values within 1e-9 of a classification boundary as equal to that boundary. Apply the absolute-zero check to the original input value.
One character unit and one real number x; -10000 ≤ x ≤ 10000. Valid unit letters are uppercase.
Line 1: Celsius with exactly 2 decimal places. Line 2: status. For invalid input, print only INVALID.
Input:
F 39.2
Output:
4.00
SAFE
Input:
K -1
Output:
INVALID
Input:
C 10.01
Output:
10.01
DANGER
Test C temperatures 0, 4, and 10; K 0; and unit X. Use floating-point division and handle whitespace when reading a character.
02. Average-Speed Camera Across Midnight
Topics: Unit conversion • conditions • integers
Difficulty: Hard | Suggested time: 30 minutes
Two cameras are d meters apart. Read entry and exit times as hours, minutes, and seconds. If the exit clock time is earlier, it is on the following day. Equal times are INVALID, not a 24-hour trip. Calculate the average speed in km/h. The fine is 0 if speed is at most L; 500 if it is above L but at most L+20; otherwise 1000. Classify using the unrounded speed.
Line 1: d L. Lines 2 and 3: entry and exit times h m s. 1 ≤ d ≤ 1000000; 1 ≤ L ≤ 200; h=0..23; m,s=0..59.
Line 1: elapsed seconds. Line 2: speed with 2 decimal places. Line 3: fine. For equal times, print only INVALID.
Input:
1500 60
23 59 30
0 0 30
Output:
60
90.00
1000
Input:
1000 60
12 0 0
12 1 0
Output:
60
60.00
0
Test speed exactly L+20 and equal timestamps. Convert each timestamp to seconds first.
03. Tiered Water Bill with a Conditional Discount
Topics: Multiple conditions • arithmetic
Difficulty: Hard | Suggested time: 30 minutes
Use this fictional pricing scheme: the first 10 units cost 8 baht each, the next 20 cost 12 each, and units above 30 cost 15 each. Add a fixed service fee of 25 baht. Members (m=1) using at most 20 units receive a 10% discount on water charges only. Apply 7% VAT to the discounted water charges plus service fee. Do not round intermediate results.
Two integers u m; 0 ≤ u ≤ 10000; m is 0 or 1.
The final bill with exactly 2 decimal places.
Input:
20 1
Output:
219.35
Input:
31 0
Output:
385.20
Input:
0 1
Output:
26.75
Test u=10,20,21,30. Apply each rate only to the units in its tier; the service fee is not discounted.
04. Bus Fare with a Daily Spending Cap
Topics: switch • if/else • minimum
Difficulty: Hard | Suggested time: 25 minutes
The regular fare is 12 + 3*max(0,z-2) baht for z zones. Passenger type 1 pays the full fare; type 2 is a student and pays half rounded UP to a whole baht; type 3 is a senior and pays zero. The actual charge must not increase the amount already paid today above 60 baht. Use switch to select the passenger type. Any other type is INVALID.
Three integers type z paid; 1 ≤ z ≤ 20; 0 ≤ paid ≤ 60; type=0..9.
Print the actual charge and new daily total on one line, or INVALID.
Input:
2 3 50
Output:
8 58
Input:
1 8 55
Output:
5 60
Input:
4 2 0
Output:
INVALID
Test paid=60, a senior passenger, and an odd regular fare for a student.
05. Limited-Banknote Change Machine
Topics: Nested loops • optimization • tie-breaking
Difficulty: Hard | Suggested time: 35 minutes
A machine has limited supplies of 100-, 50-, and 20-baht notes. Make exactly amount baht using the fewest notes. If multiple solutions use the same number, prefer more 100-baht notes, then more 50-baht notes. Taking the largest available note first is not guaranteed to work.
amount n100 n50 n20; 0 ≤ amount ≤ 10000; each note count is 0..30.
Print the counts of 100-, 50-, and 20-baht notes used, followed by their total count. If impossible, print IMPOSSIBLE.
Input:
60 0 1 3
Output:
0 0 3 3
Input:
180 1 2 4
Output:
1 0 4 5
Input:
0 0 0 0
Output:
0 0 0 0
Test amount=0, insufficient notes, and an amount not divisible by 10. Compare all feasible candidates.
06. Expanding Rows in an Auditorium
Topics: for/while • cumulative sums
Difficulty: Hard | Suggested time: 25 minutes
The first row has a seats. Each subsequent row has d more seats than the previous row. Build the fewest complete rows needed to seat n people. People fill seats from the first row onward. Report the number of rows, total seats, and empty seats in the last row. For n=0, use zero rows and zero seats.
Three integers n a d; 0 ≤ n ≤ 1000000; 1 ≤ a ≤ 1000; 0 ≤ d ≤ 100.
Print rows total empty on one line.
Input:
31 5 2
Output:
4 32 1
Input:
20 5 0
Output:
4 20 0
Input:
0 5 2
Output:
0 0 0
Test an exact fit, d=0, and one person.
07. A Bus Visiting Multiple Stops
Topics: Loops • state tracking • validation
Difficulty: Hard | Suggested time: 35 minutes
A bus starts empty and holds C passengers. At each of N stops, off passengers leave first, then on people attempt to board. Admit only as many as fit. Rejected people do not reappear at later stops. If off exceeds the number on board before that stop, stop the simulation and report INVALID with the 1-based stop number. Otherwise calculate the final load, total rejected passengers, and highest load after boarding at any stop.
C N, followed by N lines containing off on. 1 ≤ C ≤ 1000; 1 ≤ N ≤ 1000; 0 ≤ off,on ≤ 1000.
Print final rejected peak, or INVALID stop.
Input:
5 3
0 4
2 5
4 1
Output:
2 2 5
Input:
5 2
0 2
3 1
Output:
INVALID 2
Test a full bus, everyone leaving, and nobody boarding. Validate off before changing the load.
08. Monthly Savings with Rounded Bonuses
Topics: do-while • integer rounding
Difficulty: Hard | Suggested time: 30 minutes
Start with S baht and a target T. If the initial balance already reaches T, the answer is zero months. Otherwise, each month deposit D first, then add a bonus of floor(balance_after_deposit*p/100) baht. Bonuses remain in the account. Stop upon reaching T or after M months. Use do-while for the simulation.
S T D p M; 0 ≤ S ≤ 1000000; 1 ≤ T ≤ 1000000; 0 ≤ D ≤ 10000; 0 ≤ p ≤ 10; 1 ≤ M ≤ 120.
If successful, print months balance. Otherwise print NOT_REACHED balance.
Input:
100 150 20 10 12
Output:
2 167
Input:
0 10 0 10 3
Output:
NOT_REACHED 0
Input:
50 50 10 1 12
Output:
0 50
Round the bonus down each month. Test an initially sufficient balance and a balance that never grows.
09. Temperature Stream with Broken Readings
Topics: while • break • continue
Difficulty: Hard | Suggested time: 30 minutes
Read integer temperatures until sentinel 999. Values outside -50..60 are invalid: count and skip them using continue. Invalid readings also break any consecutive hot streak. Valid readings of at least 35 are hot. Find the counts of valid and invalid readings, the average of valid readings, and the longest hot streak. Do not count the sentinel.
Whitespace-separated integers, ending with 999. At most 10000 readings precede it. Readings are -1000..1000; 999 is reserved for termination.
Line 1: good bad. Line 2: average with 2 decimal places, or NO_DATA. Line 3: longestHot.
Input:
30 35 40 100 36 37 999
Output:
5 1
35.60
2
Input:
100 -100 999
Output:
0 2
NO_DATA
0
Test an immediate sentinel, all-hot readings, and an invalid reading interrupting a hot streak.
10. Three-Dice Outcome Counter
Topics: Nested loops • modulo • counting
Difficulty: Hard | Suggested time: 35 minutes
Three distinguishable dice each have faces 1..S. Count ordered outcomes (a,b,c) whose sum is in L..U inclusive, with exactly E even-valued dice, and with at least two dice showing the same value. Three equal dice also qualify. Outcomes (1,1,2), (1,2,1), and (2,1,1) are distinct.
S L U E; 2 ≤ S ≤ 20; 3 ≤ L ≤ U ≤ 3*S; 0 ≤ E ≤ 3.
Print the number of qualifying ordered outcomes.
Input:
2 3 6 1
Output:
3
Input:
2 3 6 2
Output:
3
Input:
6 3 3 0
Output:
1
Do not restrict enumeration to a≤b≤c. Test no qualifying outcomes and three equal dice.
11. Lucky Four-Digit Bus Tickets
Topics: Loops • integer division • modulo
Difficulty: Hard | Suggested time: 30 minutes
Examine all ticket numbers from A through B inclusive. Always interpret a number as four digits, so 27 is 0027. A lucky ticket has equal sums of its first two and last two digits, and no identical adjacent digits. For example, 0110 fails because its middle digits match. Find the lucky-ticket count and smallest lucky ticket.
A B; 0 ≤ A ≤ B ≤ 9999.
Print count smallest, padding smallest to 4 digits. If none exist, print 0 NONE.
Input:
1000 1020
Output:
1 1010
Input:
0 9
Output:
0 NONE
Leading zeros are real digits for both rules. Check all three adjacent pairs.
12. Snake-Numbered Bus Seating Plan
Topics: Nested loops • output patterns
Difficulty: Hard | Suggested time: 30 minutes
A bus has R rows with an even number C of seats per row. Number row 1 left to right from 1 to C, row 2 right to left, and alternate thereafter. Display every row from left to right. Insert an aisle token | between the left and right halves. Replace every seat number divisible by K with XX.
R C K; 1 ≤ R ≤ 20; 2 ≤ C ≤ 10 with C even; 1 ≤ K ≤ 200.
Print R lines. Separate all tokens, including |, with one space. Do not pad numbers with zeros or print trailing spaces.
Input:
2 4 3
Output:
1 2 | XX 4
8 7 | XX 5
Input:
1 2 1
Output:
XX | XX
The aisle is not a seat. Even-numbered rows display their seat numbers in reverse order.
13. Fastest Consecutive Road Segments
Topics: 1D Array • windows • tie-breaking
Difficulty: Hard | Suggested time: 35 minutes
A vehicle travels N road segments, each D meters long. Given each segment's travel time, select K consecutive segments with the highest overall average speed. Break ties by choosing the earliest starting segment. Overall speed is total distance divided by total time, not the average of individual segment speeds.
N K D, then N integer times t. 1 ≤ K ≤ N ≤ 1000; 1 ≤ D ≤ 100000; 1 ≤ t ≤ 10000 seconds.
Line 1: start end, using 1-based indices. Line 2: overall speed in km/h with 2 decimal places.
Input:
5 2 1000
60 30 30 90 30
Output:
2 3
120.00
Input:
3 2 500
30 30 30
Output:
1 2
60.00
Test K=1, K=N, and equal total times. Use floating-point arithmetic for speed.
14. Longest Affordable Spending Streak
Topics: 1D Array • nested loops
Difficulty: Very hard | Suggested time: 40 minutes
Given nonnegative expenses for N days, find the longest nonempty interval of consecutive days whose total expense is at most B. If several intervals have equal length, choose the earliest start. If no day is affordable, print NONE. An O(N²) solution is acceptable.
N B, then N expenses. 1 ≤ N ≤ 500; 0 ≤ B ≤ 1000000; 0 ≤ expense ≤ 10000.
Print start end sum using 1-based days, or NONE.
Input:
6 10
4 2 3 5 1 1
Output:
3 6 10
Input:
3 0
1 0 0
Output:
2 3 0
Input:
2 1
2 3
Output:
NONE
Zero-expense days count toward interval length. Maximize length, not spending.
15. Dice Frequency and Repeated Runs
Topics: 1D frequency array • ranking
Difficulty: Hard | Suggested time: 30 minutes
Given N dice rolls, report all six face frequencies, the most frequent face, and the longest consecutive run of identical faces. If multiple faces share the highest frequency, select the smallest face.
N, then N face values. 1 ≤ N ≤ 10000; 1 ≤ face ≤ 6.
Line 1: frequencies of faces 1 through 6. Line 2: mode count. Line 3: longestRun.
Input:
8
2 2 3 3 3 2 6 6
Output:
0 3 3 0 0 2
2 3
3
Input:
1
6
Output:
0 0 0 0 0 1
6 1
1
The mode need not produce the longest consecutive run. Print zero for faces that never appear.
16. Vending Machine Inventory
Topics: 1D Array • switch • transactions
Difficulty: Very hard | Suggested time: 40 minutes
There are N products numbered 1..N, each with a price and stock. Process Q commands using switch. Command 1 id qty money buys a product: invalid id or nonpositive qty → INVALID; otherwise insufficient stock → SOLD_OUT; otherwise insufficient money → NEED_MORE; otherwise print OK change and reduce stock. Check failures in that exact order. Command 2 id qty restocks: invalid id or nonpositive qty → INVALID; otherwise increase stock and print RESTOCKED. Failed commands never change stock.
N Q; N lines of price stock; then Q commands in the formats above. 1 ≤ N ≤ 20; 1 ≤ Q ≤ 100; price=1..1000; stock=0..1000; qty=-10..100; money=0..100000; id=0..N+1. Only op 1 or 2 occurs.
Print one result per command. On the final line, print all final stock counts in product-ID order.
Input:
2 4
10 2
15 0
1 1 2 25
1 1 1 100
2 2 3
1 2 2 20
Output:
OK 5
SOLD_OUT
RESTOCKED
NEED_MORE
0 3
Input:
1 2
10 5
1 0 1 20
2 1 0
Output:
INVALID
INVALID
5
If both stock and money are insufficient, print SOLD_OUT. Validate the ID before indexing an array.
17. Circular Staff Roster
Topics: 1D Array • modulo
Difficulty: Hard | Suggested time: 30 minutes
A roster contains N employee IDs. Apply Q shifts in order. A positive k rotates the roster right by k positions; a negative k rotates it left. Each command acts on the previous result. Values of |k| can exceed N. Print the final roster.
N Q; N employee IDs; Q shift values k. 1 ≤ N ≤ 100; 0 ≤ Q ≤ 100; IDs=1..9999; -1000000 ≤ k ≤ 1000000.
Print the final employee IDs in order on one line.
Input:
5 2
10 20 30 40 50
2 -1
Output:
50 10 20 30 40
Input:
3 1
1 2 3
-4
Output:
2 3 1
Test Q=0, N=1, k=0, and negative shifts. Account for C's negative remainder behavior.
18. Trim Extreme Revenue Days
Topics: 1D Array • min/max • averages
Difficulty: Very hard | Suggested time: 40 minutes
Given revenue for N days, remove exactly one minimum-revenue day, choosing the earliest on a tie. Then remove exactly one maximum-revenue day among the remaining days, choosing the latest on a tie. Calculate the remaining average and find the remaining day whose revenue is closest to that average. Break this final tie by earliest day. Do not round the average before comparisons.
N, then N revenue values. 3 ≤ N ≤ 1000; 0 ≤ revenue ≤ 1000000.
Line 1: removedMinDay removedMaxDay. Line 2: remaining average with 2 decimal places. Line 3: closestDay. All day numbers are 1-based.
Input:
5
10 20 20 30 100
Output:
1 5
23.33
2
Input:
4
7 7 7 7
Output:
1 4
7.00
2
Test all-equal values. The two removed days must differ. Exact comparison can use |revenue*(N-2)-sum| with long long.
19. Consecutive Cinema Seat Reservations
Topics: 2D Array • search • updates
Difficulty: Very hard | Suggested time: 40 minutes
A cinema has an R×C seating grid: 0 means free, 1 means occupied. Process Q groups sequentially; each requests k consecutive seats in one row. Choose the smallest row number first, then the smallest starting column. Mark successfully reserved seats as 1 immediately. If no block fits, print REJECT without changing the grid.
R C Q; R grid rows; Q group sizes k. 1 ≤ R,C ≤ 30; 1 ≤ Q ≤ 100; 1 ≤ k ≤ C+1.
For each group print row start end, or REJECT. Then print FINAL and the final grid. All positions are 1-based.
Input:
2 5 3
0 0 1 0 0
0 0 0 0 0
3 2 2
Output:
2 1 3
1 1 2
1 4 5
FINAL
1 1 1 1 1
1 1 1 0 0
Input:
1 2 1
0 1
2
Output:
REJECT
FINAL
0 1
Total free seats may be sufficient without any consecutive block. Test k>C and competing requests.
20. Hotspots on a Temperature Map
Topics: 2D Array • neighbors • boundaries
Difficulty: Hard | Suggested time: 35 minutes
A hotspot is a cell strictly hotter than every existing orthogonal neighbor: above, below, left, and right. Ignore diagonals and nonexistent neighbors. A 1×1 grid has one hotspot by definition. List all hotspots in row-major order.
R C, then an integer grid. 1 ≤ R,C ≤ 50; temperatures=-100..100.
First print the hotspot count. Then print row col temperature for each hotspot, using 1-based positions. If none exist, print only 0.
Input:
3 3
1 2 1
2 9 2
1 2 8
Output:
2
2 2 9
3 3 8
Input:
1 2
5 5
Output:
0
Input:
1 1
-4
Output:
1
1 1 -4
Test negative temperatures, corners, and equal adjacent values. Equality does not qualify.
21. Revenue Across Bus Routes and Days
Topics: 2D Array • matrix/vector calculations • sums
Difficulty: Hard | Suggested time: 35 minutes
Matrix A has R bus routes and D days. A[r][d] is the number of passengers on route r on day d. Vector fare gives the per-passenger fare for each route. Calculate revenue for each day, total revenue for each route, and the highest-earning route. Break ties by smallest route number.
R D; R rows of A with D values each; R fare values. 1 ≤ R,D ≤ 30; passengers=0..1000000; fare=1..1000.
Line 1: D daily revenues. Line 2: R route revenues. Line 3: bestRoute total, with routes numbered from 1. Use 64-bit integers.
Input:
2 3
2 0 3
1 4 0
10 20
Output:
40 80 30
50 100
2 100
Input:
2 1
0
0
10 20
Output:
0
0 0
1 0
The fare vector has one entry per route, not per day. Totals can exceed a 32-bit int.
22. Warehouse Columns: Insert, Delete, Swap
Topics: 2D Array • shifting • commands
Difficulty: Very hard | Suggested time: 50 minutes
A warehouse grid has R rows and C columns. Process commands sequentially: I p followed by R values inserts a column before position p; p=C+1 appends it. D p deletes column p. S a b swaps columns a and b. Positions refer to the current grid. Commands are guaranteed valid, and the grid always has 1..10 columns after each command. Its number of rows never changes.
R C Q; R grid rows; Q command lines. 1 ≤ R,C ≤ 10; 0 ≤ Q ≤ 30; inventory values=0..1000. Column positions are 1-based.
Print R finalC, then the final grid.
Input:
2 3 3
1 2 3
4 5 6
I 2 9 8
D 4
S 1 3
Output:
2 3
2 9 1
5 8 4
Input:
1 1 1
7
I 2 9
Output:
1 2
7 9
Test insertion at either end and swapping a column with itself. During insertion, avoid overwriting values that still need to move.
23. Solar Panels on a Blocked Roof
Topics: 2D Array • rectangular windows • tie-breaking
Difficulty: Very hard | Suggested time: 45 minutes
An R×C roof map contains nonnegative energy values, or -1 for blocked cells. Place one H×W rectangle containing no blocked cell and maximizing total energy. You may not rotate the rectangle. Break ties by the smallest top-left row, then the smallest column.
R C H W, then the grid. 1 ≤ H ≤ R ≤ 20; 1 ≤ W ≤ C ≤ 20; values are -1 or 0..1000.
Print row col total for the chosen top-left corner using 1-based positions, or IMPOSSIBLE if no placement works.
Input:
3 4 2 2
1 2 -1 4
3 4 5 6
0 1 2 3
Output:
2 3 16
Input:
2 2 2 2
1 -1
2 3
Output:
IMPOSSIBLE
An all-zero rectangle is valid. One blocked cell invalidates the entire candidate. Test a rectangle as large as the roof.
24. Two-Leg Bus Connections
Topics: 2D Array • matrix multiplication
Difficulty: Very hard | Suggested time: 45 minutes
A[i][k] counts travel options from origin i to transfer point k. B[k][j] counts travel options from transfer point k to destination j. Each first-leg option can pair with every second-leg option. Compute C[i][j] as the sum over k of A[i][k]*B[k][j]. These are counts of distinct two-leg travel choices, not bus capacities. Also report the origin–destination pair with the largest count. Break ties by smallest origin, then smallest destination.
N K M; N rows of A with K values each; K rows of B with M values each. 1 ≤ N,K,M ≤ 20; values=0..10000.
Print the N×M result matrix, then origin destination ways. Positions are 1-based. Use long long.
Input:
2 2 2
1 2
0 3
2 1
4 0
Output:
10 1
12 0
2 1 12
Input:
1 2 1
0 0
5
8
Output:
0
1 1 0
N, K, and M need not be equal. Reset each cell's accumulator. A result can exceed a 32-bit int.