21
NovIf...else statement in C Programming
if...else Statement in C
An 'if' statement in C is like asking a question to the system. The if...else statement checks whether a condition is true or false. If the condition is true, the system performs the task specified in the block of code. If it's false, the system skips the ‘if’ block and moves on to the next instruction.
In this C Tutorial, we will explore more about the if...else statement in C Programming which will include an if...else statement in C with an example, if....else statement syntax in C.
What is the if-else Statement in C?
- if-else is the first kind of control statement in C.
- In this, the operations are performed according to some specified condition.
- The statements inside the body of the if block get executed if and only if the given condition is true.
- It is an extension of the if statement.
- Here, there is an if block and an else block. When one wants to print output for both cases - true and false, use the if-else statement.
Syntax
if(test condition){
//code to be executed if condition is true
}else{
//code to be executed if condition is false
}
Flowchart
How to Use it?
#include <stdio.h>
int main() {
int num = 10;
if(num < 5) {
printf("Number is less than 5\n");
}
else if(num < 10) {
printf("Number is between 5 and 9\n");
}
else {
printf("Number is 10 or greater\n");
}
return 0;
}
- In the above code, the
if
condition checks if thenum
is less than 5 - The given number 10 is greater than 5.
- Therefore, the
if
the block gets skipped. - The statement inside the
else
the block gets printed.
Output
Number is 10 or greater
Working of if...else Statement
The test condition is checked when the program control first comes to the if-else block.
- If the test condition is true in the given code, Then if the block is executed.
- If the test condition is false in the given code, Then the else block is executed
- After that, the code control continues to the statements below the if-else statement.
Advantages
- The if-else statement helps the developer to make decisions in code and execute the right code.
- It also helps developers in the debugging of code.
Disadvantages
- It increases the number of code paths to be tested.
- If there are a lot of if statements present in the code, it sometimes becomes unreadable.
Conclusion
So we explored the if...else statement in C. Don't forget to give feedback on this article. Take your proficiency in C programming to the next level by pursuing a C Programming Course, which will validate your expertise in loops and other important concepts.