1 of 55

Conditionals

03603111 Programming Fundamentals I

Department of Computer Engineering, Faculty of Engineering at Sriracha

2 of 55

Course outline and schedule

  • L01 Introduction
  • L02 Data and I/O
  • L03 Conditionals (today!)
  • L04 Loops
  • L05 Arrays, strings, and pointers
  • L06 Functions
  • Lab exam #1
  • L07 Nested loops and I/O handling
  • L08 Sorting
  • L09 Searching
  • L10 Structures and dynamic memory allocation
  • L11 Linked data structures
  • L12 Unions and tagged structures
  • Lab exam #2

2

3 of 55

Overview

  • if and if … else
  • Boolean expressions
  • Short-circuit evaluation
  • Type conversion
  • Conditional expressions
  • Defensive programming concepts

3

4 of 55

Previous lesson recaps

4

5 of 55

Let’s make it clear for the last time

  • No plagiarism!
    • You may not submit the work, or a direct derivative thereof, of another person as your own
    • You may not have another person or an AI assistant (such as ChatGPT or Copilot) do the work for you and claim it as your own
    • However, you may discuss assignments and problems with other people, as long as the actual work is done by you

  • Remember: Learning = Coding + Mistakes
    • The best way to understand this deeply is by writing a lot of code and making a lot of mistakes — that’s how your brain truly learn
    • Getting stuck is normal – if you’re not stuck, you’re not learning

5

6 of 55

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

7 of 55

Basic C data types

  • Note that char in C is an integer type, but also used to represent a character (more precisely, the code that represents the character)
  • Integer types are signed by default (except char, which is compiler-dependent – it may be signed or unsigned by default)
  • Basic char and int types can be modified with prefixes to create different integer type variations

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

8 of 55

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

9 of 55

Arithmetic operators, precedence, and grouping

  • +, -, and * do what you expect
  • / behaves differently with integers and floating-point values
    • 10 / 4 ~> 2, while 10.0 / 4.0 ~> 2.5
  • % computes the remainder of the division
    • a % b ~> 1 if a = 10 and b = 3
  • How is this expression evaluated? (if x = 15 and y = 10)
    • 2 + x / 3 * y - 4
  • Use explicit grouping with parentheses to make it more readable
    • 2 + (x / 3 * y) - 4

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

10 of 55

Assignment operators

  • Suppose that integers a = 10, b = 5, and c = 1 in all examples below

  • a = b + c; ~> a = 6
  • a = a + 10; ~> a = 20
  • a += b + c; ~> a = 16
  • a -= b + c; ~> a = 4
  • a *= b + c; ~> a = 60
  • a /= b + c; ~> a = 1
  • a %= b + c; ~> a = 4

10

Operator

Description

=

Assign

+=

Add to

-=

Subtract from

*=

Multiply assign

/=

Divide assign

%=

Modulo assign

Note that = is for assignment, not equality

11 of 55

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

12 of 55

Understanding scanf() format specifiers

These are 3 simplified rules for using scanf() (assuming the user enters input correctly):

  1. Most format specifiers (e.g., %d, %f, %s, etc.) automatically skip leading whitespace

  • The %c (character) format specifier does not – it reads the next character exactly as it is, even if it’s a space, tab, or newline

  • Adding a space before %c in the format string tells scanf() to skip any leading whitespace – this is particularly useful when reading characters after other input

12

13 of 55

Conditionals

13

14 of 55

Let’s start with a problem

  • You’re at a shop in a role-playing game, buying an item for your next adventure with your hard-earned cash from defeating fierce rabbits
  • There’s a SALE happening now, so everything is 20% off
  • For a player with level 20 or above, there’s another 10% discount on top of (in other words, calculated over) the already discounted price

  • You’re asked to write a program to take the item price and player’s level and calculate the final price
  • The shopkeeper will give you an extra special discount for this, so you gladly accept the task!

15 of 55

Understanding the problem

  • Before solving any problem, you’ll need to understand the problem first
  • Understanding the problem:
    • What is the expected output?
      • Final price of the item
    • What are the inputs or known data?
      • Item’s price
      • Player’s level
    • What are the constraints?
      • Additional 10% discount is applied on top of the 20%-discounted price when the player’s level >= 20
  • Make sure you really understand the problem before you proceed!

15

16 of 55

Devising a plan to attack the problem

  • How to get from the input data to the output
    • In this case, from item’s price and player’s level to the final price
    • Ask yourself: Are the input data sufficient to compute the final price?
    • If sufficient, what are the steps to get from the input data to the output?
    • If not, what else are needed?

  • Draft solution steps – also known as the algorithm
    1. Get item’s price and player’s level
    2. Calculate the 20% discounted price
    3. If the player’s level >= 20, apply the additional 10% discount
    4. Display the final price

16

17 of 55

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

  1. Get item’s price and player’s level
  1. Calculate the 20% discounted price
  1. If the player’s level >= 20, apply the additional 10% discount
  1. Display the final price

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

