Decisions and loops

Programs get interesting when they can choose and repeat.

Choosing uses if, else if and else. The condition goes in parentheses:

if (score >= 90) {
    printf("A\n");
} else if (score >= 50) {
    printf("pass\n");
} else {
    printf("try again\n");
}

Here is a C fact worth knowing: there was no built-in boolean type in early C. A condition is just a number. 0 means false, anything else means true. Comparisons like x > 3 produce the int 1 or 0. (<stdbool.h> gives you bool, true and false as friendlier names.)

That is why this classic bug compiles happily:

if (x = 5)   // assigns 5, which is nonzero, so always true!

You wanted ==. Many compilers will warn you. Listen to them.

Repeating uses loops. A for loop packs start, condition and step into one line:

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

A while loop just keeps going while its condition is true, which suits "I do not know how many times yet" situations. break leaves a loop early, continue skips to the next round.

The % operator gives the remainder of a division: 10 % 3 is 1. If n % 2 == 0, n is even. You will use this constantly.

Try it yourself

Edit it. Break it. Run it again.
#include <stdio.h>

int main(void) {
    int total = 0;
    int n = 1;
    while (total < 20) {
        total = total + n;
        printf("added %d, total is %d\n", n, total);
        n++;
    }
    if (total % 2 == 0) {
        printf("%d is even\n", total);
    } else {
        printf("%d is odd\n", total);
    }
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1FizzBuzz

For each number from 1 to 15, print Fizz if it divides by 3, Buzz if it divides by 5, FizzBuzz if it divides by both, and otherwise the number itself. One per line.

#include <stdio.h>

int main(void) {
    for (int i = 1; i <= 15; i++) {
        printf("%d\n", i);
    }
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Count down from input

The program reads a number n with scanf. Print a countdown from n to 1, one number per line, then print Liftoff!. With the input below, the output is:

  • 5
  • 4
  • 3
  • 2
  • 1
  • Liftoff!

The checker feeds this input to your program.

#include <stdio.h>

int main(void) {
    int n;
    scanf("%d", &n);
    // count down here
    return 0;
}
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.