본문 바로가기

Study Meeting/빡공단 30기

[Day 11] Conditional Statement 1: if and else

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'.