if, else ו־else if
if יחיד שמריץ בלוק או מדלג עליו, if...else שבוחר אחד משני ענפים, ושרשרת else if שעוצרת בתנאי הראשון שמתקיים. מעקב אחר תוכניות ובדיקות בגבול.
השיעור הזה כתוב באנגלית בלבד.
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.
Four rules for writing an if:
- The condition goes in parentheses, and there is no semicolon after it.
- Use braces
{ }for the block, even when it has one statement. - Indent the statements inside the block.
- 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.
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.
| Input | number < 0 | The block | Output |
|---|---|---|---|
| -4 | 1 | runs | Negative, Done |
| 0 | 0 | skipped | Done |
| 7 | 0 | skipped | Done |
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 ageThis 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.
#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
OddWith 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.
number | number % 2 | number % 2 == 0 | Branch | Output |
|---|---|---|---|---|
| 8 | 0 | 1 | if | Even |
| 17 | 1 | 0 | else | Odd |
| 0 | 0 | 1 | if | Even |
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:
| Condition | 20 | 54 | 55 | 56 | 90 |
|---|---|---|---|---|---|
score >= 55 (correct) | Fail | Fail | Pass | Pass | Pass |
score > 55 (bug) | Fail | Fail | Fail | Pass | Pass |
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.
A good test has a reason:
| Condition | Tests | What they show |
|---|---|---|
x > 10 | 9, 10, 11 | 10 must give 0 |
x >= 10 | 9, 10, 11 | 10 must give 1 |
x == 0 | -1, 0, 1 | only 0 gives 1 |
x != 0 | -1, 0, 1 | only 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:
- The conditions are checked from top to bottom.
- The branch of the first true condition runs.
- All the branches after it are skipped, even if their conditions would be true.
- The final
elsecatches every value that no condition matched.
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
ZeroWith 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
GoodThe thresholds go down: 85, 70, 55. That way a higher grade is never caught early by a lower one.
The trace for four test scores. A dash means the condition was never checked. It does not mean false.
| Score | >= 85 | >= 70 | >= 55 | Output |
|---|---|---|---|---|
| 92 | 1 | - | - | Excellent |
| 70 | 0 | 1 | - | Good |
| 55 | 0 | 0 | 1 | Pass |
| 54 | 0 | 0 | 0 | Fail |
Two separate ifs are not a chain
int x = 7;
if (x > 0)
printf("A");
if (x < 10)
printf("B");
else
printf("C");ABThese 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
| English | Hebrew | Meaning |
|---|---|---|
if | אם | runs a block when its condition is true |
else | אחרת | runs when the condition is false |
| else-if chain | שרשרת else if | conditions 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).