18 of 55

if statement – do it or skip it

  • What you’ve seen in the previous example is the if statement

Syntax: if (condition) statement

  • The condition is a Boolean expression

18

Statement(s)

Condition

True

False

19 of 55

Boolean type and values

  • A Boolean type has two possible values: true and false

  • C considers any scalar type with a value equivalent to 0 to be false
  • Anything else is considered true

  • So, we’ll use integers to represent Boolean values

19

20 of 55

Native Boolean type in C

  • ANSI C doesn’t have a built-in Boolean type
  • Therefore, int is usually used in its place
  • Newer C standards support a native Boolean type
    • C99 has _Bool type but no native true and false – although we can #include <stdbool.h> header file which defines bool as _Bool, true as 1, and false as 0
    • C23 has native true and false values, and native bool type (which is an alias for _Bool) – no longer need to #include <stdbool.h>
  • Not all compilers support them yet, so we don’t use them in our course

20

INTERESTING BITS

21 of 55

Comparison operators

  • Comparison operators yield 1 for true and 0 for false
  • If at the start, a = 10, b = 5, c = 1

  • Note the low precedence of these operators, compared to arithmetic 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

22 of 55

Logical operators

  • We use them to combine “logical clauses”
  • && has higher precedence than ||, and ! has the highest precedence

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

23 of 55

Be careful with equality comparison

  1. Never use = (assignment) where == (equality) should be used

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

  • if (n = 0) ... looks wrong, but can still compile because n = 0 is an assignment expression which can be used as a condition
  • Assignment expressions always yield the assigned value

23

24 of 55

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

  • Floating-point numbers are inexact
  • Using double instead of float won’t fix it

  • Do this instead:��// Use "floating-point absolute"if (fabs(b - 0.1f) < 0.0001f)� printf("That's alright.\n");�else� printf("Something's wrong.\n");

  • Basically, check if the value is within tolerance (e.g., 0.0001f) rather than being exactly equal
  • Also, #include <math.h> to use fabs()

24

25 of 55

Let’s get back to conditionals

That was quite a detour there…

26 of 55

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

  • Invalid choices cannot get through
  • This is an example of defensive programming, which is a practice we should always strive for: building robust and secure programs

27 of 55

Blocks are treated as single statements

  • You’ve seen an example of blocks (or compound statements, as enclosed in { … }) in the previous example

if (choice < 0 || choice > 9) {

printf("Invalid choice (%d)\n", choice);

return -1;

}

  • Use blocks when more than one statement are being executed together
  • Without using blocks, the return statement will always be executed

if (choice < 0 || choice > 9)

printf("Invalid choice (%d)\n", choice);

return -1; // this statement is always executed

27

28 of 55

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

29 of 55

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

30 of 55

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

31 of 55

Is there anything wrong with this code?

if (is_qualified)

if (num_items < storage_size)

num_items += 1;

else

printf("Item is disqualified.\n");

  • This is called dangling else – the else that hangs with the wrong if
  • To prevent it, enclose the inner if inside a block

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

32 of 55

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

33 of 55

Conditional expressions

  • Let’s say we want to compute an absolute of a floating-point number (without using fabs())
  • We can do it this way:

if (x < 0.0)

y = -x;

else

y = x;

  • But it’s more concise this way:

y = x < 0.0 ? -x : x;

  • This x < 0.0 ? -x : x is called a conditional expression, using the “ternary” (3-operand) conditional operator:

cond ? a : b

  • If cond is true, the expression yields a; otherwise, it yields b

  • When there are two actions to choose from, use if … else
  • When there are two values to choose from, use conditional expressions

33

34 of 55

Problem solving revisited

35 of 55

The U-SWACT Problem Solving Framework

  1. ͏UNDERSTAND the problem
    • What is the task really asking?
    • What are the inputs and expected outputs?
    • Are there any constraints (e.g., size, time, types, value ranges)?
  2. Make up SAMPLE INPUTS
    • Try normal and edge cases
    • Include small, negative, or boundary values
  3. ͏WORK OUT solutions manually
    • For each sample input, figure out the correct output by hand
    • Explain your reasoning in plain language
    • Look for patterns or repeated steps
    • If stuck, simplify the problem or solve a related problem first
  1. Write the ALGORITHM
    • Write down the steps from input to output
    • Break it into sub-problems if needed
    • Sketch out any loops or conditions
  2. Translate into CODE
    • Start small – implement one step at a time
    • Test frequently as you build
    • Use print or a debugger to trace values
    • If it doesn’t work, go back to your algorithm or manual steps
  3. ͏TEST the code
    • Try all your sample inputs from Step 2
    • Add more: normal, edge, and invalid inputs
    • Ask: “Does this cover all cases I can think of?”

35

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

36 of 55

Problem 1: Minimum of the three

