I learned the conditional statement including 'if' and 'else'.
When setting conditions for an action, we can define the action by dividing it into 'if', 'elseif', and 'else' syntax.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
if (Condition 1) {
Action 1;
}
else if (Condition 2) {
Action 2;
}
else (Condition 3) {
Action 3;
}
return 0;
}
The action is executed after checking the conditions sequentially from the top. In other words, if the first condition of the if statement is true, the 'Action 1' code will be performed. On the other hand, if the if statement is false, the condition of the next elseif statement is verified, and 'Action 2' code is performed when true.
To help you understand the if statement, we have written an example code that grades according to your test scores.
Score | Grade |
90 ~ 100 | A |
80 ~ 90 | B |
Less than 80 | C |
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int Score;
char Grade;
if (Score > 90 ) {
Grade = 'A';
printf('Your grade is %C', Grade);
}
else if (Score > 80 && Score <= 90) {
Grade = 'B';
printf('Your grade is %C', Grade);
}
else (Score <= 80) {
Grade = 'C';
printf('Your grade is %C', Grade);
}
return 0;
}
If the score is 95, the first condition is verified as 'TRUE'. Therefore, the grade is assigned 'A'.
And if the score is 75, two conditons are verified as 'FALSE' and last condition is verified as 'TRUE'.
So, the grade is assigned 'B'.
'Study Meeting > 빡공단 30기' 카테고리의 다른 글
[Day 13] Repeated Statement: for and while (0) | 2023.01.13 |
---|---|
[Day 12] Conditional Statement 2: switch - case (0) | 2023.01.12 |
[Day 10] Operator 3: Bitwise Shift Operator (0) | 2023.01.11 |
[Day 9] Operator 2: Logical Operators and Bit operators in C Language (0) | 2023.01.10 |
[Day 8] Operator 1: Assignment, Relational, Arithmetic, Incremental Operators in C Language (0) | 2023.01.08 |