C++ If-Else-ElseIf Control Structure

In this Tutorial we will understand the working of the If-Else-elseif control structure in C++.

IF Structure

The IF Control Structure is a conditional control structure which executes depending on a particular condition. If a particular condition is true then the if block will execute otherwise that block is skipped and not executed. It is not compulsory to provide the else part if not necessary.

if block c++

Flow Chart diagram of If Control Structure

Run Online

#include<iostream>
using namespace std;
int main()
{
	cout<<"Please enter a number: ";
	int x;
	cin>>x;
	// this program only checks if the number is negative or not
	if(x<0)
	{
	   cout<<"Negative";
	}
	return 0;
}
  • The if statement evaluates the test expression inside parenthesis (x<0).
  • If test expression is  true, statements inside the body of if is executed.
  • If test expression is false, statements inside the body of if is skipped and not executed.
IF – ELSE Control Structure

The IF-Else Control Structure is a conditional control structure which executes depending on a particular condition. if the condition is true then the if block is executed, otherwise the else block is executed.

 

if else block diagram

Flow chart diagram of If-Else statements

Run Online

#include<iostream>
using namespace std;
int main()
{
	cout<<"Please enter a number: ";
	int x;
	cin>>x;
	if(x<0)
	{
		cout<<"Negative";
	}
	
	else
	{
		cout<<"the number is not negative";
	}
	return 0;
}
  • The if statement evaluates the test expression inside parenthesis (x<0).
  • If test expression is  true, statements inside the body of if is executed.
  • If test expression is false, statements inside the else block is executed.
IF – ELSE – ELSE IF Control Structure

The if-else-elseif control structure is typically used to check multiple conditions. Each if-elseif block has one condition each and every time the condition is checked with each block. If condition is true then that block is executed. if none of the conditions are true then the else part is executed.

 

if else if else block diagram

Flow chart diagram of If-ElseIf-Else statements

Run Online

#include<iostream>
using namespace std;
int main()
{
	cout<<"Please enter a number: ";
	int x;
	cin>>x;
	if(x<0)
	{
		cout<<"Negative";
	}
	
	else if(x>0)
	{
		cout<<"Positive";
	}
	else
	{
		cout<<"the number is 0";
	}
	return 0;
}
  • The if statement evaluates the test expression inside parenthesis (x<0).
  • If test expression1(x<0) is  true, statements inside the body of if is executed.
  • If test expression1(x<0) is false, the next expression inside the else if block is checked.
  • If test expression2(x>0) is  true, statements inside the body of else if is executed.
  • If test expression2 is also false, statements inside the else block is executed.
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *