This lesson includes an expert video walkthrough — purchase once for a full year of unlimited replays to master every key point 🎬
Conditional Statements — Simple if-else
I. In-Class Exercises
Programming Exercises
Sample Code
1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 if (a + b > c) {
8 cout << "yes" << endl;
9 } else {
10 cout << "no" << endl;
11 }
12 return 0;
13}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int a, b, c;
6 cin >> a >> b >> c;
7 if (a + b > c && a + c > b && b + c > a) {
8 cout << "Yes" << endl;
9 } else {
10 cout << "No" << endl;
11 }
12
13 return 0;
14}1#include <bits/stdc++.h>
2using namespace std;
3
4int main() {
5 int n;
6 cin >> n;
7 if (0 == n % 2) {
8 cout << "2" << endl;
9 }
10 if (0 == n % 3) {
11 cout << 3 << endl;
12 }
13 if (0 == n % 5) {
14 cout << 5 << endl;
15 }
16 if (0 == n % 7) {
17 cout << 7 << endl;
18 }
19 return 0;
20}II. Knowledge Summary
✨ What is Conditional Judgment
In daily life, we often need to make different choices based on different situations. For example:
- If it rains today, bring an umbrella; otherwise, don't
- If the exam score is 60 or above, it's a pass; otherwise, it's a fail
It's the same in programs. Programs execute line by line from top to bottom by default, but sometimes we want the program to execute different code based on conditions — this is a conditional statement.
✨ Conditional Control Flowchart
A conditional control flowchart includes branching structures with condition checks.
In a conditional control flowchart:
- Condition check: represented by a diamond
- Start/End: represented by an oval, rounded rectangle, or circle
- Input/Output: represented by a parallelogram
- Operation steps: represented by a rectangle
正在渲染流程图...
✨ Simple if-else Structure
if-else Syntax
The if-else structure checks a condition: if true, it executes the code after if; if false, it executes the code after else.
if (boolean_expression) {
Operation 1
} else {
Operation 2
}if-else Flowchart
正在渲染流程图...
if-else Usage Notes
Keep the following points in mind when using if-else:
- The if structure can be used alone, but the else structure must follow an if structure
- The boolean expression after if must be enclosed in parentheses
- If multiple lines of code need to be executed after if-else, they must be enclosed in curly braces
✨ Comprehensive Examples
Example 1: Check Odd or Even
Input an integer and determine whether it's even or odd using the modulo operation.
正在渲染流程图...
1int n;
2cin >> n;
3if (n % 2 == 0) {
4 cout << "Even" << endl;
5} else {
6 cout << "Odd" << endl;
7}Example 2: Pass or Fail
Input a score; 60 or above is a pass, otherwise fail.
正在渲染流程图...
1int score;
2cin >> score;
3if (score >= 60) {
4 cout << "Pass" << endl;
5} else {
6 cout << "Fail" << endl;
7}III. Homework
Programming Exercises
- Absolute Value: L1084
- Compare Two Numbers: L1085
- Check if Two-Digit Number: L1086
- Luggage Shipping Price: L1087