Learn compiled programming, explicit types, pointers and memory management.

Before starting: Files, terminal commands, and a C compiler.

Practice project: Build a text-file score reader that checks every resource operation.

1. C Architecture, Compilation & Setup

  1. C Architecture, History & The GCC Compilation Pipeline
  2. Structure of a C Program: #include, main() & return Codes
  3. Standard I/O: printf(), Escape Sequences & Console Buffering
  4. Comments, Coding Style & Preprocessor Overview

2. Types, Variables & Format Specifiers

  1. Primitive Data Types & sizeof Operator
  2. Variables, Scope, const & Modern <stdint.h> Fixed-Width Types
  3. Format Specifiers & Field Width Alignment in printf()
  4. Type Conversions: Implicit Promotion vs Explicit Casting

3. Operators & Expression Evaluation

  1. Arithmetic, Modulo & Compound Assignment Operators
  2. Increment & Decrement: Prefix vs Postfix (++i vs i++)
  3. Relational & Logical Operators with Short-Circuit Evaluation
  4. Bitwise Operators (&, |, ^, ~, <<, >>) & Bitmasks

4. Control Flow & Branching

  1. if, else if, else Decision Structures & Nested Conditions
  2. Ternary Operator (?:) for Inline Conditional Expressions
  3. switch Statements, case Labels, break & Intentional Fallthrough
  4. Scope, Variable Shadowing & Storage Duration

5. Loops & Iteration Mechanics

  1. while & do-while Loops
  2. for Loops: Anatomy, Multiple Expressions & C99 Loop Declarations
  3. Nested Loops & Matrix Traversal Patterns
  4. Loop Control: break, continue & goto for Error Unwinding

6. Arrays & Matrix Operations

  1. One-Dimensional Arrays: Declaration, Bounds & Contiguous Memory
  2. Two-Dimensional Arrays, Matrices & Row-Major Storage
  3. Array Searching: Linear Search vs Binary Search
  4. Array Sorting: Bubble Sort, Selection Sort & Insertion Sort

7. Strings & String Handling (string.h)

  1. C Strings: Null-Terminated Character Arrays (\0) & Memory
  2. Core String Functions: strlen, strcpy, strcat & strcmp
  3. Safe String Handling: strncpy, strncat & snprintf() Bounds Enforcement
  4. String Parsing & Tokenization: sscanf() & strtok_r()

8. Pointers & Memory Addressing

  1. Pointers Fundamentals: Memory Addresses (&) & Dereferencing (*)
  2. Pointer Arithmetic & Array Navigation (ptr + i)
  3. Pass-by-Reference in C Using Pointers
  4. Void Pointers (void*), Null Pointers & Pointer-to-Pointer (**)

9. Functions, Recursion & Storage Classes

  1. Function Declarations, Prototypes & Header (.h) Separation
  2. Recursion & Call Stack Mechanics (Stack Overflow)
  3. Storage Classes: auto, static, extern & register
  4. Function Pointers & Callback Architecture

10. Structures (struct), Unions & typedef

  1. Structures (struct): User-Defined Types & Dot Operator (.)
  2. Pointers to Structs & The Arrow Operator (->)
  3. typedef, Clean Aliasing & Self-Referential Linked Lists
  4. Unions, Memory Overlap & Enums (enum)

11. Dynamic Memory Allocation (Heap)

  1. Heap Memory Management: malloc() & free() Lifecycles
  2. Zero-Initialized Memory (calloc) & Dynamic Resizing (realloc)
  3. Dangling Pointers, Memory Leaks & Valgrind Diagnostics
  4. Memory Manipulation: memcpy(), memmove(), memset() & memcmp()

12. File I/O, Preprocessor & System Programming

  1. File I/O Streams: fopen(), Mode Flags & fclose()
  2. Reading Text Files: fgets(), fgetc() & feof() Safety
  3. Binary File I/O: fread(), fwrite() & fseek()
  4. The Preprocessor: #define Macros, #ifdef & Conditional Compilation
  5. Command-Line Arguments: int main(int argc, char *argv[])
  6. Variable Argument Lists (<stdarg.h>) & va_list Mechanics

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Check C input and file errors

