Breakout, the game the course builds in HiSoft C, running on the Tatung Einstein: coloured brick rows, the bat and the ball on a black court
← Back to Courses
module
11

Sums And Choices

Introduction

A program that can only do sums in a fixed order is a calculator. The moment it can look at a value and do one thing or another, it is a program. In C that is if, and the values it looks at are made with a small set of operators that this section lays out - including the one pair that everyone, sooner or later, gets the wrong way round.

Operators

The arithmetic ones you have met: + - * / %. They work in the usual order - *, / and % before + and -, and brackets to change it.

The comparisons produce a truth value, and in C a truth value is a number: 1 for true and 0 for false. So score > best is 1 or 0, and you can print it with %d and see which.

a == bequal
a != bnot equal
a < b, a > bless than, greater than
a <= b, a >= bless than or equal, greater than or equal

Two of them combine truth values: && is and, || is or, and ! in front of one is not. score > 30 && score < 40 is 1 only when both halves are.

if And else

if (score > best)
    printf("a new best: %d\n", score);
else
    printf("best is still %d\n", best);

if, a condition in brackets, and a statement; else and another. The condition is any expression, and any value but 0 counts as true. The else half may be left off. When more than one statement depends on the condition, they go inside braces, { ... }, and the whole block is what the if controls - and here is the mistake C makes easy:

if (a > 5)
    printf("more than 5\n");
    printf("this line too?\n");

The indentation says both lines belong to the if. The compiler says only the first does. this line too? is printed whether or not a is more than 5, because without braces an if controls exactly one statement. Put the braces in whenever there are two.

?:

There is a shorter way to choose a value than an if with two assignments:

printf("bigger is %d\n", score > best ? score : best);

condition ? this : that is this if the condition is true, otherwise that. It is an expression, so it can go wherever a value can - inside a printf, on the right of an =.

The Code

#include STDIO.H

main()
{
    int score, best;
    score = 37;
    best = 30;
    if (score > best)
        printf("a new best: %d\n", score);
    else
        printf("best is still %d\n", best);
    if (score % 2 == 0)
        printf("even\n");
    else
        printf("odd\n");
    printf("%d %d %d\n", score > best, score == best, score != best);
    printf("bigger is %d\n", score > best ? score : best);
    if (score > 30 && score < 40)
        printf("in the thirties\n");
    if (score < 0 || score > 100)
        printf("out of range\n");
    else
        printf("in range\n");
}

#include ?STDIO.LIB?

Starting from

Typed as CHOICE.C; compiled and run.

What you should see

a new best: 37
odd
1 0 1
bigger is 37
in the thirties
in range

= And ==

== compares. = assigns. They look alike, and the compiler accepts either inside an if, because an assignment is an expression too and has a value - the value assigned. So:

score = 0;
if (score = 5)
    printf("yes, score is %d\n", score);
else
    printf("no, score is %d\n", score);

prints yes, score is 5. The if did not ask whether score was 5; it made it 5, and 5 is not 0, so the condition was true. No message, no warning, from the compiler or anything else. When an if always takes the same branch, look at its =.

Change One Thing

  • Change score = 37 to score = 30. Which lines change?
  • Change score % 2 == 0 to score % 2. Does odd still come out right, and why?
  • Put braces round the two printf lines in the a > 5 example above and run it with a = 3. Then take the braces off and run it again.

Exercises

11.1 Read no input yet (that is S14): set a variable temp to a number in the program and print freezing, cold, mild or hot for below 0, below 10, below 20, and the rest.

11.2 Set three variables to numbers and print the largest, using only if, no ?:. Then again using only ?:.

11.3 Print whether a year set in the program is a leap year: divisible by 4, except centuries, except every fourth century.

Worked solutions are in Appendix II.

When It Goes Wrong

SymptomCause
An if always goes the same way= where == was meant.
A line runs whether the condition is true or notNo braces: only the first statement belonged to the if.
missing ')' at an ifA bracket missing from the condition.
: does not follow a ? properlyA ?: with its : missing or misplaced.

Summary

Comparisons give 1 or 0; if (condition) statement; else statement; takes any non-zero value as true; braces make several statements one; &&, || and ! combine; ?: chooses a value. == compares and = assigns, and the compiler does not care which you meant.

Next

S12, Round And Round - while, do and for, break and continue, switch, and the one line that lets you stop a loop from the keyboard.

Get the Newsletter

New guides, disk images and community finds, roughly once a quarter. No spam, we promise, this isn't Tatung's marketing department.
Your subscription could not be saved. Please try again.
Your subscription has been successful.

Newsletter

Subscribe to our newsletter and stay updated.