CMSC 14300: Practice Set 2 - Loops, switch, Functions & Makefiles¶
Practice for the material in Week 1.
Work in a fresh directory and compile everything with warnings on:
mkdir -p ~/cmsc14300/lec02-pset && cd ~/cmsc14300/lec02-pset
clang -Wall -Wextra -std=c17 problem1.c -o problem1
If your compiler prints a warning, treat it as something to fix - warnings are the compiler trying to help you.
Problem 1 - Pick the right loop¶
Read an integer n and print a countdown from n down to 1, then Liftoff!.
- If
nis0or negative, print onlyLiftoff!(no countdown).
Problem 2 - Average until a sentinel¶
Keep reading integers until the user enters -1. Then print how many numbers were
entered (not counting the -1) and their average as a double. If the very first
number is -1, print No numbers entered.
Problem 3 - Grade letter with switch¶
Write a function char letter_grade(int score) that returns a letter for a
0-100 score: 90+ -> A, 80-89 -> B, 70-79 -> C, 60-69 -> D, else F. In
main, read a score and print the letter.
Problem 4 - Functions: a number toolkit¶
Write and test these three functions (prototypes at the top, definitions below
main):
int sum_digits(int n); /* sum of the decimal digits, e.g. 1234 -> 10 */
int count_digits(int n); /* how many digits, e.g. 1234 -> 4 */
int is_palindrome(int n);/* 1 if n reads the same reversed, else 0 */
Assume n >= 0. In main, read an integer and print all three results.
Problem 5 - Multi-file build + Makefile¶
Package Problem 4's functions as a reusable module, mirroring the calculator from Lecture 2.
digits.h- prototypes forsum_digits,count_digits,is_palindrome, wrapped in an include guard (IFNDEF).digits.c- the three definitions, including its own header.main.c-#include <stdio.h>and#include "digits.h", plusmain.- Build it by hand first:
-
Then write a
Makefile(withCC,CFLAGS, acleantarget, and TAB indented recipes) somakebuilds it andmake cleanremoves the artifacts. -
Check your understanding: after a successful
make, edit onlydigits.cand runmakeagain. Which files get recompiled? Which don't? Why?
Self-check¶
You're ready for Quiz 1 material from this week if you can, without looking it up:
- Explain when
whileruns zero times butdo/whileruns once, and why. - Say what
breakdoes in aswitch, and give a use for deliberate fall-through. - Name the difference between a function prototype, definition, and call, and explain why C sometimes needs a prototype.
- Describe the two steps
clangtakes to turn several.cfiles into one program (compile -> link), and what an "undefined reference" error means.