If else statement is the conditional statement.
Conditional statement :- it means we can change flow of executing program based on condition in program.
If else statement : It is the simple and commonly used conditional statement in c++. if statement contains condition , if this conditional is true then the statements followed by if statement is executed otherwise statement in else block get executed.
Syntax for if else statement in c++
123456789101112131415161718192021222324252627 | if(condition){Statement 1;Statement 2;..Statement n;}else {Statement 1;Statement 2;..Statement n;} |
In above syntax ,
1. We write if keyword followed by condition in bracket (). and after that we write statement in block enclosed in curly braces { }. You can write any number of statement in if block enclosed in { } . if you want to execute only one statement in if block then you not need to write curly braces.In this case statement (one )followed by if block is executed similarly for else block.
2. If condition is true then statement in of block get executed i.e statement 1 to statement n otherwise the statement in else block get executed i.e statement 1 to statement n.
Example
1234567 | if(x>1)cout<<“x value greater than 1”;elsecout<<“x value less than 1”; |
In above example, if statement checks value of x if it is greater than 1 then statement x value greater than 1 is executed otherwise x value less than 1 get executed.
Program to demonstrate if else statement
1234567891011121314151617181920212223242526272829303132333435 | #include<iostream.h>#include<conio.h>void main (){int x;cout<<“if _ else statement in cpp”<<endl;cout<<“Enter x value”<<endl;cin>>x;if(x>10) //if statement to check condition{cout<<“x value is greater than 10” //executed if condition true}else{cout<<“x value is less than 10”. //executed if condition is false}getch();} |
Output :-
if else statement in c++
Enter x value
11
x value greater than 10
Program description
- In above program we demonstrate if else statement.
- First we taken input from user in variable x
- Then first if condition we check condition if(x>10) if user enters value greater than 10 then if condition if (x > 10) get true and statement in if (i.e x value greater than 10) is executed and statement in else block get skipped.
- And if use enters value less than 10 then if condition if(x> 10) get false and statement in if block skipped and statement in else block get executed (i.e x value less than 10).