Programming in C
What this domain tests
You must read and write short C programs: declarations, operators, control statements, loops, functions, arrays, strings, structures and simple file handling. A typical question gives a snippet and asks for output, or asks you to correct a faulty program.
Core rules
- A C program has preprocessor directives, function definitions, and execution starting at main().
- Format specifiers: %d int, %f float, %c char, %s string, %lf double. scanf needs the address of the variable, as in scanf("%d", &n).
- Integer division truncates: 7/2 is 3 and 7%2 is 1. Mixing int and float promotes the result to float, but only after the integer part is computed.
- Loops: for, while (test before body) and do-while (body runs at least once). Arrays index from 0 to size-1.
- Strings are char arrays ending with '\0'; use %s or library functions such as strlen and strcpy.
- A function returns at most one value; use pointers or structures to send back more.
Worked example
int i, s = 0; for (i = 1; i <= 4; i++) s = s + i*i; printf("%d", s); Trace it: i = 1 adds 1, i = 2 adds 4, i = 3 adds 9, i = 4 adds 16. The loop ends when i becomes 5, so the printed value is 30. Note that s was initialised; without initialisation the answer is unpredictable.
Traps that cost marks
- Writing = where == is needed inside if.
- Omitting & in scanf, or adding & in printf.
- A semicolon after for(...) making the loop body empty.
- Off-by-one array access, such as a[10] for an array of size 10.
- Using %d with a float variable.
- Declaring float x = 5/2 and expecting 2.5; it stores 2.0.