[go: up one dir, main page]

0% found this document useful (0 votes)
15 views29 pages

Lecture 3 - Selection Statements

The document covers programming concepts related to selection statements in C, including the use of relational, equality, and logical operators. It explains the importance of making choices in programs through if statements and switch statements, along with their syntax and examples. Additionally, it highlights potential pitfalls and caveats when using these constructs.

Uploaded by

coolguysemail222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Lecture 3 - Selection Statements

The document covers programming concepts related to selection statements in C, including the use of relational, equality, and logical operators. It explains the importance of making choices in programs through if statements and switch statements, along with their syntax and examples. Additionally, it highlights potential pitfalls and caveats when using these constructs.

Uploaded by

coolguysemail222
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Presented by UFMFGT-15-1: Programming for Engineers

Tom Knowles Week 14: 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

• This choosing is mediated by selection (conditional) statements


New Operators
Equality Relational Logical

> < || &&


== !=
>= <= !
• Most compare the two variables on either side of the operator
• Output 1 (true) or 0 (false); regular numbers
• Can be combined together
Equality Operators
Initialisation Expression True/False
int a = 5;
int b = 5;
a == b 1
int a = 4;
int b = 5;
a == b 0
int a = 5;
int b = 5;
a != b 0
int a = 4;
int b = 5;
a != b 1
Equality Operators

Operator Example Output Explanation


int a = 1; a contains the same value as b;
== int b = 1; 1 the result is therefore 1 (true)

int a = 3; a does not contain the same


!= int b = 1; 1 value as b;
the result is therefore 1 (true)
Relational Operators
Initialisation Expression True/False
int a = 4; a > b 0
int b = 5;
int a = 4; a < b 1
int b = 5;
int a = 4; b > a 1
int b = 5;
int a = 4; b < a 0
int b = 5;
Relational Operators
Initialisation Expression True/False
int a = 4; a >= b 0
int b = 5;
int a = 4; a <= b 1
int b = 5;
int a = 5; a >= b 1
int b = 5;
int a = 5; a <= b 1
int b = 5;
Relational Operators
Operator Example Output Explanation
int a = 3; a is larger than b;

> int b = 1; 1 the result is therefore 1 (true)

int a = 3; a is not smaller than b; the result

< int b = 1; 0 is therefore 0 (false)

int a = 4; a is not greater than, but is equal


>= int b = 4; 1 to b;
the result is therefore 1 (true)

int a = 6; a is not smaller than or equal


<= int b = 2; 0 to b;
the result is therefore 0 (false)
Logical Operators
Initialisation Expression True/False
int a = 0;
int b = 0;
a || b 0
int a = 0;
int b = 1;
a || b 1
int a = 1;
int b = 0;
a || b 1
int a = 1;
int b = 1;
a || b 1
Logical Operators
Initialisation Expression True/False
int a = 0;
int b = 0;
a && b 0
int a = 0;
int b = 1;
a && b 0
int a = 1;
int b = 0;
a && b 0
int a = 1;
int b = 1;
a && b 1
Logical Operators
Initialisation Expression True/False
int a = 0;
int b = 0;
!(a && b) 1
int a = 0;
int b = 1;
!(a || b) 0
int a = 4;
int b = 5;
!(a > b) 1
int a = 5;
int b = 5;
!(a == b) 0
Logical Operators
Operator Example Output Explanation
int a = 1; Either a OR b is true;
|| int b = 0; 1 the result is therefore 1 (true)

int a = 1; a is true, but b is not; the result is


therefore 0 (false)
&& int b = 0; 0

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);

int casted_a = (int)a

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)

• A piece of 'synactic sugar'; a shortcut


• This can replace a full if statement for
test ? value : value

simple cases int number;


• For more complex use cases, stick with the int isBig;
full if statement
• Both these code snippets are equivalent scanf(%d, &number);

if (number > 100) {


int number;
int isBig; isBig = 1;

scanf(%d, &number); } else {

isBig = number > 100 ? 1 : 0; isBig = 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;

only case 0 will case 2:


options();

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

• Caveats and pitfalls


• Use cases

You might also like