K&R C Programs Exercise 4-7

Exercise 4-7. Write a routine ungets(s) that will push back an entire string onto the input. Should ungets know about buf and bufp, or should it just use ungetch? The answer is: ungets should use ungetch, not access buf and bufp directly. This is the principle of information hiding — getch and ungetch own the …

K&R C Programs Exercise 4-3

Exercise 4-3. Given the basic framework, it’s straightforward to extend the calculator. Add the modulus (%) operator and provisions for negative numbers. This exercise extends the RPN desk calculator from K&R Section 4.3. Two independent additions: Modulus operator % — pop two operands, cast to int, apply %, push result. Floating-point modulus is mathematically well-defined …

Print Factors of a Number in C – O(√n) Algorithm

A C program to print factors of a number finds all positive integers that divide the number evenly (with no remainder). These are also called divisors. For 12: the factors are 1, 2, 3, 4, 6, and 12. Every number has at least two factors: 1 and itself. A number with exactly two factors is …

Topological Sort in C — Kahn’s Algorithm with Cycle Detection

Topological sort orders the vertices of a directed acyclic graph (DAG) so that every edge points forward: if there’s an edge from u to v, then u appears before v in the ordering. It’s the algorithm behind every dependency system you’ve used — build tools compiling files in the right order, package managers resolving installs, …

K&R C Exercise 3-5: itob — Integer to Any Base String

Exercise 3-5. Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) should produce in s a hexadecimal string. itob generalises itoa from base 10 to any base 2–36. The only change to the digit-extraction loop is replacing n % 10 with n …

System Information in C — getenv(), system(), and uname()

How do you get system information from a C program? There are three portable-ish layers, and knowing which to use is the actual lesson: getenv() reads environment variables (pure standard C), system() runs a shell command like uname (standard C, but it launches a whole shell), and POSIX uname() fills a struct with OS name, …