If Else in C++
Flow control or if-else statements are used, when we have to take decision, depending upon certain condition.
Types of if-else statements:
- if Statement
- if-else
- if-else Ladder
- Nested if-else
if Statement
if statement takes condition in parenthesis and a block of statements within braces. If condition is true, it will return non-zero value, and statements given in if block will get execute.
Syntax of simple if statement :
if (condition) { - - - - - - - - - - - - - - - - - - - - }
if-else Statement
if statement takes condition in parenthesis and a block of statements within braces. If condition is true, it will return non-zero value, and statements given in if block will get execute. If condition is false, it will returns zero, and statements given in else block will get execute.
Syntax of simple if-else statement
if (condition) { - - - - - - - - - - - - - - - - - - - - } else { - - - - - - - - - - - - - - - - - - - - }
Example of simple if-else statement
#include<iostream.h> void main() { int num; cout << "Enter any number : "; cin >> num; if (num>0) cout << num <<" is Positive."; else cout << num <<" is Negative."; } Output : Enter any number : 24 24 is Positive
if-else Ladder
if-else ladder is used for checking multiple conditions, if the first condition will not satisfy, compiler will jump to else block and check the next condition, whether it is true or not and so on.
Syntax of if-else ladder statement
if (condition) { - - - - - - - - - - - - - - - - - - - - } else if (condition) { - - - - - - - - - - - - - - - - - - - - } else if (condition) { - - - - - - - - - - - - - - - - - - - - } else { - - - - - - - - - - - - - - - - - - - - }
Example of if-else ladder statement
#include<iostream.h> void main() { int amt,discount; cout << "Enter amount : "; cin >> amt; if (amt>20000) discount=15; else if (amt>15000) discount=10; else if (amt>10000) discount=5; else discount=0; cout << "You will get " << discount << "% discount."; } Output : Enter amount : 14000 You will get 5% discount.
Nested if-else Statement
In nested if-else, one if-else statement contains another if-else statement.
Syntax of nested if-else statement
if (condition) { if (condition) else } else { if (condition) else }
Example of nested if-else statement
#include<iostream.h> void main() { int a,b,c; cout << "\nEnter value of A : "; cin >> a; cout << "\nEnter value of B : "; cin >> b; cout << "\nEnter value of C++ : "; cin >> c; if (a>b) { if (a>c) cout << "\n\nA is Greatest"; else cout << "\n\nC is Greatest"; } else { if (b>c) cout << "\n\nB is Greatest"; else cout << "\n\nC is Greatest"; } } Output : Enter value of A : 45 Enter value of B : 89 Enter value of C : 78 B is Greatest
note:-it's just a sudo code if its not executing on your device make some changes in the further code this is only for understanding logic.
0 Comments