Conditional Statements
In C, the conditional statement is used to control the flow of a program based on certain conditions. It allows you to execute different blocks of code depending on whether a specified condition is true or false.
We use if, if-else, else-if as conditional statements.
Note: We use comparison operators to check the condition.
If statement
If statement checks the condition and execute the specific code.
If else
If-else is used as conditional statement. In if else statements, if one condition is true, it will be executed and all others will be ignored.
- If requires condition.
- Else does not require condition.
Else if
If you want to check conditions more than one time then use else if.
If else with logical operators
If you want to check two condition in single if statement, you will use logical operators.
In this way, you can use any comparison operator with conditional statements to check conditions.
Nested if else
In nested if else, we use if statement within if statement.
Dangling else Grammar
If you are using multiple if statements and single else statement, then there is dangling else problem.
Compiler does not know that with which if, else will go.
Ternary Operator
It is also used to check condition like if else. It is a single lined statement.
Goto Statement
As name indicates goto statemet is used to go to a particular line of code. We labelled a line of code and at some point, we write "goto label" and our control jumps to that label.
Note: You can use ternary operator when logic is simple. It makes your code more compact and easy to use.
Practice Exercises
Complete these exercises to reinforce your learning and earn XP