Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

C Documentation

The language underneath operating systems and embedded devices — learn memory, pointers and how computers really work.

C is a small, fast, compiled language created in 1972 for the UNIX operating system. Linux, Windows kernels, databases, embedded devices and the runtimes of other languages are written in C. Learning C teaches you how memory, pointers and the computer really work.

1. Introduction & Installation

C source files (.c) are compiled into a machine-code executable before running.

Install a compiler

  • Windows: install MSYS2 and run pacman -S mingw-w64-ucrt-x86_64-gcc, or install the "Desktop development with C++" workload in Visual Studio. Add the bin folder to PATH.
  • macOS: xcode-select --install (gives clang, also available as gcc).
  • Linux: sudo apt install build-essential.
gcc --version
gcc hello.c -o hello      # compile
./hello                   # run (hello.exe on Windows)
#include <stdio.h>

int main(void) {
    printf("Hello, Codify!\n");
    return 0;   // 0 = success
}

Output:

Hello, Codify!

Useful flags: -Wall -Wextra (show warnings), -g (debug info), -O2 (optimise), -std=c17.

⚠️ Common error: undefined reference to 'WinMain' / 'main' — your file has no main function or you compiled the wrong file.

2. Basic Syntax

  • Every program starts at int main(void).
  • Statements end with ; and blocks use { }.
  • #include copies a header (like stdio.h for input/output) before compiling.
  • Comments: // one line and /* multi-line */.
#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);          // & gives the address to store into
    printf("Sum = %d\n", a + b);
    return 0;
}

Output (input 4 9):

Enter two numbers: 4 9
Sum = 13

⚠️ Common error: forgetting & in scanf("%d", a) — scanf needs the variable's address. The program may crash (segmentation fault).

Practice: Read the length and breadth of a rectangle and print its area and perimeter.

3. Variables & Data Types

Variables must be declared with a type before use.

Type Typical size Format specifier Example
char 1 byte %c 'A'
int 4 bytes %d 42
long long 8 bytes %lld 9000000000LL
float 4 bytes %f 3.14f
double 8 bytes %lf (scanf) / %f (printf) 3.14159
unsigned int 4 bytes %u 40u
#include <stdio.h>
#include <limits.h>

int main(void) {
    int age = 20;
    double pi = 3.14159;
    char grade = 'A';
    long long big = 9000000000LL;
    const int DAYS = 7;          // constant: cannot be changed

    printf("%d %.2f %c %lld %d\n", age, pi, grade, big, DAYS);
    printf("int max = %d, size of double = %zu bytes\n", INT_MAX, sizeof(double));
    printf("7/2 = %d, 7/2.0 = %.1f, (double)7/2 = %.1f\n", 7 / 2, 7 / 2.0, (double)7 / 2);
    return 0;
}

Output:

20 3.14 A 9000000000 7
int max = 2147483647, size of double = 8 bytes
7/2 = 3, 7/2.0 = 3.5, (double)7/2 = 3.5

⚠️ Common error: integer overflow — int x = 100000 * 100000; does not fit in int. Use long long and write 100000LL * 100000.

Practice: Convert a temperature from Celsius to Fahrenheit (F = C * 9 / 5 + 32) using double.

4. Operators

Category Operators
Arithmetic + - * / % (integer / drops the fraction)
Increment ++x, x++, --x, x--
Relational == != < > <= >= (result is 1 or 0)
Logical `&&
Bitwise `&
Assignment = += -= *= /= %= <<= >>=
Others ?: (ternary), sizeof, & (address), * (dereference), ,
#include <stdio.h>

int main(void) {
    int x = 5;
    int y = x++;        // y = 5, then x = 6
    int z = ++x;        // x = 7, then z = 7
    printf("%d %d %d\n", x, y, z);
    printf("%d %d %d\n", 17 / 5, 17 % 5, -17 / 5);
    printf("%d %d %d %d\n", 6 & 3, 6 | 3, 6 ^ 3, 1 << 5);
    printf("%s\n", (x > 3 && x < 10) ? "in range" : "out");
    return 0;
}

Output:

