Programming in a High-Level Language (C)
What the examiner tests
Reading and writing short C programs: declarations, expressions, conditions and loops, plus predicting output.
Core rules
- Every C program has
main(), statements end with;, and blocks are enclosed in{ }.#include <stdio.h>is needed forprintf/scanf. - Data types:
int(whole numbers),float,double,char(one character in single quotes).printfuses%d,%f,%c,%s;scanfneeds&before each variable. - Operators: arithmetic
+ - * / %; relational< > <= >= == !=; logical&& || !; assignment=; increment/decrement++ --.*,/,%bind tighter than+and-, which bind tighter than relational operators, which bind tighter than logical operators. Use brackets when unsure. /between two integers gives an integer quotient (7/2 = 3), and%works only on integers.- Control:
if,if–else,else ifladder,switch(withbreakanddefault),for,while, anddo–while, which always runs at least once.
Worked example
int a = 7, b = 2;
float c = a / b;
printf("%.1f", c);
Output: 3.0. The division happens first in integer arithmetic, giving 3; only then is 3 converted to float. To get 3.5, write (float)a / b.
Traps
if (a = 5)assigns instead of comparing; use==.- Omitting
&inscanf("%d", n). - Forgetting
breakinswitch, so control falls through. - Putting a semicolon after
for(...)orif(...), which detaches the body. - Assuming
5 / 2is 2.5 in C.