Library calls can fail even when the program compiles. Inspect a return value before using the resource it represents. A failed fopen returns a null pointer; passing it to file-reading functions is invalid. This example reports the operating-system error and exits unsuccessfully. It closes the stream on the successful path.

Hosted C17 environment with GCC or Clang

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *file = fopen("score.txt", "r");
    if (file == NULL) {
        perror("score.txt");
        return EXIT_FAILURE;
    }
    if (fclose(file) == EOF) {
        perror("closing score.txt");
        return EXIT_FAILURE;
    }
    puts("File opened and closed");
    return EXIT_SUCCESS;
}
Check the output
With a readable file: File opened and closed. Without it: an error message on stderr; wording depends on the operating system.

Use fgets to read one line. Distinguish end-of-file from a read error with ferror before deciding which message to display.

Open the C learning path on DevStudyHub · Play coding games on this blog

More C lessons and practice

Choose a topic below to open its full lesson on DevStudyHub. Read the explanation, try the example in the stated environment, and compare your result before continuing.

Extra practice

  1. Trace changing state and check loop boundaries
  2. Check C input and file errors

Follow the ordered C learning path · Practice with coding games · Visit DevStudyHub

Five beginner C programs with worked examples

Start with the program below. Put one example at a time inside main, just above return 0. Save it as practice.c. With GCC installed, compile using gcc -std=c11 -Wall practice.c -o practice. Run ./practice on Linux or .\practice.exe in Windows PowerShell.

#include <stdio.h>
int main(void) {
    /* Put your example here. */
    return 0;
}

Convert Fahrenheit to Celsius

A sensor reads 68 °F. Subtract 32 to align the zero points, then scale the difference by five ninths. Use decimal constants so C keeps the fractional part.

double f = 68;
printf("%.1f C\n", (f - 32) * 5.0 / 9.0);

Expected output 20.0 C

Try 32 and 212. They should give 0.0 and 100.0.

Calculate the area and circumference of a circle

A circular garden has a radius of 3 metres. The fence length is the circumference. The ground it encloses is the area.

const double pi = 3.141592653589793;
double r = 3;
printf("Fence %.2f m, ground %.2f m2\n", 2*pi*r, pi*r*r);

Expected output Fence 18.85 m, ground 28.27 m2

Double the radius. The fence length doubles and the area grows fourfold.

Find a factorial with a loop

For four different books, there are four choices for the first spot, three for the next, then two, then one. Multiply these counts to get 4 factorial.

unsigned long result = 1;
for (int k = 2; k <= 4; ++k) {
    result *= k;
}
printf("%lu\n", result);

Expected output 24

Trace the accumulator: 1 → 2 → 6 → 24. With an upper limit of zero the loop is skipped and the result is 1. Use small values because integer types have a maximum.

Swap two numbers using a temporary variable

To exchange two seat assignments, save the first value before overwriting it.

int left = 7, right = 12;
int saved = left;
left = right;
right = saved;
printf("%d %d\n", left, right);

Expected output 12 7

Trace left, right and saved after each assignment.

Check whether three lengths form a triangle

Three positive lengths form a triangle only if each pair adds up to more than the third side. Equality makes a straight line.

double a = 3, b = 4, c = 5;
int fits = a > 0 && b > 0 && c > 0 &&
           a+b > c && a+c > b && b+c > a;
puts(fits ? "Triangle" : "No triangle");

Expected output Triangle

Change the lengths to 2, 3 and 5. The first two sides meet exactly end to end.

C programming practice with decisions and loops

Use one example at a time inside main in the starter program above. Predict the result before you run it.

Print a greeting with puts

A C program starts in main. To print one line, pass its text to puts. The function adds the line break for you.

puts("Hello, library!");

Expected result

Hello, library!

Add two numbers

A book cart has 18 books upstairs and 7 downstairs. Store each count in an int and add the counts before printing.

int upstairs = 18, downstairs = 7;
printf("%d books\n", upstairs + downstairs);

Expected result

25 books

Calculate gross salary

For this exercise, gross pay consists of basic pay plus a housing allowance of 10% and a travel allowance of 5% of basic pay. Both percentages use the same starting amount.

