Control Statement in C++

Control Statement in C++

Control Statement in C++ are as follows

    • if statement
    • if-else statement
    • if-else-if ladder

1. If Statement in C++

An ‘if’ statement consists of a boolean expression.’If’ statement is used ro specify a block of code to be executed if condition is true and If the condition is false then code inside body of ‘if’ is skipped.

Syntax of if statement

if(condition){    
//code to be executed    
}  

Program of if statement in C++

#include <iostream>  
using namespace std;  
   
int main () {  
   int num = 10;    
            if (num % 2 == 0)    
            {    
                cout<<"Number is even";    
            }   
   return 0;  
}  

Output

Number is even

2. If-else Statement in C++

The if-else statement in C++  tests the given condition. It executes when if condition is true. If the condition evaluates false then code inside the body of else is skipped from execution

Syntax of if else statement

if(condition){    
//code if condition is true    
}else{    
//code if condition is false    
}    

Program of if else statement in C++

#include <iostream>  
using namespace std;  
int main () {  
   int num = 15;    
            if (num % 2 == 0)    
            {    
                cout<<"Number is even";    
            }   
            else  
            {    
                cout<<"Number is odd";    
            }  
   return 0;  
}  

Output

It is odd number

3. IF-else-if ladder Statement in C++

Syntax of if else if statement

if(expression 1)
{
    statement-block1;
}
else if(expression 2) 
{
    statement-block2;
}
else if(expression 3 ) 
{
    statement-block3;
}
else 
    default-statement;

Here, code block1 is executed only when condition1 is true. And if it is false then condition2 is executed.

Code block 2 is executed only when  condition2 is true. And if it is false then code block 2 executed

 

Program of if else if statement in C++

#include <iostream> 
using namespace std; 
int main( )
{
    int a=20;
    
    if( a%5==0 && a%8==0)
    {
        cout << "divisible by both 2 and 10";
    }  
    else if( a%8==0 )
    {
        cout << "divisible by 2";
    }
    else if(a%5==0)
    {
        cout << "divisible by 10";
    }
    else 
    {
        cout << "None";
    }
return 0;
}

Output

divisible by both 2 and 10

 

Read more, Comments in C++

Share this post

Leave a Reply

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