7 5 7
3 2 -3
2 7 5 32
in range

⚠️ Common error: if (x = 5) assigns 5 and is always true. Compile with -Wall to get a warning; write if (x == 5).

5. Conditional Statements

#include <stdio.h>

int main(void) {
    int marks = 72;
    if (marks >= 90) printf("A\n");
    else if (marks >= 60) printf("B\n");
    else printf("C\n");

    int day = 3;
    switch (day) {
        case 1: printf("Monday\n"); break;
        case 2: printf("Tuesday\n"); break;
        case 3: printf("Wednesday\n"); break;
        default: printf("Another day\n");
    }
    return 0;
}

Output:

B
Wednesday

In C, any non-zero value is true and 0 is false.

⚠️ Common error: forgetting break in a switch — execution "falls through" into the next case.

Practice: Read three numbers and print the largest using nested if.

6. Loops

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 5; i++) printf("%d ", i);
    printf("\n");

    int n = 12345, rev = 0;
    while (n > 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    printf("reversed = %d\n", rev);

    int k = 0;
    do {
        printf("runs at least once (k=%d)\n", k);
    } while (k > 0);

    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) continue;   // skip even
        if (i > 7) break;           // stop the loop
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output:

1 2 3 4 5 
reversed = 54321
runs at least once (k=0)
1 3 5 7 

⚠️ Common error: a stray semicolon for (i = 0; i < n; i++); — the loop body becomes empty and the block below runs only once.

Practice: Print a right-angled star triangle of height n, and check whether a number is prime.

7. Functions

A function must be declared before use (a prototype at the top, or defined above main). Arguments are passed by value (a copy); pass a pointer to modify the caller's variable.

#include <stdio.h>

int add(int a, int b);            // prototype
void swap(int *a, int *b);
long long factorial(int n);

int main(void) {
    int x = 3, y = 8;
    printf("add = %d\n", add(x, y));
    swap(&x, &y);
    printf("after swap: x=%d y=%d\n", x, y);
    printf("10! = %lld\n", factorial(10));
    return 0;
}

int add(int a, int b) { return a + b; }

void swap(int *a, int *b) {        // pointers let us change the caller's variables
    int t = *a;
    *a = *b;
    *b = t;
}

long long factorial(int n) {      // recursion
    return n <= 1 ? 1 : n * factorial(n - 1);
}

Output:

add = 11
after swap: x=8 y=3
10! = 3628800

static variables inside a function keep their value between calls.

⚠️ Common error: implicit declaration of function — you used a function before declaring it. Add a prototype or the right #include.