double basic = 20000.0;
double housing = basic * 0.10;
double travel = basic * 0.05;
printf("Gross pay %.2f\n", basic + housing + travel);

Expected result

Gross pay 23000.00

Assign a student grade with if and else

Test the highest mark first. In this practice scale, 80 earns A, 65 earns B, 50 earns C, and lower marks need review. A mark outside 0 to 100 is invalid.

int mark = 65;
if (mark < 0 || mark > 100) puts("Invalid mark");
else if (mark >= 80) puts("A");
else if (mark >= 65) puts("B");
else if (mark >= 50) puts("C");
else puts("Review");

Expected result

B. Try 64 and 101 to check both a grade boundary and invalid input.

Print a multiplication table with a for loop

Run the same calculation for each multiplier from 1 through 10. On each pass, i has a new value and the number 7 stays fixed.

for (int i = 1; i <= 10; ++i) {
    printf("7 x %d = %d\n", i, 7 * i);
}

Expected result

The first line is 7 x 1 = 7. The tenth line is 7 x 10 = 70.

Draw a staircase with nested loops

Think of a row as one trip through the outer loop. The inner loop prints one star per column. Move to the next line only after the inner loop finishes.

for (int row = 1; row <= 3; ++row) {
    for (int col = 1; col <= row; ++col) {
        putchar('*');
    }
    putchar('\n');
}

Expected result

*
**
***

Follow prefix and postfix updates

Postfix returns the old value and then changes the variable. Prefix changes it first. Keep each update in a separate statement so the sequence is clear.

int seats = 4;
int before = seats++;
int after = --seats;
printf("%d %d %d\n", before, after, seats);

Expected result

4 4 4. The seat count moves from 4 to 5, then back to 4.

Choose a menu command with switch

A switch selects the case matching a value. break ends the selected case. default handles anything else.

char choice = 'r';
switch (choice) {
    case 'r': puts("Read"); break;
    case 'w': puts("Write"); break;
    default: puts("Unknown choice");
}

Expected result

Read. Change the letter to x to exercise the default case.

C file handling for beginners: draw a triangle and read it back

Start in a fresh practice directory with a C11 compiler. Save the program as triangle.c, compile with cc -std=c11 -Wall -Wextra triangle.c -o triangle, and run the resulting executable. The x in the write mode asks the library to create a new file exclusively. A second run in the same directory should report an error if triangle.txt already exists.

#include <stdio.h>

int main(void) {
    FILE *out = fopen("triangle.txt", "wx");
    if (!out) { perror("triangle.txt"); return 1; }
    for (int row = 1; row <= 4; ++row) {
        for (int col = 0; col < row; ++col) {
            if (fputc('*', out) == EOF) { fclose(out); return 1; }
        }
        if (fputc('\n', out) == EOF) { fclose(out); return 1; }
    }
    if (fclose(out) == EOF) return 1;
    FILE *in = fopen("triangle.txt", "r");
    if (!in) { perror("triangle.txt"); return 1; }
    int ch;
    while ((ch = fgetc(in)) != EOF) putchar(ch);
    int failed = ferror(in);
    fclose(in);
    return failed ? 1 : 0;
}

Trace the two loops

*
**
***
****

Each outer iteration chooses one row. The inner loop visits columns zero through row minus one, so row four receives four stars. The newline is outside the inner loop. To make a descending triangle, change the outer loop to start at four and continue while row is positive, subtracting one each iteration. The file will then start with four stars.

Use bitwise AND to select a drawing option

Suppose bit zero means draw a border and bit one means print row numbers. With unsigned options = 3u;, both options are enabled. Test row numbers with (options & 2u) != 0u. In binary, 11 AND 10 gives 10. Change options to 1u and the result becomes zero. Logical AND would only check whether both operands are nonzero.

C interview practice: explain the output and the error paths

Why store the return from fgetc in an int?

The function returns a byte value converted to int or the special EOF value. Narrowing the value to char before the comparison can lose that distinction.

Why check fclose after writing?

Output can still be buffered. Closing the stream can reveal a write failure.

How can you distinguish a read error from a normal end of file?

Both stop the loop. Inspect ferror on the still-open input stream to detect a read failure.

The Open Group file-opening reference

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.