Programming in C
The largest practical domain: program structure, data types and operators, control structures, functions, arrays, strings, pointers, structures and file handling.
Core rules
- Execution starts at
main(). Statements end with a semicolon; blocks use braces. - Arrays are 0-indexed; a string is a char array terminated by
'\0'. - C is pass-by-value: a function receives copies. To modify a caller's variable, pass its address and dereference with
*. - File I/O:
FILE *fp = fopen("data.txt", "r");- check for NULL, thenfclose(fp).
Worked example
int i, s = 0;
for (i = 1; i <= 5; i++) {
if (i % 2 == 0) continue;
s += i;
}
Trace: i=1 odd → s=1; i=2 even → continue skips the addition; i=3 → s=4; i=4 skipped; i=5 → s=9; loop ends when i=6. Output: 9.
Library calls worth memorising
strlen, strcpy, strcmp (returns 0 when equal), strcat from <string.h>; printf/scanf from <stdio.h>; malloc/free from <stdlib.h>.
Traps
Writing if (a = 5) instead of ==; omitting & in scanf("%d", &x); expecting an array to know its length (use strlen or pass n); assuming 5/2 gives 2.5 (it gives 2); leaving a string without '\0'; using a pointer after free().