Skip to content
Tutorials Center
My learning

Topics

Lesson 129 of 135 ยท Practice and Review

C Programs: 50 Classic Examples

50 classic C programs with output: primes, factorial, Fibonacci, palindromes, GCD and LCM, Armstrong numbers, base conversion, strings, sorting and matrices.

Every C programmer has written the same small classics: check whether a number is prime, reverse a string, find the second largest value in an array, multiply two matrices. They are short enough to read in a minute, yet each one trains a real skill: loops with the right bounds, integer arithmetic that doesn't overflow, careful work with char arrays and the null terminator, pointers into arrays. This page collects 50 of them, all written from scratch in clean, portable C.

Every program is complete and runs as it is. Press Run and our server compiles it with GCC 15 (-std=c23 -Wall -Wextra) and shows the output. Change the numbers, break something on purpose, and run again. Programs that read input come with values already in the Input box, so you can edit those too. Each example has a short explanation and a link to the lesson that covers the idea in depth.

A few habits run through the whole page. The programs use types on purpose: unsigned long long when values grow fast, size_t for sizes and indexes. They check the return value of scanf. They cast to unsigned char before calling <ctype.h> functions. And they compute an array's length with sizeof array / sizeof array[0] only where the array is still an array, not a pointer. If you would rather write these yourself before reading ours, try the practice exercises first.

Input and basic arithmetic

These practice reading input, printf, arithmetic operators and if statements.

1. Sum and average of numbers

Reads numbers until the input runs out and prints the count, the sum and the average. scanf returns how many values it stored, so the loop ends cleanly at the end of the input (or at the first thing that isn't a number).

C 1. Sum and average

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

2. Even or odd

A number is even when n % 2 == 0. Compare with 0, not with 1: since C99, % keeps the sign of the left operand, so -7 % 2 is -1, and n % 2 == 1 would call -7 "even".

C 2. Even or odd

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

3. Largest of three numbers

The if chain keeps a running "largest so far", which is the same idea you use for a whole array in program 37. See Comparison and Logical Operators.

C 3. Largest of three

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

4. Swap two numbers

C passes arguments by value, so a swap function needs the addresses of the two variables. The XOR trick is a classic interview answer, but it's harder to read and it zeroes the value if both pointers point to the same variable. See Pointers and Functions.

C 4. Swap two numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

5. Simple calculator

Reads expressions like 12 * 4, one per line, and evaluates them with a switch on the operator character. The space before %c in the format skips whitespace, so 12*4 and 12 * 4 both work. Division by zero is reported instead of printing inf. See switch Statements.

C 5. Simple calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

6. Leap year

A year is a leap year when it's divisible by 4, except century years, unless they are divisible by 400. One boolean expression captures all three rules. In C23, bool is a keyword; older code includes <stdbool.h> for it (see Booleans).

C 6. Leap year

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

7. Temperature conversion table

Prints Celsius and Fahrenheit side by side with field widths. Writing 9.0 makes the arithmetic floating point; celsius * 9 / 5 in pure int arithmetic would truncate. See Type Conversions.

C 7. Temperature table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Loops and number theory

These practice for loops, while loops, functions, recursion and integer types.

8. Factorial

Computes n! with a loop and with recursion. unsigned long long holds factorials up to 20!; 21! doesn't fit in 64 bits, and unsigned arithmetic silently wraps around, so the last line prints a wrong (but well-defined) number.

C 8. Factorial

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

9. Fibonacci sequence

Keeps only the last two terms, so it runs in O(n) time and O(1) memory. F(93) is the last Fibonacci number that fits in an unsigned long long. The naive recursive version recomputes the same terms an exponential number of times; see Recursion.

C 9. Fibonacci sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

10. Prime check

Trial division only needs to test divisors up to the square root of n. Writing the condition as d <= n / d instead of d * d <= n avoids overflow for numbers near INT_MAX. Skipping even divisors halves the work.

C 10. Prime check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

11. All primes up to N (Sieve of Eratosthenes)

Instead of testing each number, the sieve crosses out the multiples of every prime. It starts at p * p because smaller multiples were already crossed out by smaller primes. It's the fastest simple way to list all primes in a range.

C 11. Sieve of Eratosthenes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

12. GCD and LCM

Euclid's algorithm replaces (a, b) with (b, a % b) until b is zero. For the LCM, divide before multiplying (a / gcd * b) so the intermediate value stays small.

C 12. GCD and LCM

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

13. Reverse a number and sum its digits

n % 10 gives the last digit and n / 10 drops it. Building the reversed value as an integer means trailing zeros disappear: 1200 reverses to 21.

C 13. Reverse and digit sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

14. Palindrome number

A number is a palindrome when it equals its own reverse. This version reverses only half the digits, which also avoids overflow for large values: it stops when the reversed half catches up with what's left.

C 14. Palindrome number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

15. Armstrong numbers

An Armstrong (narcissistic) number equals the sum of its digits, each raised to the number of digits: 153 = 1ยณ + 5ยณ + 3ยณ. The program uses its own integer power function, because pow works with double and can round.

C 15. Armstrong numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

16. Perfect numbers

A perfect number equals the sum of its proper divisors: 28 = 1 + 2 + 4 + 7 + 14. Divisors come in pairs (d, n / d), so the loop only runs up to the square root.

C 16. Perfect numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

17. Fast exponentiation

Squaring the base and halving the exponent needs only about logโ‚‚(exponent) multiplications. The modular version keeps every intermediate value below the modulus, which is how cryptography and hashing compute huge powers.

C 17. Fast exponentiation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The casts to unsigned long long make %llu correct on every platform; the exact alternative is the PRIu64 macro from <inttypes.h> (see Integer Types).

18. Multiplication table

Two nested loops and a field width (%4d) produce an aligned grid.

C 18. Multiplication table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

19. Roots of a quadratic equation

The discriminant bยฒ โˆ’ 4ac decides between two real roots, one repeated root, or a pair of complex roots. sqrt comes from <math.h>; on Linux you link with -lm, which our server already does. See The Math Library.

C 19. Quadratic roots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

20. Prime factorization

Divide out each factor as many times as it goes in. Once d * d exceeds what's left, the remainder (if it's above 1) must itself be prime.

