C midterm crash course: basics to loops

Station 0 is a quick warm-up on how coding works, and it's worth a look even if you've seen some code before. In each station, read the notes, play with the "Try it" boxes (change the numbers and watch the code react), then take that station's test. Finish with the solved programs at the end.

Station 0

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.

Think of it like a recipeThe ingredients are your variables (things you store). The steps are statements. "If the dough is sticky, add flour" is an if-else. "Stir 10 times" is a loop. That's the whole midterm: storing things, making decisions, and repeating.

How C code becomes a running program

  1. You write code in a .c file. It's just text.
  2. A compiler translates it into machine language the computer understands.
  3. If you broke a rule (a missing ;, a misspelled word), the compiler refuses and shows an error. Fix it and try again.
  4. 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

WordPlain meaning
StatementOne instruction, ending with ;
VariableA labelled box that holds one value, like age holding 19
Data typeWhat kind of value the box holds: whole number, decimal or character
OutputWhat the program shows on screen (printf)
InputWhat the user types in (scanf)
ConditionA yes/no question, like marks >= 50
LoopRepeating some code while a condition stays true
CommentNotes after // or inside /* */. The computer ignores them.
Try it: your first program

Change the name and switch \n on and off to see how the output changes. Highlighted lines are the ones printing something.

Why is C so strict about ; and brackets?The compiler is a machine reading your text. A full stop tells a human that a sentence has ended, and ; does the same job for the compiler. Without it, the compiler can't tell where one instruction stops and the next one starts.
Station 1

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
}
Easy marks to protect: watch out for a missing ;, a missing #include <stdio.h>, or unmatched { }. C is case-sensitive: Printf is wrong.
Line by line, in plain words#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.

TypeStoresExampleFormat
intwhole numbersint age = 19;%d
floatdecimalsfloat gpa = 3.5;%f
doublebigger, more precise decimalsdouble pi = 3.14159;%lf
charone character, in single quoteschar g = 'A';%c
In plain wordsint 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.
Why do we need different types?The computer has to know how much space to set aside and how to read what's inside. A whole number, a decimal and a letter are stored differently, so you tell C upfront what each box will hold.

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
Why does scanf need & but printf doesn't?printf only needs to read what's in the box. scanf has to put a value into the box, so it needs to know where the box is. &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

KindOperatorsWatch 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.

Try it: operators

Change a and b. Watch / and % especially.

Try it: x++ vs ++x

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.

Station 2

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");
Try it: move the marks slider

The highlighted lines are the ones that actually run.

    Why does the order of the ladder matter?C checks from the top and stops at the first true condition. If you wrote 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.
    Why == 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
    Traps: 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.
    Station 3

    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 like case x > 5.
    • Case values can't be duplicated.
    • No break means fall-through: execution keeps running into the next cases until it hits a break or the closing }.
    • default is optional and can go anywhere, but it usually goes last.
    In plain wordsThink of a lift. You press a floor number (the value) and the lift goes straight to that floor (the matching case). break is the door opening so you can get out. Without it, you'd keep riding down through every floor below.
    Try it: switch and break

    Pick a day, then turn break off to see fall-through.

    Why does C fall through instead of stopping?A case label is only a starting point, like a bookmark. C jumps to it and keeps reading downward until something tells it to stop, and that's what 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");
    }
    switch vs if-else: switch only handles exact matches. Ranges like marks >= 50 need if-else.
    Station 4

    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.

    In plain words"Start counting at 1. While you're still at 5 or below, print the number, then add 1." The variable i is just the counter.
    Try it: step through a for loop

    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
    }
    Why do we need i++ inside the while?The loop keeps going as long as 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 or while: which one?Use 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.
    Try it: a while loop on digits

    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);
    Try it: while vs do-while

    It's the same loop written two ways. Try a start of 1, then 7.

    Why use do-while for menus?A menu has to appear at least once before the user can choose anything. do-while guarantees that first run.

    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.

    In plain wordsThink of a clock. The minute hand (the inner loop) goes all the way round for every single step of the hour hand (the outer loop). In patterns, the outer loop picks the row and the inner loop prints what goes in that row.
    Try it: pattern maker

    Dry-run method: make a table with a column for each variable and write a new row every round. That's how you answer "what is the output" questions with no guessing. Traps: 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.
    Station 5

    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.