thecodingidiot.com

Writing CControl Flow

Control Flow

A program without control flow runs every statement once, in order, and exits. Control flow lets a program make decisions and repeat work.

if and else

int x = 10;
 
if (x > 0)
    printf("positive\n");
else if (x < 0)
    printf("negative\n");
else
    printf("zero\n");

The condition is any expression that evaluates to an integer. Zero is false; anything else is true. C uses integers for truth values — C99 added <stdbool.h> with a bool type if you want explicit boolean variables.

When the body of an if or else is more than one statement, wrap it in braces:

if (x > 0) {
    printf("positive\n");
    printf("x is %d\n", x);
}

Single-statement bodies do not require braces. The style used throughout this site omits them for single statements; multi-statement bodies always use braces.

Comparison and logical operators

OperatorCharactersMeaning
====equal
!=!=not equal
<<less than
>>greater than
<=<=less or equal
>=>=greater or equal
&&&&logical and
||||logical or
!!logical not

This site renders code in a font with programming ligatures[1]!= appears as a single merged symbol, <= as a single glyph. This is the first chapter where that distinction matters for what you type. Most terminals do not use ligature fonts by default, so your environment likely already shows the characters as written. The Characters column confirms it either way. Ligatures are cosmetic; the compiler always sees the individual characters.

= assigns. == compares. Confusing them is the most common C bug for new programmers. The compiler will not always catch it.

while and for

while repeats as long as a condition is true:

int i;
 
i = 0;
while (i < 5) {
    printf("%d\n", i);
    i++;
}

i++ is shorthand for i = i + 1. The -- operator does the reverse: i-- subtracts one. Both come in two forms:

FormNameBehaviour
i++post-incrementuses i, then adds one
++ipre-incrementadds one, then uses the result
i--post-decrementuses i, then subtracts one
--ipre-decrementsubtracts one, then uses the result

In a standalone statement — as used here — the two forms are identical; i++ and ++i both leave i one higher. The difference only matters when the expression is used inside a larger one, such as a[i++], which is covered when arrays are introduced.

for packages the initialiser, condition, and increment in one line:

int i;
for (i = 0; i < 5; i++)
    printf("%d\n", i);

Both print 0 through 4. Use for when you know the count in advance; use while when you do not.

break exits the loop immediately. continue skips to the next iteration.


Reading input with scanf

scanf reads formatted input from standard input. The format specifiers are the same as printf:

int n;
 
printf("Enter a number: ");
scanf("%d", &n);
printf("You entered %d\n", n);

The only thing that looks strange is &n instead of n. For now, treat it as a rule: scanf arguments always take a & in front of them. Leaving it out causes a crash or garbage output. The reason will make complete sense when you reach memory and pointers — for now, just remember the &.


The complete calculator

Putting types, arithmetic, control flow, and input together:

#include <stdio.h>
 
int main(void)
{
    int    a;
    int    b;
    char   op;
    int    result;
 
    printf("Enter: number operator number (e.g. 3 + 4)\n");
    scanf("%d %c %d", &a, &op, &b);
    if (op == '+')
        result = a + b;
    else if (op == '-')
        result = a - b;
    else if (op == '*')
        result = a * b;
    else if (op == '/') {
        if (b == 0) {
            printf("Error: division by zero\n");
            return (1);
        }
        result = a / b;
    }
    else {
        printf("Error: unknown operator '%c'\n", op);
        return (1);
    }
    printf("%d %c %d = %d\n", a, op, b, result);
    return (0);
}

Test it:

gcc -Wall -Wextra calculator.c -o calculator
./calculator
Enter: number operator number (e.g. 3 + 4)
10 / 3
10 / 3 = 3

This is a working calculator. It is also a wall of if/else that will become unmaintainable as soon as you need to add operations. The next page introduces functions — the tool for organising programs that grow.

Footnotes

  1. Ligature (writing) - Wikipedia