C - 嵌套的 If 認證語句

Hello there, aspiring programmers! Today, we're going to dive into the fascinating world of nested if statements in C. As your friendly neighborhood computer science teacher, I'm excited to guide you through this topic. Trust me, once you get the hang of it, you'll be nesting if statements like a pro bird builder!

C - nested if statements

什麼是嵌套的 If 認證語句?

Before we jump into the deep end, let's start with the basics. You know how in life, we often make decisions based on multiple conditions? Well, nested if statements are just like that! They allow us to check multiple conditions and execute different code blocks based on those conditions.

Imagine you're deciding what to wear. You might think:

  1. If it's cold outside...
  • If it's raining...
  • Wear a raincoat
  • Otherwise...
  • Wear a warm jacket
  1. Otherwise (if it's not cold)...
  • If it's sunny...
  • Wear a t-shirt
  • Otherwise...
  • Wear a light jacket

This decision-making process is exactly what nested if statements do in programming!

語法

Now, let's look at how we write nested if statements in C. The basic structure looks like this:

if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
else {
// Code to execute if condition1 is true but condition2 is false
}
}
else {
// Code to execute if condition1 is false
if (condition3) {
// Code to execute if condition1 is false but condition3 is true
}
else {
// Code to execute if both condition1 and condition3 are false
}
}

Don't worry if this looks a bit intimidating at first. We'll break it down with some examples!

示例 1:溫度和濕度

Let's start with a simple example. We'll write a program that suggests what to wear based on temperature and humidity.

#include <stdio.h>

int main() {
int temperature = 25;
int humidity = 80;

if (temperature > 30) {
if (humidity > 70) {
printf("It's hot and humid. Wear light, breathable clothes.\n");
} else {
printf("It's hot but dry. Wear light clothes and stay hydrated.\n");
}
} else if (temperature > 20) {
if (humidity > 70) {
printf("It's warm and humid. A t-shirt should be fine.\n");
} else {
printf("It's pleasant outside. Enjoy the weather!\n");
}
} else {
printf("It's cool. Consider wearing a light jacket.\n");
}

return 0;
}

In this example, we first check the temperature. If it's above 30°C, we then check the humidity to decide between "hot and humid" or "hot and dry" conditions. If the temperature is between 20°C and 30°C, we again check the humidity for more specific advice. If it's below 20°C, we simply suggest a light jacket.

示例 2:成績計算器

Now, let's try something a bit more complex. We'll create a grade calculator that not only determines the letter grade but also adds a plus or minus.

#include <stdio.h>

int main() {
int score = 85;

if (score >= 90) {
if (score >= 97) {
printf("A+\n");
} else if (score >= 93) {
printf("A\n");
} else {
printf("A-\n");
}
} else if (score >= 80) {
if (score >= 87) {
printf("B+\n");
} else if (score >= 83) {
printf("B\n");
} else {
printf("B-\n");
}
} else if (score >= 70) {
if (score >= 77) {
printf("C+\n");
} else if (score >= 73) {
printf("C\n");
} else {
printf("C-\n");
}
} else if (score >= 60) {
if (score >= 67) {
printf("D+\n");
} else if (score >= 63) {
printf("D\n");
} else {
printf("D-\n");
}
} else {
printf("F\n");
}

return 0;
}

This program first determines the general grade range (A, B, C, D, or F), then uses nested if statements to add the appropriate plus or minus. It's like a Russian nesting doll of grades!

示例 3:簡單的冒險遊戲

Let's have some fun and create a simple text-based adventure game using nested if statements.

#include <stdio.h>

int main() {
char direction;
printf("You're at a crossroad. Do you go left (L) or right (R)? ");
scanf(" %c", &direction);

if (direction == 'L' || direction == 'l') {
printf("You've chosen to go left.\n");
printf("You see a river. Do you swim across (S) or look for a bridge (B)? ");
scanf(" %c", &direction);

if (direction == 'S' || direction == 's') {
printf("You swim across and find a treasure chest. You win!\n");
} else if (direction == 'B' || direction == 'b') {
printf("You find a bridge, cross safely, but find no treasure. Game over.\n");
} else {
printf("Invalid choice. The river sweeps you away. Game over.\n");
}
} else if (direction == 'R' || direction == 'r') {
printf("You've chosen to go right.\n");
printf("You encounter a dragon. Do you fight (F) or run (R)? ");
scanf(" %c", &direction);

if (direction == 'F' || direction == 'f') {
printf("You bravely fight the dragon and win! You're a hero!\n");
} else if (direction == 'R' || direction == 'r') {
printf("You run away safely, but without glory. Game over.\n");
} else {
printf("Invalid choice. The dragon eats you. Game over.\n");
}
} else {
printf("Invalid choice. You stand still and nothing happens. Game over.\n");
}

return 0;
}

This game uses nested if statements to create different paths based on the player's choices. It's a simple demonstration of how nested if statements can create branching narratives or decision trees.

示例 4:登錄系統

For our final example, let's create a basic login system that checks both username and password.

#include <stdio.h>
#include <string.h>

int main() {
char username[20];
char password[20];

printf("Enter username: ");
scanf("%s", username);

if (strcmp(username, "admin") == 0) {
printf("Enter password: ");
scanf("%s", password);

if (strcmp(password, "secretpassword") == 0) {
printf("Login successful. Welcome, admin!\n");
} else {
printf("Incorrect password. Access denied.\n");
}
} else if (strcmp(username, "user") == 0) {
printf("Enter password: ");
scanf("%s", password);

if (strcmp(password, "userpass") == 0) {
printf("Login successful. Welcome, user!\n");
} else {
printf("Incorrect password. Access denied.\n");
}
} else {
printf("Username not found. Access denied.\n");
}

return 0;
}

In this example, we first check the username. If it matches "admin" or "user", we then check the corresponding password. This demonstrates how nested if statements can be used to implement multi-level authentication systems.

結論

Nested if statements are a powerful tool in your programming toolkit. They allow you to create complex decision-making structures and handle multiple conditions with ease. Remember, while they're incredibly useful, be careful not to nest too deeply, as it can make your code hard to read and maintain. As with many things in programming, clarity and simplicity are key!

I hope this tutorial has helped you understand nested if statements better. Keep practicing, and soon you'll be nesting conditions like a pro! Happy coding, future programmers!

Credits: Image by storyset