ECE151 - Lecture 4
ECE151 - Lecture 4
Programming
Relational Operators
7 <= 5 is false
if x is 10, then
x == 10 is true,
x != 8 is true, and
x == 8 is false
Relational Expressions
● General Format:
if (expression)
statement;
The if Statement-What Happens
To evaluate:
if (expression)
statement;
● If the expression is true, then statement is executed.
● If the expression is false, then statement is
skipped.
if Statement in Program 4-2
Continued…
if Statement in Program 4-2
Flowchart for Program 4-2 Lines 21 and 22
if Statement Notes
grade = 'A';
}
● { } creates a block of code
The if/else statement
● General Format:
if (expression)
statement1; // or block
else
statement2; // or block
if/else-What Happens
To evaluate:
if (expression)
statement1;
else
statement2;
Continued…
Testing the Divisor in Program 4-9
Nested if Statements
if (expression)
statement1; // or block
else if (expression)
statement2; // or block
.
. // other else ifs .
else if (expression)
statementn; // or block
The if/else if Statement in Program 4-13
Using a Trailing else to Catch Errors in
Program 4-14
This trailing
else catches
invalid test
scores
Flags
(x <= z) || (y == z) false
(x <= z) || (y != z) true
1) expression is evaluated
2) The value of expression is compared against exp1
through expn.
3) If expression matches value expi, the program
branches to the statement following expi and continues
to the end of the switch
4) If no matching value is found, the program branches to
the statement after default:
break Statement
Continued…
break and default statements in Program 4-
25
Using switch in Menu Systems