If-else statements allow you to execute a block of code based on a condition. They enable you to control the flow of your program by making decisions at runtime. Depending on whether the condition evaluates to true or false, different sets of instructions are executed.
The syntax of if else condition is:
if(expression) { //statement //statement } else { //statement //statement }
#include<stdio.h> int main() { int x=10; if(x==10) { printf("Small Code"); } else { printf("Vicky Chaurasiya"); } }
Small Code
Here x=10 and the condition is 10==10 it is absolutely correct,then the statement of if will execute.
It is modified form of if-else statement means if the we have multiple number of condition along with multiple output or if we have multiple number of choices then we use if-else ladder form.the syntax of if else condition is:-
if( expression ) { //statement //statement } else if( expression ) { //statement //statement } else { //statement //statement }
#include<stdio.h> int main() { int x=10; if(x>5) { printf("Vikas Chaurasiya"); } else if(x==10) { printf("Small Code"); } else { printf("Vicky Chaurasiya"); } }
Small Code
Here x=10 and the condition is 10==10 it is absolutely correct,then the statement of if will execute.
It is also modified form of if-else statement means if the we have more the one condition then we use Nested and the syntax of if else condition is:-
if( expression ) { if( expression ) { //statement1 //statement2 } } else { //statement3 //statement4 }
#include<stdio.h> int main() { int year; printf("Please Enter any year="); scanf("%d",&year); if(year%4 == 0) { if( year%100 == 0) { if ( year%400 == 0) printf("%d is a Leap Year.", year); else printf("%d is not the Leap Year.", year); } else printf("%d is a Leap Year.", year ); } else printf("%d is not the Leap Year.", year); return 0; }
i/o: Please Enter any year=2020
2020 is a leap year.