Set Union and Intersection in C — Array Program with Examples

A set is a collection of distinct elements — no duplicates, order irrelevant. The two operations every course asks you to implement in C are union (A ∪ B: every element that appears in A or B) and intersection (A ∩ B: only the elements that appear in both). This page implements them cleanly over arrays, with a shared …

K&R C Programs Exercise 4-6

Exercise 4-6. Add commands for handling variables. (It’s easy to provide for twenty-six variables with single-letter names.) Add a variable for the most recently printed value. Twenty-six variables map naturally to an array var[26] indexed by c – ‘a’. The protocol: a lowercase letter pushes its variable’s value; = assigns the top of the stack …

K&R C Programs Exercise 4-5

Exercise 4-5. Add access to library functions like sin, cos, exp, and pow. See <math.h> in Appendix B, Section 4. Math functions need the calculator to recognize words as well as single characters. getop currently returns one character at a time. The fix: if getop sees a letter, it reads the whole word into s[] …

Kruskal’s Algorithm in C — Minimum Spanning Tree with Union-Find

Kruskal’s algorithm finds the minimum spanning tree (MST) of a weighted, connected, undirected graph — the cheapest possible set of edges that connects every vertex with no cycles. It’s the classic greedy approach: sort all edges by weight, then keep taking the cheapest edge that doesn’t form a cycle. Road networks, electrical wiring, and network …

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 …

K&R C Exercise 2-8: rightrot — Rotate Bits Right

K&R C Exercise 2-8 — rightrot(x, n) Exercise 2-8: Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. Approach A right rotation is different from a right shift. When you shift right by n, the n bits that fall off the right end are …