Every coin has 2 faces and this can be additionally true for our issues. until currently, we’ve learnt regarding if statement within which we will execute a group of statements by giving some condition or expression.
But most of your time we’d like to execute one set of statements if the condition is true, and a wholly completely different set of statements if the condition is fake.
This task is often accomplished simply in C language by mistreatment if-else statement.
Syntax of if-else statement
\ if(condition)
one
Statement two and then on
}
else
one
Statement two and then on
}
Few points regarding the if-else block
The statements within if keyword is together known as if block.
The statements within else keyword is together known as else block.
The parenthesis within if-else block are often born, if there’s just one statement
statement in it. because the default scope of those keywords is just one statement.
No condition is employed with else keyword. The statements beneath else are going to be dead providing the condition with if statement is end up false. thus it’s treated as default selection.
The best thanks to perceiving a subject is thru a program. Let’s create one program mistreatment if-else statement.
Program to visualize a negative variety
#include <stdio.h>
void main()
{
int num;
printf("Enter a number to check if it is negative:n");
scanf("%d",&num);
if(num<0)
{
printf("Number is negative");
}
else
{
printf("Number is positive");
}
}
Output
Inter a number to check if it is negative:
7
number is positive
Explanation
Statements in starting are self-explainable. I hope until currently, you’re additionally at home with them.
The main logic of the program lies within if-else block. within the if block I actually have written a condition that is checking, if the quantity is negative. If it seems to be true then the message “Number is negative” is written, otherwise compiler can skip this block.
In the next else block I actually have written just one printf() operate which can print the message “Number is positive”.
Checkout I actually have written no condition with else keyword. As I aforementioned earlier else block is employed because the default block.
In our take a look at run I actually have entered the quantity seven that is positive. thus once taking the input, compiler checked the condition. It seems false thus it dead the statements beneath else block.