Conditionals
03603111 Programming Fundamentals I
Department of Computer Engineering, Faculty of Engineering at Sriracha
Course outline and schedule
2
Overview
3
Previous lesson recaps
4
Let’s make it clear for the last time
5
What we’ve covered
#include <stdio.h>
int main()
{
// Variable declarations
int height;
float weight;
float bmi;
int cm2_to_m2 = 10000;
// Read body measurement
printf("Enter height (cm): ");
scanf("%d", &height);
printf("Enter weight (kg): ");
scanf("%f", &weight);
// Compute body mass index (BMI)
bmi = weight / (height * height) * cm2_to_m2;
printf("BMI = %f\n", bmi);
return 0;
}
Types of the variables
A literal or “written value” – used here to initialize the cm2_to_m2 variable
An expression – something that can be evaluated to a value
Variables – used for storing values
Another integer literal – a literal is by itself also an expression, as it can be evaluated to a value
Statements specify actions to be carried out – a program is a sequence of statements
Basic C data types
7
Type | Description |
char | 1-byte character or integer |
int | Basic integer type |
float | 32-bit (4-byte) “single-precision” floating-point number |
double | 64-bit (8-byte) “double-precision” floating-point number |
Integer types with type modifiers
8
Modifier(s) | Type | Minimum Size (bytes) | Range |
signed | char | 1 | -128 to 127 |
unsigned | 1 | 0 to 255 | |
short | int | 2 | -32,768 to 32,767 |
unsigned short | 2 | 0 to 65535 | |
signed | 2 (normally 4) | Refer to either above or below | |
unsigned | 2 (normally 4) | ||
long | 4 | -2,147,483,648 to 2,147,483,647 | |
unsigned long | 4 | 0 to 4,294,967,295 | |
long long | 8 | -263 to 263-1 | |
unsigned long long | 8 | 0 to 264-1 |
IMPORTANT: Assignments or operations that produce values beyond the range of the type will cause numerical overflow or wrapping
Arithmetic operators, precedence, and grouping
9
Operator | Description |
+ | Add |
- | Subtract |
* | Multiply |
/ | Divide |
% | Modulo |
Operator | Associativity | Precedence |
( ) | left to right | highest |
+ - (unary) | right to left | … |
* / % | left to right | … |
+ - (binary) | left to right | lowest |
Assignment operators
10
Operator | Description |
= | Assign |
+= | Add to |
-= | Subtract from |
*= | Multiply assign |
/= | Divide assign |
%= | Modulo assign |
Note that = is for assignment, not equality
Format strings and format specifiers
printf("%d is equal to 0x%x (%X)\n", 1234, 1234, 1234);
~> 1234 is equal to 0x4d2 (4D2)
printf("%d is also the ASCII code of '%c'\n", 70, 70);
~> 70 is also the ASCII code of 'F'
printf("A large float: %f\n", 1.35425e20);
~> A large float: 135425000000000000000.000000
printf("%f + %.1f = [%8.2f]\n", 12.5f, 21.3f, 12.5f + 21.3f);
~> 12.500000 + 21.3 = [ 33.80]
// '0' flag -> prefixed with 0s, '-' flag -> left-aligned
printf("Mr.%s, %06d is billed at [%-4d]PM.\n", "Kim", 25, 12);
~> Mr.Kim, 000025 is billed at [12 ]PM.
printf("There's a %u%% OFF SALE right now.\n", 50);
~> There's a 50% OFF SALE right now.
11
%d | int (decimal) |
%u | unsigned int (decimal) |
%x, %X | int (hexadecimal) |
%c | char (character) |
%f | float |
%lf | double |
%s | char[] (string) |
%% | Printing % |
| flag | field width | precision | type |
% | -, 0 | 8 | .2 | f |
Understanding scanf() format specifiers
These are 3 simplified rules for using scanf() (assuming the user enters input correctly):
12
Conditionals
13
Let’s start with a problem
Understanding the problem
15
Devising a plan to attack the problem
16
And here’s a solution in C
#include <stdio.h>
int main()
{
float item_price;
int player_level;
float discounted_price;
printf("Enter item's price: ");
scanf("%f", &item_price);
printf("Enter player's level: ");
scanf("%d", &player_level);
discounted_price = 0.8 * item_price; // 20% discount
if (player_level >= 20)
// 10% discount on top
discounted_price -= 0.1 * discounted_price;
printf("Final price = %.2f\n", discounted_price);
return 0;
}
17
Input data
Output data
Enter item's price: 100
Enter player's level: 19
Final price = 80.00
// Re-run
Enter item's price: 100
Enter player's level: 20
Final price = 72.00
Results
if statement – do it or skip it
Syntax: if (condition) statement
18
Statement(s)
Condition
True
False
Boolean type and values
19
Native Boolean type in C
20
INTERESTING BITS
Comparison operators
21
b != c + 4
a == b + 5
a + b <= c
(a < b) > c
~> false (0)
~> true (1)
~> false (0)
Don’t do this!
It’s false, by the way – but don’t do it
Operator | Description |
== | Equal to |
!= | Not equal to |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
Logical operators
22
Operator | Description |
! | Negation (NOT) |
&& | AND |
|| | OR |
int x = 10; int y = 20;
int b = 1; int c = b && x < y;
�printf("%d\n", !c);
~> 0 // false
printf("%d\n", !(x >= y));
~> 1 // true
printf("%d\n", x < 10 || x > 60 && y < 20);
~> 0 // false
printf("%d\n", !b || c);
~> 1 // true
Be careful with equality comparison
� int n = 0;
if (n == 0) printf("1");
if (n = 0) printf("2"); // Don't do this
if (n == 1) printf("3");
if (n = 1) printf("4"); // Don't do this
~> 14�
23
2. Never compare floating-points for equality
float a = 1.0f;
float b = a - 0.9f;
if (b == 0.1f)
printf("That's alright.\n");
else
printf("Something's wrong.\n");
~> Something's wrong.
printf("1.0 - 0.9 = %f\n", b);
printf("1.0 - 0.9 = %.10f\n", b);
~> 1.0 - 0.9 = 0.100000
~> 1.0 - 0.9 = 0.1000000238
24
Let’s get back to conditionals
That was quite a detour there…
Using if to guard against invalid inputs
printf("Enter your choice (0-9): ");
scanf("%d", &choice);
if (choice < 0 || choice > 9) {
printf("Invalid choice (%d)\n", choice);
return -1;
}
printf("You choose option %d\n", choice);
Blocks are treated as single statements
if (choice < 0 || choice > 9) {
printf("Invalid choice (%d)\n", choice);
return -1;
}
if (choice < 0 || choice > 9)
printf("Invalid choice (%d)\n", choice);
return -1; // this statement is always executed
27
if … else statement – do this or do that
Syntax:
if (condition) statement1 else statement2
int n = 123;
if (n % 2 == 0)
printf("%d is even.\n", n);
else
printf("%d is odd.\n", n);
~> 123 is odd.
28
Statement(s)1
Condition
Statement(s)2
True
False
Something is wrong with this code
int x = 10;
int y = 20;
int b = 1;
int c = b && x < y;
if (x < y - 10)
printf("First case is true\n");
if (c)
printf("Second case is true\n");
else
printf("Second case is false\n");
printf("Which I don't like\n");
29
This line will be executed regardless of the condition
if (c) {
printf("Second case is true\n");
} else {
printf("Second case is false\n");
printf("Which I don’t like\n");
}
To fix it, enclose them in blocks
Conditionals can be nested
int storage_size = 10;
int num_items = 10;
// … some other code …
// Check and store qualified items
if (is_qualified) {
// Avoid exceeding storage limit
if (num_items >= storage_size) {
printf("Out of storage.\n");
} else {
num_items += 1;
}
}
printf("Storage Status: %d/%d\n", num_items, storage_size);
30
// When is_qualified is false
Storage Status: 10/10
// When is_qualified is true
Out of storage.
Storage Status: 10/10
Results
Many people like to use blocks even when there is only one statement – it’s a stylistic choice
Is there anything wrong with this code?
if (is_qualified)
if (num_items < storage_size)
num_items += 1;
else
printf("Item is disqualified.\n");
if (is_qualified) {
if (num_items < storage_size)
num_items += 1;
} else {
printf("Item is disqualified.\n");
}
31
// When is_qualified is false
// Nothing is printed
// When is_qualified is true
// and num_items == storage_size
Item is disqualified.
Results
// When is_qualified is false
Item is disqualified.
// When is_qualified is true
// and num_items == storage_size
// Nothing is printed
Results
Multiway selection – the if … else if … else pattern
printf("Enter the day number (1-7): ");
scanf("%d", &day);
if (day == 1) {
printf("Monday\n");
} else if (day == 2) {
printf("Tuesday\n");
} else if (day == 3) {
printf("Wednesday\n");
} else if (day == 4) {
printf("Thursday\n");
} else if (day == 5) {
printf("Friday\n");
} else if (day == 6) {
printf("Saturday\n");
} else if (day == 7) {
printf("Sunday\n");
} else {
printf("Invalid day number.\n");
}
32
day == 1
False
True
day == 2
False
day == 3
Print “Monday”
Print “Tuesday”
Print “Wednesday”
True
True
…
…
Conditional expressions
if (x < 0.0)
y = -x;
else
y = x;
y = x < 0.0 ? -x : x;
cond ? a : b
33
Problem solving revisited
The U-SWACT Problem Solving Framework
35
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
Problem: Write a program that finds and prints the smallest of three integers
36
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
37
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
38
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
39
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
Idea sketch from Step 3:
Algorithm:
40
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
41
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
#include <stdio.h>
int main() {
int a, b, c;
int min;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
if (a < b)
min = a;
else
min = b;
if (c < min)
min = c;
printf("The smallest number is %d\n", min);
return 0;
}
42
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Problem 1: Minimum of the three
43
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
You can write algorithm as comments for scaffolding
#include <stdio.h>
int main() {
int a, b, c; // We need to declare a, b, c
int min; // we also need min
// 1. Read three integers: a, b, c
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
// 2. If a < b, set min = a, otherwise set min = b
if (a < b)
min = a;
else
min = b;
// 3. If c < min, set min = c
if (c < min)
min = c;
// 4. Print min
printf("The smallest number is %d\n", min);
return 0;
}
44
Code can be more concise with conditional expressions
#include <stdio.h>
int main() {
int a, b, c, min;
// 1. Read three integers: a, b, c
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
// 2. If a < b, set min = a, otherwise set min = b
min = a < b ? a : b;
// 3. If c < min, set min = c
min = c < min ? c : min;
// 4. Print min
printf("The smallest number is %d\n", min);
return 0;
}
45
Problem 2: Middle of the three
46
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
Blank sheet – work out your solutions here
47
Blank sheet – work out your solutions here
48
Problem 3: Sorting 3 variables
49
SWAP
PROBLEM: Given two variables, we want to swap their values
Let’s say, we have:
int a = 1, b = 2;
FIRST TRY:
a = b;
b = a;
// We've got a = 2, b = 2
SOLUTION: We need an intermediate variable to hold one of the value temporarily
int temp;
temp = a; // temp = 1
a = b; // a = 2
b = temp; // b = 1
50
CODING PATTERN
PATTERN NAME
Blank sheet – work out your solutions here
51
Blank sheet – work out your solutions here
52
The U-SWACT Framework Addendum
53
UNDERSTAND
SAMPLE INPUTS
WORK OUT
ALGORITHM
CODE
TEST
When you’re lost, a reference is here to help…
C reference: https://en.cppreference.com/w/c
Still, I recommend getting a book – your life will be easier that way
54
That’s all for today!
55