Lecture 3 - Selection Statements
Lecture 3 - Selection Statements
Code: XX-XX-XX
15 February, 2024
This session
• Comparing variables
o Relational operators
o Equality operators
o Logical operators
• Selection statements
o Conditional operator
• Flow control
Why do we need Selection Statements?
• You've already covered the basics of writing programs in C
o Making variables
o Assignments
o Data types
o Operators
• Sometimes we want to make choices within the program, or check inputs from an external
source (function, file, library)
o Multiple 'paths' for the program to take
int a = 1; a OR b is true;
! int b = 0;
this is then inverted.
The result is therefore 0 (false)
0
||
Caveats
• Be careful with comparing floating point
numbers float a;
/**
o Imprecision can cause unexpected several operations on a later...
inequalities **/
int b = 1;
1.000000000000000099 printf(a);
1 printf(b);
result = a == b;
false printf(result);'
Casting
• One way to overcome this is by casting one
type to another float a;
/**
o A fair comparison between variables several operations on a later...
o Inputs can be validated **/
int b = 1;
1.0000000000000000 printf(a);
1 printf(b);
result = casted_a == b;
true printf(result);
Casting
• Casting is also done implicitly via
'promotion' float a = 3.4;
int b = 1;
• The compiler takes care of this
• Precision maintained if promoted, precision float result;
lost if demoted
o Will likely need an explicit cast result = a + b;
float a = 3.4;
int b = 1;
int result;
result = a + b;
if statements // Create new variables to store
input
int a = 0;
• Used to choose whether to run a block of
int b = 0;
code or not float result = 0;
• A very common use of these operators
• The if keyword is followed by an expression // Store user input
in brackets scanf('%d', &a);
scanf('%d', &b);
o The expression should evaluate to true or
false (1 or 0) if (b != 0) {
• Curly braces are not required, but
recommended for legible code result = a / b;
}
if statements // Create new variables to store
input
int a = 0;
• We can add 'clauses' to this statement to
int b = 0;
account for other outcomes float result = 0;
• If we want to do something else when the
condition is not met, we have two options: // Store user input
o else scanf('%d', &a);
scanf('%d', &b);
o else if
• Here they are used interchangeably: if (b != 0) {
result = a / b;
} else {
} else if (b == 0) {
printf("Denominator cannot be
0") printf("Denominator cannot be
0")
}
}
if statements if (b != 0) {
printf("Denominator cannot be
• These clauses can be chained together as
0")
much as required
• They can also be nested, but be aware of if (a > 0) {
readability; 'dangling else'
result = a / b;
if (a > 0) {
} else {
result = a / b;
result = -a / b;
} else if (a < 0) {
}
result = -a / b;
Valid code, but is difficult to
} else {
read and debug
printf("Denominator cannot be
0")
if statements if (b != 0) {
printf("Denominator cannot be
• These clauses can be chained together as
0")
much as required
• They can also be nested, but be aware of if (a > 0) {
readability; 'dangling else'
result = a / b;
if (a > 0) {
} else {
result = a / b;
result = -a / b;
} else if (a < 0) {
}
result = -a / b;
Valid code, and easy to
} else {
interpret
printf("Denominator cannot be
0")
Conditional Operator if (test == 1) if (test == 0)
}
switch statements // Create the controlling variable
char meal[10];
• Like an if statement, but with several
// User chooses the value
specific cases scanf('%9s', &meal);
• Checks the value of a variable, rather than
the truth of an expression switch (meal) {
• Useful when we have a large number of case 'salad':
serveSalad(); // Defined
simple choices, with no nesting required
prior
• Examples: case 'chicken':
o User interface serveChicken();
o Restaurant menu case 'steak':
serveSteak();
case 'fish':
serveFish();
}
switch statements // Create the controlling variable
char meal[10];
• If the user's choice isn't accounted for, we
// User chooses the value
can catch this using a default scanf('%9s', &meal);
• Very similar to an else
switch (meal) {
case 'salad':
serveSalad(); // Defined
prior
case 'chicken':
serveChicken();
case 'steak':
serveSteak();
case 'fish':
serveFish();
default:
printf("Valid items
only");
scanf('%9s', &meal);
}
switch cascading // Create the controlling variable
int uiCommand;
• A switch statement will cascade to all
// Prompt; user chooses the option
subsequent cases unless told otherwise printf("Select option from menu")
o This is useful for catching multiple scanf('%d', &uiCommand);
potential cases at once, but can be
unintuitive switch (uiCommand) {
• The break statement interrupts this, and case 0:
newGame(); // Defined
exits the switch statement immediately prior
case 1:
Select option from menu loadGame();
1
cases 1 and 2 will case 2:
options();
be triggered }
break statements // Create the controlling variable
int uiCommand;
• Adding break statements makes for more
// Prompt; user chooses the option
intuitive behaviour printf("Select option from menu")
scanf('%d', &uiCommand);
switch (uiCommand) {
case 0:
newGame(); // Defined
prior
break;
case 1:
Select option from menu loadGame();
0 break;
be triggered }
break;
switch statements // Create the controlling variable
int number;
• There are valid use cases for allowing fall-
// User enters number 0-9
through, but they are rare scanf('%d', &number);
• This behaviour has been changed in a lot of
C-inspired languages switch (number) {
case 0:
case 2:
case 4:
case 6:
case 8:
printf("Number is even")
break;
default:
printf("Number is odd")
break;
}
Caveats int a = 5;
int readInput(void);
• Controlling variables must be integers or
switch (command) {
strings case 0:
o String characters can be interpreted as // case body
integers
• Case statements can additionally only work case 1 + 1:
// case body
with 'constant expressions'. This means:
o Only fixed integers, operations on fixed case 5 / 4:
numbers, or things that represent them // case body
(characters)
o No variables case a:
// case body
o No function calls
• Case statements can have bodies using all of case readInput():
these things, however // case body
}
Caveats int a = 5;
int readInput(void);
• case 0
switch (command) {
o 0 is a fixed integer, so is fine case 0:
// case body
• case 1 + 1
o Evaluates to a fixed integer, so is fine case 1 + 1:
// case body
• case 5 / 4 case 5 / 4:
o Evaluates to a float, so is forbidden // case body
case a:
• case a // case body
o Is a variable, so is forbidden
case readInput():
// case body
• case readInput()
}
o Is a function, so is forbidden
Summary
• New operators
o Relational Attendance Code:
o Equality
o Logical
XX-XX-XX
o Conditional
• Select statements
o if
o switch