← Back to Index
Research & Engineering Archive

LPC 3. Decision Making Statements

By Jingnan Huang · January 13, 2025 · 1833 Words

Last Edit: 1/13/25

 In this chapter, we will discuss how to make decisions in C. We will discuss the ifelse and else if statements

3.1 If-Statement
#

if (condition) {
  // code to execute if condition is true
} else {
  // code to execute if condition is false
}

3.1.1 What can this condition be
#

Relational Expression
#

#include <stdio.h>
int main(void) {
  int age = 0;
  printf("Enter your age: ");
  scanf("%d", &age);
  
  if (age < 14) {  // Condition 
checking if age is less than 14
    printf("You are not yet 
eligible to work in Ontario.");
  } else {
    printf("You are eligible to 
work in Ontario.");
  }
  return 0;
}

3.1.2. What can we do with relational operators?
#

  1. 比较值的大小:(7.2>5.1)
  2. 比较char的大小:'a'>'b',这里比较的是他们的ASCII
  3. 比较charint:比如(0 == '0'),char的0有ASCII = 48,所以0 != ‘0’
int x = 0;
if (x = 1) {
	printf("True");
}

3.2 Multiple Conditions
#

3.2.1 Logical/Boolean Operators
#

A B A && B A || B
false false false false
false true false true
true false false true
true true true true
#include <stdio.h>
int main(void) {
  char letter = ' ';
  printf("Enter a letter: ");
  scanf("%c", &letter);
  
  if (letter == 'A' || letter == 'a') {
    printf("You entered an upper case or lower 
case A.");
  } else {
    printf("You did not enter an upper case or 
lower case A.");
  }
  return 0;
}

3.2.1.1 Lazy Evaluation
#

if (条件1) {
    // 条件1满足时执行的代码
    if (条件2) {
        // 条件1和条件2同时满足时执行的代码
    }
}
if (y != 0 && x % y < 10) {
  // do something
}

3.2.1.2 De Morgan’s Law
#

Img

3.3 Nested-if Statement
#

3.3.2 Dangling Else Problem
#

if (condition)
    statement;
else
    statement;
if (condition1)
    if (condition2)
        statement;
else
    statement;