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,

if (condition is true)
   // code will execute if the condition is true

Here’s an example showing if decision making statement,

#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 C++ decision making statements

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,

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,

#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,

C++ if else decision making statement

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,

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.

#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,

C++ if elseif else decision making statement

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:


For Videos, Join Our YouTube Channel: Join Now


Read More:

C++ Operators
C++ Loops
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment