Today, let’s talk about the C language. When I first started learning, I was also confused, thinking it seemed simple, but I encountered various problems when using it. After years of trial and error, I would like to share some of my insights with you.
Here are examples of using selection statements in C language:
if Statement
-
• Single Branch if Statement: Determine if a number is positive and output it.
#include <stdio.h>
int main() {
int num;
printf("Please enter an integer: ");
scanf("%d", &num);
if (num > 0) {
printf("%d is a positive number\n", num);
}
return 0;
}
-
• Double Branch if Statement: Determine if a number is odd or even.
#include <stdio.h>
int main() {
int a;
printf("Please enter an integer: ");
scanf("%d", &a);
if (a % 2 == 0) {
printf("It is an even number\n");
} else {
printf("It is an odd number\n");
}
return 0;
}
-
• Multiple Branch if Statement: Output the corresponding grade based on the student’s score.
#include <stdio.h>
int main() {
int score;
printf("Please enter a score: ");
scanf("%d", &score);
if (score >= 90 && score <= 100) {
printf("Class A\n");
} else if (score >= 80 && score < 90) {
printf("Class B\n");
} else if (score >= 70 && score < 80) {
printf("Class C\n");
} else if (score >= 60 && score < 70) {
printf("Class D\n");
} else {
printf("Class E\n");
}
return 0;
}
switch Statement
-
• Output the corresponding day of the week based on the input number:
#include <stdio.h>
int main() {
int day;
printf("Please enter a number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Input error, please enter a number between 1-7\n");
}
return 0;
}
-
• Perform calculations based on the input operator:
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("Please enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Please enter two numbers: ");
scanf("%f %f", &num1, &num2);
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
printf("Denominator cannot be 0\n");
return 0;
}
result = num1 / num2;
break;
default:
printf("Unsupported operator\n");
return 0;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}