C 20. Prime factorization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

21. Collatz sequence

If n is even, halve it; if it's odd, take 3n + 1. Nobody has proved that every start reaches 1, but every number ever tested does. 27 is famous for taking 111 steps and climbing to 9232 on the way.

C 21. Collatz sequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

More number programs: neon numbers, sums of two primes, factors, Fibonacci sums and interest

Five more number programs that reuse the tools above: digit loops, trial division and the square-root bound. (Armstrong numbers in a range are already program 15, which scans everything below 100,000.)

Neon numbers. A number is neon if the digits of its square add up to the number itself: 9 ร— 9 = 81 and 8 + 1 = 9. The digit-sum loop is the same one from program 13. The program shows that only 0, 1 and 9 qualify below 10,000.

C More: neon numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Sum of two primes. Can an even number be written as the sum of two primes? (Nobody has proved it for all even numbers; that is Goldbach's conjecture, checked by computer for enormous ranges.) The program tries each prime p up to n / 2 and tests whether n - p is prime too. An odd number can only be split as 2 plus an odd number, so the program finds a split only if n - 2 is prime. That is why 11 (9 is not prime) and 27 (25 is not prime) report that no split exists.

C More: sum of two primes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

All factors of a number. Testing every d up to n is slow and unnecessary. Factors come in pairs d and n / d, and one of the pair is always at most the square root. So the loop d <= n / d finds the small factor, and the partner n / d is the large one. The program stores both halves and prints the small ones in increasing order, then the large ones in the reverse order of discovery. For a perfect square, such as 144, the middle pair is the same number twice, and the code prints it once.

C More: all factors of a number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Change n to 144 to see the perfect-square case: the output has 15 factors, an odd number, and that only happens for squares.

Sum of the even-index Fibonacci numbers. With F(0) = 0 and F(1) = 1, the numbers at even positions are 0, 1, 3, 8, 21, and so on. The program adds them and checks the result against an identity: the sum of F(0) + F(2) + ... + F(2k) equals F(2k + 1) - 1. For k = 10 that is F(21) - 1 = 10,945. Cross-checking a loop with a closed-form result is a good habit.

C More: even-index Fibonacci sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Simple and compound interest. Simple interest is P ร— r ร— t / 100, the same amount every year. Compound interest earns interest on the interest: the total after t years is P ร— (1 + r / 100)^t. The program computes both, then prints a year-by-year table by adding the interest to the balance each year, which must agree with the pow formula. Money values here use double for simplicity; real accounting software uses integers (cents) to avoid rounding error. See Floating-point numbers.

C More: simple and compound interest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Number bases and bits

These practice bitwise operators, printf format specifiers and string conversions.

22. Decimal to binary, octal and hexadecimal

printf prints octal (%o) and hexadecimal (%x, %X) directly. C23 adds %b for binary, but not every C library supports it yet, so this program builds the binary string itself, filling a buffer from the right.

C 22. Decimal to other bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

23. Any base back to decimal

strtol parses a string in any base from 2 to 36 and tells you, through its end pointer, where it stopped, so you can reject trailing garbage. The hand-written loop shows the algorithm: multiply by the base, add the next digit.

C 23. Base to decimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

24. Count set bits and test powers of two

n & (n - 1) clears the lowest set bit, so the loop runs once per 1-bit (Brian Kernighan's trick). A power of two has exactly one set bit, which gives a one-line test. GCC and Clang also offer __builtin_popcount, a compiler extension; C23's <stdbit.h> standardizes stdc_count_ones, but many C libraries don't ship it yet.

C 24. Set bits and powers of two

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

25. Check the byte order (endianness)

Looking at an object through an unsigned char * is always allowed in C and shows how its bytes sit in memory. Our server is an x86-64 machine, which is little-endian: the least significant byte comes first. Code that writes binary files or network packets must not depend on this; see Binary Files.

C 25. Endianness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Strings

These practice strings, string functions, characters and ctype.h and safe string handling.

26. String length by hand

A C string is a char array ending in '\0', so its length is the number of characters before that byte. sizeof measures the whole array, including the terminator and any unused space.

C 26. String length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

27. Reverse a string in place

Swap the first character with the last, the second with the second-to-last, and stop in the middle. The string must be a modifiable array: string literals are read-only, so reverse("abc") would be undefined behavior.

C 27. Reverse a string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

28. Palindrome string

Two indexes walk toward each other, skipping anything that isn't a letter or digit and comparing case-insensitively. The (unsigned char) casts matter: passing a negative char to isalnum or tolower is undefined behavior.

C 28. Palindrome string

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

right points one past the character being compared, so it never has to go below zero, which matters because size_t is unsigned.

29. Count vowels, consonants, digits and spaces

<ctype.h> classifies characters; strchr on a string of vowels is a compact membership test.

C 29. Count character kinds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

30. Count lines, words and characters

A tiny version of the Unix wc tool. It reads the input one character at a time with getchar and counts a word whenever it moves from whitespace into a non-space character. Edit the Input box and run it again.

C 30. Line, word and character count

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

c is an int, not a char, because getchar must be able to return every byte value plus the distinct value EOF. The empty third line counts as a line but contains no words.

31. Character frequency

An array of 26 counters indexed by letter - 'a' replaces a map. This relies on 'a' to 'z' being consecutive, which is true in ASCII and UTF-8 (every system you're likely to use).

C 31. Character frequency

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

32. Anagram check

Two strings are anagrams when every letter appears the same number of times in both. Count up for the first string and down for the second; they are anagrams if every counter ends at zero. That's O(n), faster than sorting both strings.

C 32. Anagram check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

33. Capitalize every word

A flag remembers whether the previous character was whitespace. The function changes the array in place, so it gets a char *, not a const char *.

C 33. Capitalize words

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

34. Remove a character from a string

The classic two-index compaction: read visits every character, write advances only for characters you keep. It runs in one pass, with no extra buffer.

C 34. Remove a character

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

35. Run-length encoding

Turns aaabccdddd into a3b1c2d4. The output buffer has a fixed size, so the function writes with snprintf and reports failure instead of overflowing. That's the habit from Safe String Handling.

C 35. Run-length encoding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

36. Sort strings alphabetically

qsort passes the comparator pointers to the elements. The elements are const char *, so each argument is really a const char *const *, which is dereferenced once before calling strcmp. Forgetting that extra level is the most common qsort bug. See qsort and bsearch.

C 36. Sort strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

"Apricot" comes first because strcmp compares byte values, and every uppercase ASCII letter is smaller than every lowercase one.

Arrays

These practice arrays, pointers and arrays and sorting and searching algorithms.

37. Sum, average, minimum and maximum

One pass collects all four results. The array is passed as a pointer plus a length, because inside the function sizeof values would only measure the pointer.

C 37. Array statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

38. Second largest element

Track the largest and second largest in one pass. A found flag handles arrays where all values are equal, which have no second largest distinct value.

C 38. Second largest

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Linear search works on any array in O(n). Binary search needs a sorted array and halves the range each step, so it takes O(log n): about 20 steps for a million elements. low + (high - low) / 2 avoids the overflow of (low + high) / 2.

C 39. Linear and binary search

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The half-open range [low, high) keeps every index a valid size_t. The common version with high = count - 1 breaks when count is 0 or when middle - 1 would go below zero.

40. Bubble sort

Repeatedly swaps neighbors that are out of order. The swapped flag stops early when a pass changes nothing, so an already sorted array takes a single pass. It's O(nยฒ), fine for learning, too slow for real data: use qsort instead.

C 40. Bubble sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

41. Rotate an array

Rotating left by k with three reversals (the first k elements, the rest, then everything) works in place in O(n) time with no extra array.

C 41. Rotate an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

42. Remove duplicates from a sorted array

In a sorted array, duplicates sit next to each other, so the two-index compaction from program 34 removes them in one pass. The function returns the new length; the elements after it are leftovers.

C 42. Remove duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

43. Merge two sorted arrays

Compare the front elements, take the smaller one, repeat; then copy whatever is left of the other array. This is the heart of merge sort (see Sorting and Searching Algorithms).

C 43. Merge sorted arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

44. Count how often each value occurs

Sort a copy with qsort, then count runs of equal values. The comparator uses (x > y) - (x < y) instead of x - y, because the subtraction can overflow for large values.

C 44. Frequency of elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Matrices

These practice multidimensional arrays.

45. Matrix addition and multiplication

A 2ร—3 matrix times a 3ร—2 matrix gives a 2ร—2 matrix: element [i][j] is the dot product of row i of the first and column j of the second. Addition needs both matrices to have the same shape.

C 45. Matrix add and multiply

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

46. Transpose a matrix

Rows become columns: t[j][i] = m[i][j]. The function takes the sizes first so it can use them in the array parameter types (a variably modified parameter, which needs VLA support; GCC and Clang have it, MSVC doesn't).

C 46. Transpose a matrix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The cast in the last call is there because C (before C23) doesn't convert int (*)[2] to const int (*)[2] automatically; C23 finally allows that conversion, but the cast keeps the code portable.

47. Row sums, column sums and the diagonal

One pass over a square matrix fills a row-sum array and a column-sum array and adds up both diagonals.

C 47. Row and column sums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

More matrix programs: determinant, trace, boundary, rotation and sorted rows

Five more classics on square matrices. The determinant uses cofactor expansion along the first row: each element is multiplied by the determinant of the smaller matrix left after deleting its row and column, with alternating signs. That is recursion on a shrinking matrix, fine for small sizes (the cost grows like n!, so real code uses elimination instead). The trace is the sum of the main diagonal and the norm (the Frobenius norm) is the square root of the sum of all squares. Rotating 90 degrees clockwise maps m[i][j] to r[j][n - 1 - i].

C Determinant, trace, norm, boundary, rotation, equality and sorted rows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The determinant of this matrix is 2 x (3 - 2) - 0 + 1 x (1 - 3) = 0. The rotation reads the original matrix's first row 2 0 1 and writes it down the last column. Two matrices are equal only if every element matches, so the program stops at the first difference; comparing with memcmp would be wrong when padding or non-integer types are involved. A 2D int array is stored row after row, so m[i] is itself an array of N ints that qsort can sort in place. Swapping the first and last rows is the same idea with a temporary row array and memcpy calls.

Patterns and structures

More shapes are in C Pattern Printing Programs. These practice nested loops, printf field widths and structures.

48. Pyramid and Floyd's triangle

Each row of the pyramid prints rows - row spaces and then 2 * row - 1 stars. %*s takes the field width from an argument, so printf("%*s", n, "") prints n spaces without a loop.

C 48. Pyramid and Floyd's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

49. Pascal's triangle

Each entry is a binomial coefficient C(row, k), and the next one in the same row is C * (row - k) / (k + 1). Multiplying before dividing keeps the arithmetic exact, because the product is always divisible.

C 49. Pascal's triangle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

50. A fraction type with a struct

A struct groups a numerator and denominator into one value. Every function returns a normalized fraction (reduced, with a positive denominator), so equal values always have equal members and comparing them is trivial. Structs are copied by value when you pass or return them, which is cheap for small types like this. See Structures.

C 50. A fraction struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last call fails on purpose: make_fraction(1, 0) prints an error to stderr and ends the program with exit(EXIT_FAILURE), so "never printed" never appears. See Useful stdlib.h Functions for exit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. The sieve (program 11) starts crossing out multiples of p at p * p. Why is that safe?

    Any multiple k * p with k < p has a prime factor smaller than p (a factor of k), so that prime's pass already marked it.
  2. 2. In program 2, what does -7 % 2 evaluate to in C99 and later?

    Since C99, integer division truncates toward zero, and the remainder has the sign of the left operand, so -7 / 2 is -3 and -7 % 2 is -1.
  3. 3. Why does program 30 store the result of getchar() in an int instead of a char?

    EOF is a negative int distinct from every unsigned char value. Storing it in a char either confuses it with a real byte (signed char) or never matches EOF (unsigned char).
  4. 4. In program 36, what is each argument of the qsort comparator?

    qsort passes pointers to the elements it compares. The elements are const char * values, so the comparator receives pointers to those pointers and must dereference once.

Summary

  • Number classics (primes, GCD, digits, powers, factorization) come down to %, / and loops with good bounds: square-root limits written as d <= n / d, Euclid's algorithm, halving exponents.
  • Pick types deliberately: unsigned long long for fast-growing values, size_t for sizes and indexes, int for the result of getchar, unsigned char before every <ctype.h> call.
  • String classics are two-index scans over char arrays: reverse, palindrome, compaction. Always keep the null terminator in mind and write into fixed buffers with snprintf.
  • Array functions take a pointer and a length; sizeof array / sizeof array[0] only works where the array is declared.
  • qsort comparators receive pointers to elements and should return (x > y) - (x < y) rather than x - y.
  • Structs plus small functions give you clean value types, like the normalized Fraction.

Next: C Practice Exercises, where you write programs like these yourself and compare your solutions with ours.