Start here: how coding actually works
A program is a list of instructions for a computer. The computer is extremely fast and extremely literal: it does exactly what you wrote, in order, top to bottom. It never guesses what you meant.
How C code becomes a running program
- You write code in a
.cfile. It's just text. - A compiler translates it into machine language the computer understands.
- If you broke a rule (a missing
;, a misspelled word), the compiler refuses and shows an error. Fix it and try again. - If it compiles, the program runs and shows its output.
To practise without installing anything, search for an online C compiler such as OnlineGDB or Programiz, paste code in, and press Run.
Words you'll keep hearing
| Word | Plain meaning |
|---|---|
| Statement | One instruction, ending with ; |
| Variable | A labelled box that holds one value, like age holding 19 |
| Data type | What kind of value the box holds: whole number, decimal or character |
| Output | What the program shows on screen (printf) |
| Input | What the user types in (scanf) |
| Condition | A yes/no question, like marks >= 50 |
| Loop | Repeating some code while a condition stays true |
| Comment | Notes after // or inside /* */. The computer ignores them. |
Change the name and switch \n on and off to see how the output changes. Highlighted lines are the ones printing something.
; does the same job for the compiler. Without it, the compiler can't tell where one instruction stops and the next one starts.C basics: structure, variables, input/output, operators
The skeleton of every C program
#include <stdio.h> // gives you printf and scanf
int main() { // execution always starts here
printf("Hello\n"); // every statement ends with ;
return 0; // 0 = program ended normally
}
;, a missing #include <stdio.h>, or unmatched { }. C is case-sensitive: Printf is wrong.#include <stdio.h> borrows a toolbox that contains printf and scanf. int main() is the front door: the computer always starts here. Everything between { and } is your program. return 0; means "finished, no problems".Variables and data types
A variable is a named box in memory. You must declare its type before using it.
| Type | Stores | Example | Format |
|---|---|---|---|
int | whole numbers | int age = 19; | %d |
float | decimals | float gpa = 3.5; | %f |
double | bigger, more precise decimals | double pi = 3.14159; | %lf |
char | one character, in single quotes | char g = 'A'; | %c |
int age = 19; means "make a box that holds whole numbers, label it age, and put 19 inside". Later, age = 20; swaps the 19 for 20. A box holds one value at a time.Naming rules: letters, digits and _ only. Can't start with a digit, no spaces, can't be a keyword like int or for. So total_marks is valid, but 2marks and my marks are not.
Constants: const float PI = 3.14; or #define PI 3.14 (no ; and no = with #define).
Output and input
int n; float price;
printf("Enter a number: ");
scanf("%d", &n); // & = "address of n", required
scanf("%f", &price);
printf("n = %d, price = %.2f\n", n, price); // %.2f = 2 decimals
&n means "the location of n". Even experienced programmers forget the & sometimes, so it's worth double-checking.Escape sequences: \n new line, \t tab, \\ backslash, \" quote.
Operators
| Kind | Operators | Watch out |
|---|---|---|
| Arithmetic | + - * / % | 7/2 is 3 with ints. % is the remainder, ints only. |
| Relational | == != > < >= <= | Result is 1 (true) or 0 (false) |
| Logical | && || ! | AND, OR, NOT |
| Assignment | = += -= *= /= %= | x += 3 means x = x + 3 |
| Increment | ++ -- | x++: use, then add. ++x: add, then use. |
Precedence (high to low): ! ++ -- → * / % → + - → < > <= >= → == != → && → || → =. Brackets beat everything.
Type casting: (float)7/2 gives 3.5.
Change a and b. Watch / and % especially.
Read x++ as "use x, then add 1" and ++x as "add 1, then use x". On a line of their own (x++;), both just add 1. The difference only shows when the value is used in the same statement.
Decisions with if, else if and else
The program runs a block only when its condition is true. In C, any non-zero value is true and 0 is false.
Three forms
// 1. simple if
if (marks >= 50) {
printf("Pass");
}
// 2. if-else
if (n % 2 == 0)
printf("Even");
else
printf("Odd");
// 3. else-if ladder: checked top to bottom, the FIRST true one runs
if (marks >= 85) printf("A");
else if (marks >= 70) printf("B");
else if (marks >= 50) printf("C");
else printf("F");
The highlighted lines are the ones that actually run.
marks >= 50 first, a student with 95 would get C: 95 >= 50 is already true, so the rest is never checked. Always go from the strictest condition to the loosest.== and not =?= means "put this value in the box". == asks "are these equal?". They look alike, but in C they do completely different jobs.Nested if
if (a > b) {
if (a > c) printf("a is largest");
else printf("c is largest");
} else {
if (b > c) printf("b is largest");
else printf("c is largest");
}
Ternary operator (short if-else)
int max = (a > b) ? a : b; // condition ? if-true : if-false
if (x = 5) assigns, so it's always true. Use ==. A ; right after if (...) ends the if, so the next line always runs. Without braces, only one statement belongs to the if. An else pairs with the nearest unmatched if.switch-case: choosing from fixed values
Use it when one variable is compared against exact values, like menu choices, grades or day numbers.
int day;
scanf("%d", &day);
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
case 6:
case 7: printf("Weekend"); break; // two cases share code
default: printf("Invalid"); // runs if nothing matches
}
The rules
- The expression must be int or char, not float and not a string.
- Case labels must be constants (
case 3:,case 'a':), not variables or ranges likecase x > 5. - Case values can't be duplicated.
- No
breakmeans fall-through: execution keeps running into the next cases until it hits a break or the closing}. defaultis optional and can go anywhere, but it usually goes last.
break is the door opening so you can get out. Without it, you'd keep riding down through every floor below.Pick a day, then turn break off to see fall-through.
break does. Falling through also lets several cases share the same code (case 6 and case 7 → Weekend).char op = '+';
switch (op) {
case '+': printf("%d", a + b); break;
case '-': printf("%d", a - b); break;
case '*': printf("%d", a * b); break;
case '/': printf("%d", a / b); break;
default: printf("Unknown operator");
}
marks >= 50 need if-else.Loops: for, while, do-while
A loop repeats a block. Every loop has three parts: start (initialise), condition (keep going?) and update (move towards the end).
for loop: when you know how many times
for (int i = 1; i <= 5; i++) { // start; condition; update
printf("%d ", i); // 1 2 3 4 5
}
Order: start once → check → body → update → check → body … until the check fails.
i is just the counter.Set the values, then press Next step to watch the computer work through the loop one step at a time.
Try a step of 2. Or set step to -1 with <= to see an infinite loop.
while loop: checks first, may run 0 times
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; // forget this and you get an infinite loop
}
i <= 5 is true. If i never changes, it stays at 1, the condition is true forever, and the program never stops. Something inside the loop must move i towards the end.for when you know how many times ("print 10 numbers"). Use while when you repeat until something happens ("keep dividing until n becomes 0"). Either one can do the other's job. It's about which reads more naturally.Type any number. This is the reverse-a-number program, traced round by round.
while (n > 0) {
d = n % 10; // take the last digit
rev = rev * 10 + d; // stick it on the end of rev
sum = sum + d;
n = n / 10; // chop the last digit off
}
do-while: runs at least once, note the ; at the end
int choice;
do {
printf("Enter 0 to quit: ");
scanf("%d", &choice);
} while (choice != 0);
It's the same loop written two ways. Try a start of 1, then 7.
break and continue
for (int i = 1; i <= 10; i++) {
if (i == 4) continue; // skip just this round
if (i == 7) break; // leave the loop completely
printf("%d ", i); // 1 2 3 5 6
}
Nested loops: patterns
for (int i = 1; i <= 4; i++) { // rows
for (int j = 1; j <= i; j++) // columns: row i has i stars
printf("* ");
printf("\n");
}
/* *
* *
* * *
* * * * */
The inner loop runs completely for every single round of the outer loop. Total runs = outer × inner.
for(...); with a semicolon has an empty body; i < 5 and i <= 5 differ by one run; while(1) runs forever unless it hits a break.Exam-style programs with solutions
Try writing each one on paper first, then open the solution and compare.
Your overall score
Answer the section tests to see your score.