Practice: Write int gcd(int a, int b) using recursion (Euclid's algorithm).

8. Arrays & Data Structures

Arrays store fixed-size elements of one type in contiguous memory. Strings are char arrays ending with '\0'.

#include <stdio.h>
#include <string.h>

int main(void) {
    int a[5] = {4, 8, 15, 16, 23};
    int n = sizeof(a) / sizeof(a[0]);
    int sum = 0, max = a[0];
    for (int i = 0; i < n; i++) {
        sum += a[i];
        if (a[i] > max) max = a[i];
    }
    printf("n=%d sum=%d max=%d\n", n, sum, max);

    int m[2][3] = {{1, 2, 3}, {4, 5, 6}};   // 2-D array
    printf("m[1][2] = %d\n", m[1][2]);

    char name[20] = "Codify";
    char copy[20];
    strcpy(copy, name);
    strcat(copy, " C");
    printf("%s | length %zu | cmp %d\n", copy, strlen(copy), strcmp("abc", "abd") < 0);
    return 0;
}

Output:

n=5 sum=66 max=23
m[1][2] = 6
Codify C | length 8 | cmp 1

Structures and unions group related data:

#include <stdio.h>

struct Student {
    char name[30];
    int roll;
    float marks;
};

union Value {        // all members share the same memory
    int i;
    float f;
};

int main(void) {
    struct Student s = {"Asha", 12, 91.5f};
    struct Student *p = &s;
    printf("%s %d %.1f\n", s.name, p->roll, p->marks);   // -> with pointers
    union Value v;
    v.i = 10;
    printf("union size = %zu\n", sizeof(v));
    return 0;
}
Asha 12 91.5
union size = 4

C has no built-in lists or maps — you build linked lists, stacks and queues yourself with structs and pointers.

⚠️ Common error: out-of-bounds access (a[5] in an array of 5) is undefined behaviour — C does not check. It may print garbage or crash.

Practice: Store 5 students in an array of structs and print the topper.

9. Object-Oriented Programming

C is not object-oriented — there are no classes, inheritance or methods. You can still apply the ideas:

  • Encapsulation: keep a struct and the functions that work on it in one .c file, expose only a header.
  • "Methods": functions that take a pointer to the struct (void account_deposit(Account *a, int amt)).
  • Polymorphism: function pointers inside a struct.
#include <stdio.h>

typedef struct Shape {
    const char *name;
    double (*area)(double);      // function pointer = "virtual method"
} Shape;

double square_area(double s) { return s * s; }
double circle_area(double r) { return 3.14159 * r * r; }

int main(void) {
    Shape shapes[2] = {{"square", square_area}, {"circle", circle_area}};
    for (int i = 0; i < 2; i++)
        printf("%s: %.2f\n", shapes[i].name, shapes[i].area(2.0));
    return 0;
}

Output:

square: 4.00
circle: 12.57

For real OOP, move on to C++, which was designed as "C with classes".

10. Advanced Concepts

Pointers store addresses. &x = address of x, *p = value at address p. Arrays decay to a pointer to their first element.

#include <stdio.h>

int main(void) {
    int x = 10;
    int *p = &x;
    *p = 25;                         // changes x through the pointer
    printf("x=%d, *p=%d\n", x, *p);

    int a[3] = {10, 20, 30};
    int *q = a;                      // same as &a[0]
    printf("%d %d %d\n", *q, *(q + 1), q[2]);   // pointer arithmetic
    return 0;
}
x=25, *p=25
10 20 30

Dynamic memory lives on the heap until you free it:

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

int main(void) {
    int n = 5;
    int *arr = malloc(n * sizeof(int));
    if (arr == NULL) return 1;            // always check
    for (int i = 0; i < n; i++) arr[i] = i * i;
    arr = realloc(arr, 2 * n * sizeof(int));
    for (int i = n; i < 2 * n; i++) arr[i] = i * i;
    printf("%d %d\n", arr[4], arr[9]);
    free(arr);                            // give memory back
    arr = NULL;
    return 0;
}
16 81

File handling:

#include <stdio.h>

int main(void) {
    FILE *f = fopen("data.txt", "w");
    if (!f) { perror("fopen"); return 1; }
    fprintf(f, "%d %d\n", 3, 4);
    fclose(f);

    int a, b;
    f = fopen("data.txt", "r");
    fscanf(f, "%d %d", &a, &b);
    fclose(f);
    printf("read %d and %d\n", a, b);
    return 0;
}
read 3 and 4

Other topics: the preprocessor (#define, #ifdef), multi-file programs with header files, enum, typedef, bit fields, volatile, and tools like gdb and Valgrind (finds memory leaks).

⚠️ Common error: memory leaks (forgetting free), using memory after free (dangling pointer) and dereferencing NULL — the most common C bugs. Set pointers to NULL after freeing.

11. Examples with Output

Example 1 — Bubble sort

#include <stdio.h>

int main(void) {
    int a[] = {5, 1, 4, 2, 8}, n = 5;
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; }
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}
1 2 4 5 8 

Example 2 — Count vowels in a string

#include <stdio.h>
#include <ctype.h>

int main(void) {
    char s[] = "Learning C at Codify";
    int v = 0;
    for (int i = 0; s[i] != '\0'; i++) {
        char c = tolower(s[i]);
        if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') v++;
    }
    printf("vowels = %d\n", v);
    return 0;
}
vowels = 6

Example 3 — Singly linked list

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

typedef struct Node { int val; struct Node *next; } Node;

Node *push(Node *head, int v) {
    Node *n = malloc(sizeof(Node));
    n->val = v;
    n->next = head;
    return n;
}

int main(void) {
    Node *head = NULL;
    for (int i = 1; i <= 4; i++) head = push(head, i * 10);
    for (Node *p = head; p; p = p->next) printf("%d -> ", p->val);
    printf("NULL\n");
    while (head) { Node *t = head->next; free(head); head = t; }
    return 0;
}
40 -> 30 -> 20 -> 10 -> NULL

12. Practice Problems

Solve these on Codify (choose C in the editor):

  1. Sum of Two Numbers — scanf / printf and long long (Easy)
  2. Maximum in an Array — arrays and loops (Easy)
  3. Reverse a String — two indices swapping chars (Easy)
  4. Check Palindrome — compare from both ends (Easy)
  5. Fibonacci Number — loop vs recursion (Easy)
  6. Binary Search — lo, hi, mid (Easy)
  7. Two Sum — nested loops, then think of sorting + two pointers (Easy)
  8. Maximum Subarray Sum — Kadane's algorithm (Medium)

Also try: implement your own strlen, strcpy and a dynamic array that grows with realloc.

13. Interview Questions

1. What is the difference between malloc and calloc? malloc(size) allocates uninitialised memory; calloc(n, size) allocates n*size bytes and sets them to zero.

2. What is a dangling pointer? A pointer that still holds the address of memory that has been freed or gone out of scope. Using it is undefined behaviour.

3. Difference between struct and union? A struct gives every member its own memory (size ≥ sum of members); a union's members share one block (size = largest member).

4. What does static mean in C? Inside a function: the variable keeps its value between calls. At file level: the variable/function is visible only in that file.

5. Call by value vs call by reference? C always passes by value; you simulate pass-by-reference by passing a pointer (swap(&a, &b)).

6. What is the difference between ++i and i++? ++i increments then returns the new value; i++ returns the old value then increments.

7. What is a segmentation fault? A crash caused by accessing memory you are not allowed to — e.g. dereferencing NULL, out-of-bounds access, or writing to a string literal.

8. What is void *? A generic pointer that can hold the address of any type (returned by malloc); it must be cast/assigned to a typed pointer before dereferencing.

9. Stack vs heap memory? Local variables live on the stack (automatic, fast, limited size). malloc memory lives on the heap (manual lifetime, larger).

10. What does the const keyword do with pointers? const int *p — can't change the value through p; int *const p — can't change where p points.

14. Cheat Sheet & References

Program skeleton

// Basic program
#include <stdio.h>
int main(void) { printf("Hi\n"); return 0; }
// Compile and run
// gcc main.c -o main -Wall && ./main

Input and output

scanf("%d", &n);
scanf("%d %lld %lf %c %s", &a, &b, &d, &c, str);
printf("%d %lld %.2f %c %s\n", a, b, d, c, str);
fgets(line, sizeof line, stdin);

Types and limits

char c = 'A'; int i = 1; long long ll = 1LL << 40;
float f = 1.5f; double d = 2.5; unsigned u = 4u;
#include <limits.h>
INT_MAX; INT_MIN; LLONG_MAX;
sizeof(int); (double)a / b;

Control flow

if (a > b) { } else if (a == b) { } else { }
switch (x) { case 1: break; default: break; }
for (int i = 0; i < n; i++) { }
while (cond) { }
do { } while (cond);

Arrays and strings

int a[5] = {0};
int n = sizeof(a) / sizeof(a[0]);
int m[3][3];
#include <string.h>
strlen(s); strcpy(d, s); strcat(d, s); strcmp(a, b);
strchr(s, 'x'); strstr(s, "ab");

Pointers and memory

int *p = &x; *p = 5;
int *a = malloc(n * sizeof(int));
int *z = calloc(n, sizeof(int));
a = realloc(a, 2 * n * sizeof(int));
free(a); a = NULL;

Structs and functions

typedef struct { int x, y; } Point;
Point pt = {1, 2}; Point *pp = &pt; pp->x = 5;
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }

Files

FILE *f = fopen("a.txt", "r");
fprintf(f, "%d\n", x); fscanf(f, "%d", &x);
fclose(f);

Official documentation