90 min

if, else and else-if

A single if that runs a block or skips it, if...else that picks one of two branches, and an else-if chain that stops at the first true condition. Tracing programs and testing at the boundary.

A single if

In the last lesson a condition gave 1 (true) or 0 (false). An if statement uses that answer to decide whether a block of code runs.

if (condition)
{
    statements;
}

The program works out the condition first. If it is true, the statements in the block (בלוק), between { and }, run. If it is false, the whole block is skipped. Either way, the program then continues with the line after the block.

The diamond is the question. Step through the two runs: with -4 the program goes through the box, with 7 it goes around it. Both paths meet again at Done.Open full screen

Four rules for writing an if:

  1. The condition goes in parentheses, and there is no semicolon after it.
  2. Use braces { } for the block, even when it has one statement.
  3. Indent the statements inside the block.
  4. The condition is checked before the block.

Worked program: a warning for a negative value

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int number;
    scanf("%d", &number);
    if (number < 0)
    {
        printf("Negative\n");
    }
    printf("Done\n");
    return 0;
}

With the input -4, the console shows:

-4
Negative
Done

-4 < 0 is 1, so the block runs. With the input 4, the condition 4 < 0 is 0, the block is skipped, and only Done is printed. The line #define _CRT_SECURE_NO_WARNINGS stops Visual Studio's warning C4996 about scanf.

The program line by line with input -4: the variable in memory, the condition's value next to the if, and the console.Open full screen

Trace tables

A trace table (טבלת מעקב) checks a program on paper: one row per test input, and one column per thing that happens. Always fill in the condition before the output.

Inputnumber < 0The blockOutput
-41runsNegative, Done
00skippedDone
70skippedDone

Zero is not negative, so it behaves like 7.

Exercise 2: a multiple of 5

Checking an input once

A single if can catch an impossible input:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int age;
    scanf("%d", &age);
    if (age < 0)
    {
        printf("Invalid age\n");
    }
    return 0;
}
-2
Invalid age

This checks the value once. Asking again and again until the value is valid needs a loop, which comes in unit 6.

if...else: one of two branches

An if can have an else part. Then there are two branches (ענפים), and exactly one of them runs: the if block when the condition is true, the else block when it is false. Never both, never neither.

Step through the two runs, 8 and 17. One box runs each time, never both.Open full screen
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int number;
    scanf("%d", &number);
    if (number % 2 == 0)
    {
        printf("Even\n");
    }
    else
    {
        printf("Odd\n");
    }
    return 0;
}
17
Odd

With 17, the condition reduces step by step: 17 % 2 == 0 becomes 1 == 0, which is 0. So the program skips the if block and runs the else block. Note that else has no condition of its own: it runs exactly when the if condition is 0.

numbernumber % 2number % 2 == 0BranchOutput
801ifEven
1710elseOdd
001ifEven

Zero is even: 0 % 2 is 0.

Testing at the boundary

Why those three tests? The boundary value (ערך גבול) is the value where the answer changes, here 55. Suppose someone wrote score > 55 instead of score >= 55:

Condition2054555690
score >= 55 (correct)FailFailPassPassPass
score > 55 (bug)FailFailFailPassPass

Tests like 20 and 90 give the right answer with both conditions, so they cannot find the bug. Only the test at the boundary, 55, does. Test every condition below, at and above its boundary.

The correct and the buggy condition side by side. Only one test exposes the wrong operator.Open full screen

A good test has a reason:

ConditionTestsWhat they show
x > 109, 10, 1110 must give 0
x >= 109, 10, 1110 must give 1
x == 0-1, 0, 1only 0 gives 1
x != 0-1, 0, 1only 0 gives 0

else-if chains

When there are more than two outcomes, chain the decisions with else if:

if (condition1)
{
    action1;
}
else if (condition2)
{
    action2;
}
else
{
    default_action;
}

An else-if chain (שרשרת else if) works like this:

  1. The conditions are checked from top to bottom.
  2. The branch of the first true condition runs.
  3. All the branches after it are skipped, even if their conditions would be true.
  4. The final else catches every value that no condition matched.
condition1 is 0, condition2 is 1: only action2 runs, and the else is never reached.Open full screen

Order matters

Because the chain stops at the first true condition, the order of the conditions is part of the logic. Look at a score of 90:

if (score >= 55)
    printf("Pass\n");
else if (score >= 85)
    printf("Excellent\n");

90 >= 55 is already true, so the chain prints Pass and stops. Excellent can never print, for any score. The right order starts from the highest threshold:

if (score >= 85)
    printf("Excellent\n");
else if (score >= 55)
    printf("Pass\n");
else
    printf("Fail\n");

A later condition only sees the values that every earlier condition rejected.

Worked program: the sign of a number

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int number;
    scanf("%d", &number);
    if (number > 0)
        printf("Positive\n");
    else if (number < 0)
        printf("Negative\n");
    else
        printf("Zero\n");
    return 0;
}
0
Zero

With 0, number > 0 is 0 and number < 0 is 0, so the final else runs. It needs no condition: after "not positive" and "not negative", only zero is left.

Worked program: classify a score

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
 
int main(void)
{
    int score;
    scanf("%d", &score);
    if (score >= 85)
        printf("Excellent\n");
    else if (score >= 70)
        printf("Good\n");
    else if (score >= 55)
        printf("Pass\n");
    else
        printf("Fail\n");
    return 0;
}
70
Good

The thresholds go down: 85, 70, 55. That way a higher grade is never caught early by a lower one.

Step through the chain with 70, then click 92, 55 and 54 at the top and watch how many conditions are checked each time.Open full screen

The trace for four test scores. A dash means the condition was never checked. It does not mean false.

Score>= 85>= 70>= 55Output
921--Excellent
7001-Good
55001Pass
54000Fail

Two separate ifs are not a chain

int x = 7;
if (x > 0)
    printf("A");
if (x < 10)
    printf("B");
else
    printf("C");
AB

These are two independent if statements, not one chain, so both conditions are checked. x > 0 is 1, so A prints. x < 10 is 1, so B prints. The else belongs to the nearest if above it, the second one, so C does not print.

Key words

EnglishHebrewMeaning
ifאםruns a block when its condition is true
elseאחרתruns when the condition is false
else-if chainשרשרת else ifconditions checked in order; the first true one wins
blockבלוקthe statements between { and }
branchענףone of the paths a decision can take
boundary valueערך גבולthe value where the answer changes
trace tableטבלת מעקבthe values of a program written down step by step
test inputקלט בדיקהa value chosen to check the program

Practice

All of Tom's questions for this lesson, with answers, are on the practice page (questions 7 to 20, 27 and 28).