C midterm crash course: basics to loops

Read each station, then take its test straight away. Answers are explained as you go. Finish with the solved programs at the end.

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
}
Common exam marks are lost on a missing ;, a missing #include <stdio.h>, or unmatched { }. C is case-sensitive: Printf is wrong.

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

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

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.

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");

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

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
}

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);

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.

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.