Conditional Statements in C++ language

When we want to execute a program on the base of some particular condition is known as a conditional statement. So, C++ provides some statements for implementing selection control structure. In the conditional statement the condition is firstly checked and then the block of that condition is executed.
There are different types of conditional statement we have and are listed below:
1. " if " statement
2. " if-else " statement
3. " nested if " statement

We will explain each statement one by one below:

1. IF statement: if() statement is one of the basic conditional statement which has the single entry and exit statement. This simply includes a condition and if that condition is true the block of if statement is executed.

Syntax for the IF statement:

if(condition) // this particular block is executed if condition is true only
{
statement 1.......n;
}

C++ Program which explains the working of IF condition.

Program Code:
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter the age of person : ";
cin>>age;
if(age>=18)
{
cout<<"Person is eligible for vote";
}
cout<<"Program end ";
return 0;
}



The program is tested on www.jdoodle.com
Output:
Enter the age of person : 20
Person is eligible for vote
Program end 
  

2. IF-Else statement: In if statement there is only one block for execution if the condition is true but nothing for if the condition is false. So in IF-Else statement, if the condition is true then the if statement block is executed and if condition is false then the else block is executed.

Syntax for the IF-Else statement:

if(condition) // this particular block is executed if condition is true only
{
statement 1.......n;
}
else // this else block is executed if the condition is false 
{
statement 1.......n;
}

C++ Program which explain the working of IF-Else condition.

Program Code:
#include<iostream>
using namespace std;
int main()
{
int age;
cout<<"Enter the age of person : ";
cin>>age;
if(age>=18)
{
cout<<"Person is eligible for vote";
}
else
{
cout<<"Person is not eligible for vote ";
}
return 0;
}

The program is tested on www.jdoodle.com
Output:
Enter the age of person : 20
Person is eligible for vote


3. Nested  IF statement: In nested if statement, if block may be nested in another if or else block. This is known as nesting of if or else block.

Syntax for the Nested-if statement:
if(condition) // this particular block is executed if condition is true only
{
if(condition)
{
statement 1.......n;
}
}


Thanks
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: