In this tutorial you will learn about if statement, if-else statement and if-else-if statement, which are also known as decision making statements.
Given below is the structure of an if statement:
Conditional expression can be anything which can give true or false. Hence is the statement is true, the code in the body of the statement run. If the conditional statement evaluates to false. Given below is an example of if statement:
The result on Serial Monitor is:
The student1 marks is greater than 33. He passed the exam.
The student2 marks is less than or eqaul to 33. He failed the exam.
In the above code is Student 1 has marks greater than 33 hence the first statement is true and gets executed. For Student2 second statement is true, hence second stat ement is executed.
When using an if statement, the code in the body of the if statement is run only when the if statement evaluates to true. When it evaluates to false, program execution skips the code in the body of the if statement and continues below the body of the if statement.
By adding an else statement, code in the body of the else statement will run only when its corresponding if statement evaluates to false.
Hence, When the conditional expression evaluates to true:
When the conditional expression evaluates to false:
Given below is an example of if else statement:
The if-else-if construct allows further conditional expressions to be evaluated than the if-else construct.
Basic structure is given below:
Hence, When the conditional expression 1 evaluates to true:
When the conditional expression 1 evaluates false and conditional expression 2 evaluates to true:
When the conditional expression 1 and 2 evaluates to false:
Given below is an example of if-else-if statement:
Your grade is: A
Try changing marks and check each if-else-if statement.