30 Sep C++ Decision Making Statements
With C++ decision making statements, easily take decision based on different conditions. The following decision making statemente swe have discussed with examples,
- if
- if…else
- if…else if…else
Note: Learn how to run your first C++ program in Turbo C++. We will be running the following programs in the same way.
if statement
The if decision making statement executes the code, if the condition is true.
Here’s the syntax,
1 2 3 4 |
if (condition is true) // code will execute if the condition is true |
Here’s an example showing if decision making statement,
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream.h> #include <conio.h> void main () { int myVar = 25; if (myVar>10) cout<<"Value "<<myVar<<" is more than 10"; getch(); } |
Here’s the output,
if…else statement
The if…else decision making statement executes some code if the condition is true and another code if the condition is false. The false condition goes comes under else.
Here’s the syntax,
1 2 3 4 5 6 |
if (condition is true) // code will execute if the condition is true else // code will execute if the condition is false |
Here’s an example showing the if…else statement,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream.h> #include <conio.h> void main () { int myVar = 5; if (myVar>10) cout<<"Value "<<myVar<<" is more than 10"; else cout<<"Value "<<myVar<<" is less than 10"; getch(); } |
Here’s the output,
if…elseif…else Statement
The if…elseif…else statement executes code for different conditions. If more than 2 conditions are true, you can use else for the false condition.
Here’s the syntax,
1 2 3 4 5 6 7 8 9 10 |
if (condition1 is true) // code will execute if the condition is true else if (condition2 is true) // code will execute if another condition is true else if (condition3 is true) // code will execute if above conditions aren’t true else // code will execute if all the above given conditions are false |
Here’s an example showing the if…elseif…else statement,
Here, myVar = 10, and the else condition gets executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream.h> #include <conio.h> void main () { int myVar = 10; if (myVar>10) cout<<"Value "<<myVar<<" is more than 10"; else if(myVar < 10) cout<<"Value "<<myVar<<" is less than 10"; else cout<<"Values are equal!"; getch(); } |
Here’s the output,
No Comments