In this tutorial, you will be familiarize with the conditional statements available for C programming language along with their syntax.
Conditional statements
Conditional statements are those code which allows you to control the program’s flow of the execution centred on a condition.
It means that the statements in the program are not executed in sequence.
Rather, one group of statements is executed, depending on how the condition is evaluated.
Conditional statements in C programming language are:
- if statement
2. if-else statement
3. Ternary\conditional statement
4. nested if-else statement
5. switch statement
- if Statement:
Syntax for if statement:
if (condition) { statement; statement; }
- If condition written in brackets() is true, then single statement or multiple statements inside the curly braces executes, otherwise skipped.
- Numerical values other than zero is considered true while zero is false.
2. if-else Statement:
Syntax for if-else Statement :
if (condition) statement; else statement;
3. CONDITIONAL OPERATOR IN C:
Conditional operator in C is defined as operator which checks condition which is written before (?) and returns one value as a result/output.
Syntax for the conditional operator is:
(test expression)? Expression1: Expression2 ;
For example :
(A > 100 ? 0 : 1);
In above example, if value stored in variable A is greater than 100, then 0 is returned else 1 is returned as output.
This is equivalent to if else conditional statements.
If conditional operators return a value then we have to store the output in a variable.
Then the syntax is given below:
Variable = (test expression)? Expression1: Expression2 ;
For example:
int x = (A > 100 ? 0 : 1);
In above example, if value stored in variable A is greater than 100, then 0 is returned else 1 is returned as output and returned value is stored in variable x.
4. nested if-else Statement:
Syntax for nested if-else Statement:
if (condition1) if (condition2) if (condition3) statements; else statements;
5. switch statement:
Syntax for switch statement:
switch (expression) { case label: statements; break; case label: statements; break; case label: statements; break; case label: statements; break; default : statements; break; }
* Expression written in the switch must results in integer value.
* Otherwise default statement executes if present in the switch statement.
* break statement must be written in the end in each case.
* break causes the execution to jump out of the switch to the statement immediately following the switch.
This is all about the conditional statements available for C programming language along with their syntax.
if you have any query please comment below.