Problem: Write a program that finds and prints the smallest of three integers

  1. ͏UNDERSTAND the problem
  2. Restate the problem in your own word
    • We need a program that takes three integers and prints the smallest one
  3. What are the inputs?
    • Three integers
  4. What are the outputs?
    • The smallest of the three
  5. Are there any constraints?
    • Not really – except that we assume all the inputs are valid integers
    • Note that basic C operators only allow comparison between two numbers at a time

  • Now that we’ve got the U out of the way, let’s SWACT the rest!

36

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

37 of 55

Problem 1: Minimum of the three

  1. Make up SAMPLE INPUTS
  2. Make up some inputs for normal and edge cases
    • 5 2 9 (min in the middle, max last)
    • -3 0 1 (min first, max last)
    • 3 2 1 (min last, max first)
    • -1 1 -2 (min last, max in the middle)
    • 7 7 7 (all equal)
    • 4 4 2 (two equal, one smaller)
    • … and so on

37

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

38 of 55

Problem 1: Minimum of the three

  1. ͏WORK OUT solutions manually
  2. Let’s try some:
    • 5, 2, 9 ~> 2
    • -3, 0, 1 ~> -3
  3. HOLD ON! Don’t just scan through the numbers and answer – think like a computer
  4. Imagine you can’t see all the numbers at once – you can only see two at a time and don’t know what the next number is
  5. Now, go back and work through all the samples
  6. If stuck, find a related problem: imagine finding the lightest of the three marbles using a balance scale

38

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

39 of 55

Problem 1: Minimum of the three

  • We’re still at Step 3: WORK OUT solutions manually
  • After going through the samples, can you explain how you find the answer in plain language?
  • Do you find patterns in your method? Does your method look somewhat like this? (It’s OK if not – there are more than one way)
    1. Compare the first two numbers
    2. Take the smaller one
    3. Compare the smaller one to the third number
    4. Take the smaller of the two – that one is the smallest of the three

39

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

40 of 55

Problem 1: Minimum of the three

  1. Write the ALGORITHM
  2. At this step, we’ll turn the rough idea into an algorithm

Idea sketch from Step 3:

  1. Compare the first two numbers
  2. Take the smaller one
  3. Compare the smaller one to the third number
  4. Take the smaller of the two – that one is the smallest of the three

Algorithm:

  • Inputs need to come from somewhere – so we take it from the user
  • Read three integers: a, b, c
  • Next, we compare the first two, but we’ll need something to hold the smaller number – let’s call it min
  • If a < b, set min = a, otherwise set min = b
  • If c < min, set min = c
  • Here, if min < c, we don’t need to change it
  • Now, we’ll need to output the result
  • Print min

40

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

41 of 55

Problem 1: Minimum of the three

  1. Translate into CODE
  2. Here is the algorithm from Step 4
    1. Read three integers: a, b, c
    2. If a < b, set min = a, otherwise set min = b
    3. If c < min, set min = c
    4. Print min
  3. We’ll need to translate it into code
  4. Start with an empty main() and translate the algorithm step-by-step
  5. Test along the way

41

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

42 of 55

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

  1. Read three integers: a, b, c
  2. If a < b, set min = a, otherwise set min = b
  3. If c < min, set min = c
  4. Print min

43 of 55

Problem 1: Minimum of the three

  1. ͏TEST the code
  2. Test the code with all the samples from Step 2
  3. Find more test examples to cover all cases you can think of
    • Test with all permutations of number ordering
    • Test with two duplicate numbers at various positions

43

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

44 of 55

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

  • Write algorithm as comments first
  • Translate comments to code line-by-line
  • This can help make code translation easier at the beginning of your skill development

45 of 55

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

46 of 55

Problem 2: Middle of the three

  • Problem: Write a program that finds and prints the middle of three integers

  • Let’s U-SWACT it together!

  • Steps 1 & 2 are similar to the previous problem
  • Hints:
    • You may use a decision tree or flowchart in Step 3
    • The decision tree can be translated directly to algorithm in Step 4
  • Practice turning ideas into algorithm, and then into code – it’s a skill

46

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

47 of 55

Blank sheet – work out your solutions here

47

48 of 55

Blank sheet – work out your solutions here

48

49 of 55

Problem 3: Sorting 3 variables

  • Problem: Write a program that takes three integers, rearranges them from smallest to largest, and prints them in order

  • Hints:
    • You’ll probably need to switch values between two variable – this is called swapping, which is a frequently used coding pattern
    • Note that, in addition to only comparing two numbers at a time, you can only change one variable at a time

49

50 of 55

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

51 of 55

Blank sheet – work out your solutions here

51

52 of 55

Blank sheet – work out your solutions here

52

53 of 55

The U-SWACT Framework Addendum

  • Optional step: R&RREFLECT and REFINE
    • Could the code be clearer or shorter?
    • Would someone else understand it?
    • Does it handle invalid input?

  • This optional step makes you think harder and grow faster
  • If you want to be the best programmer you can be, try it

53

UNDERSTAND

SAMPLE INPUTS

WORK OUT

ALGORITHM

CODE

TEST

54 of 55

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

55 of 55

That’s all for today!

55