Programming in C / Problem Solving
Programming in C / Problem Solving
This domain applies programming concepts in C: tokens, data types, operators, input/output, control statements, functions, arrays and strings. Expect code reading, error spotting and short program writing.
Core rules
- C is compiled;
mainreturnsint. Statements end with semicolons. Headers such as<stdio.h>provide declarations likeprintfandscanf. scanfneeds addresses for ordinary variables:scanf("%d", &n);. Strings read with%sdo not use&because an array name decays to an address.- Integer division truncates:
5/2is2; use a floating type for fractional results. =assigns;==compares. Arrays use zero-based indexing.- Functions receive arguments, may return one value, and need a prototype or definition before use.
Worked example
To sum the first n natural numbers: int n, i, sum=0; scanf("%d", &n); for(i=1; i<=n; i++) sum += i; printf("%d", sum);. For n=4 the loop adds 1, 2, 3, 4, producing 10. The reasoning is initialisation, condition, update: sum starts at zero so the first addition is correct; i<=n includes n.
Traps
Forgetting & in scanf for an int leads to undefined behaviour. Writing if (x = 1) assigns instead of compares. 5/2 is not 2.5 in integer arithmetic. Array index n is out of bounds for an n-element array. Missing semicolons and mismatched braces are syntax errors, not logic errors.