Category: CPlusPlus Tutorial

  • C++ if-else-if ladder statement

    This statement allows the user to have multiple options to check for different conditions. Here, if one of the if or else-if condition is true then that part of the code will be executed and the rest will be skipped. if none of the conditions are true then the final else statement present at the end will be executed.

    The syntax of the if-else-if ladder statement in C++:

     if(condition1)
     {  
       //code to be executed if condition1 is true  
     }
     else if(condition2){  
       //code to be executed if condition2 is true  
     }  
     else if(condition3){  
       //code to be executed if condition3 is true  
     }  
       ...  
     else{  
        //final else if all the above condition are false 
     }

    Flowchart diagram for if-else if statement:

    if elseif statement

    Example of C++ if-else-if ladder statement

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 100;
    
      	// check condition
       if (a > 50)
       {
          cout << "Value of a less than 10." << endl;
       }
       else if (a == 10)
       {
          cout << "Value of a is equal to 20." << endl;
       }
       else if (a < 30)
       {
          cout << "Value of a is greater than 30." << endl;
       }
       else
       {
          cout << "None of the condition is true" << endl;
       }
    
       cout << "Value of a: " << a << endl;
    
       return 0;
    }

    Output:

    Value of a less than 10.
    Value of a: 100

  • C++ nested if statement

    This statement allows the user to use if block inside the other if block. And the inner if statement is executed only if the outer if statement’s condition is true.

    The syntax of the nested if statement in C++:

    if(condition1)
    {    
       //block of code to be executed    
       if(condition2)
       {  
         //block of code to be executed    
       }    
    } 

    You can also nest the if..else statement in same manner as shown below.

    //Nested if....else statement
    
    if(condition1)
    {
        if(condition2)
        {
            //block of statement;
        }
        else 
        {
            //block of statement;
        }
    }
    else
    {
        //block of statement;
    }

    nested if statement Flowchart:

    nested if

    Example of nested if statement in C++

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 50;
       int b = 110;
    
      	// check condition
       if (a < 100)
       {
         	// agian the use of if
          if (b < 200)
          {
             cout << "Value of a and b are 50 and 110 respectively" << endl;
          }
       }
    
       cout << "Value of a is: " << a << endl;
       cout << "Value of b is: " << b << endl;
    
       return 0;
    }
    
    

    Output:

    Value of a and b are 50 and 110 respectively
    Value of a is: 50
    Value of b is: 110

    Example of C++ nested if…else statement

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a, b, c;
    
       cout << "Enter 3 integers: ";
       cin >> a >> b >> c;
    
       if (a > b)
       {
          if (a > c)
          {
             cout << a << " is greatest of all.";
          }
          else
          {
             cout << c << " is greatest of all.";
          }
       }
       else
       {
          if (b > c)
          {
             cout << b << " is greatest of all.";
          }
          else
          {
             cout << c << " is greatest of all.";
          }
       }
    }

    Output:

    Enter 3 integers: 2 5 4
    5 is greatest of all.

  • C++ if…else statement

    If the Boolean expression is true then the code inside the if statement block is executed or if it is false then the code inside else statement will be executed. Hence if..else statement.

    The syntax of the if..else statement in C++:

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

    If…else Flowchart:

    if…else

    Example of if…else statement in C++

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int x = 50;
    
       // check condition
       if (x < 20)
       {
          //condition is true
          cout << "x is less than 20;" << endl;
       }
       else
       {
          //condition is false
          cout << "x is not less than 20;" << endl;
       }
    
       cout << "value of x: " << x << endl;
    
       return 0;
    }

    The output of if…else statement in C++.

    x is not less than 20;
    value of x: 50

  • C++ if Statement

    An if statement consists of a Boolean expression followed by one or more statements. If the Boolean expression is true, the block of code inside the if statement will be executed else not. This is most simple of all the decision making statements.

    The syntax of the if statement in C++:

    if (condition) 
    {
       //block of statement
    }
    • If the condition is evaluated true, block of statement is executed.
    • If the condition is evaluated false, block of statement is skipped.

    if statement Flowchart:

    if statement

    Example of C++ if statement:

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int x = 100;
    
       //check the Boolean condition
       if (x < 200)
       {
          //if true, following will be displayed
          cout << "x is less than 200;" << endl;
       }
    
       cout << "value of x: " << x << endl;
    
       return 0;
    }

    Output:

    x is less than 200;
    value of x: 100

  • Type Conversion in C++

    C++ programming allows us to convert the variables from one data type to another. A type cast basically means the conversion of one data type to another.

    There are two types of conversion in C++:

    1. Implicit Conversion
    2. Explicit Conversion (or type casting)

    Implicit Conversion

    Implicit type conversion which is also known as ‘Automatic type conversion’, converts one data type to another without any external trigger from the user. The conversion is done by the compiler on its own that is why it is known as Automatic type.

    This generally takes place in an expression where more than one data types are present, to avoid lose of data. In such conversion, variables with all data types are converted to the largest data type present. The precedence of conversion is in the following order:

    bool -> char -> short int -> int -> 
    
    unsigned int -> long -> unsigned -> 
    
    long long -> float -> double -> long double

    Example of implicit type casting in C++ programming:

    //implicit type-conversion
    
    #include <iostream>
    using namespace std;
    
    int main()
    {
       //integer type variable
       int integer_num = 7;
    
       //double type variable
       double double_num;
    
       //int assign to double, Implicit conversion
       double_num = integer_num;
    
       cout << "Integer Value: " << integer_num << endl;
       cout << "Double Value: " << double_num << endl;
    
       return 0;
    }

    Output:

    Integer Value: 7
    Double Value: 7

    Data Loss:

    While Implicit conversion, data may get lost that is sign can be lost when signed type is implicitly converted to the unsigned type or when long is implicitly converted to float.

    This happens when data of a larger type is converted to data of a smaller type.
    long double - > double -> float -> long -> short -> char

    Example: Take an example shown below.

    int x;
    float y = 45.99;
    
    //assigning float value to an int variable
    x = y;

    As soon as the float variable is assign to the int variable, the compiler implicitly convert the float value to integer (with no decimal part).

    Now if you print the value of x, the output will be 45. As you can see, the .99 (decimal part is lost). Since int cannot have a decimal part, the digits after the decimal point are truncated in the above example.


    Explicit Conversion

    Sometimes, the situation may arise where the programmer might need to force the compiler to change the data type and that is when the Explicit casting is performed. When the user performs the data type conversion manually then it is called Explicit Casting.

    This process is also called type casting and it is dependent on user.

    Explicit conversion in C++ can be done in three different ways.

    1. Cast Notation (By assigning)
    2. Type conversion operators

    1. Cast Notation (By assigning): It is a forceful method to convert the data types Explicitly. The required data type is defined explicitly in front of the expression in parenthesis.

    Syntax for this style is:

    (data_type)expression;

    Example:

    //c++ explicit type casting
    #include <iostream>
    using namespace std;
    
    int main()
    {
       double num = 5.2;
    
      	//Explicit conversion
       int result = (int) num + 5;
    
       cout << "Result: " << result;
    
       return 0;
    }

    Output: After execution following output will displayed.

    Result: 10

    2. Type conversion operators:

    There are four types of casting operators in C++ which forces one data type to be converted into another data type. these are the unary data type. They are:

    • static_cast
    • dynamic_cast
    • const_cast
    • reinterpret_cast

    However, these casting will be discussed later on this C++ tutorials.


  • C++ Increment and Decrement Operators

    Increment and Decrement Operators are the Unary Operators as they operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.

    • Post-Increment or Post-Decrement:
      First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
    • Pre-Increment Pre-Decrement:
      Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.

    Let us understand the post and pre with an example.


    Example: C++ program for Increment and Decrement Operators

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 11;
       int result;
    
       //a value is not increased instantly, it will be increased after the assignment
       result = a++;
       cout << "Value of a++: " << result << endl;	//prints 11
    
       //now the value of is increased by 1
       cout << "value of a: " << a << endl;	//prints 12
    
       //the value is increased before the assignment
       result = ++a;
       cout << "Value of ++a: " << result << endl;	//prints 13
    
       return 0;
    }

    Output:

    Value of a++: 11
    value of a: 12
    Value of ++a: 13

  • C++ Arithmetic Operators

    Arithmetic Operators the symbols that are used to perform mathematical operations on operands such as addition, subtraction, multiplication, division etc.

    operatordescription
    +addition
    adds two operands. eg, a+b.
    -subtraction
    subtracts two operands. eg, a-b.
    *multiplication
    multiplies two operands. eg, a*b.
    /division
    divides the operand by the second. eg, a/b.
    %modulo
    returns the remainder when the first operand is divided by the second. For example, a%b.

    Example: C++ program for the Arithmetic operators.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 12;
       int b = 5;
       int result;
    
       result = a + b;
       cout << "Addition Result: " << result << endl;
    
       result = a - b;
       cout << "Subtraction Result: " << result << endl;
    
       result = a * b;
       cout << "Multiplication Result: " << result << endl;
    
       result = a / b;
       cout << "Division Result: " << result << endl;
    
       result = a % b;
       cout << "modulo Result: " << result << endl;
    
       return 0;
    }

    Output: Result of Arithmetic Operators in C++

    Addition Result: 17
    Subtraction Result: 7
    Multiplication Result: 60
    Division Result: 2
    modulo Result: 2

  • C++ Assignment Operators

    Assignment operators are used in a program to assign a value of the right-hand side to the left-hand side as shown below.

    //10 is assign to the variable a
    int a = 10;
    
    //the value of b (10) is assigned to a
    int b = 20;
    int a = b;

    These are the short version formed by combining the two operators. For example Instead of writing, int a = a+5, we can write a += 5.

    Following are the list of assignment operators used in C++.

    OperatorDescription
    =Simple assignment operator, Assigns values from right side operands to left side operand.
    a = b + c;
    +=Add AND assignment operator, It adds the right operand to the left operand and assigns the result to the left operand.
    a += b
    -=Subtract AND assignment operator, It subtracts the right operand from the left operand and assigns the result to the left operand.
    a -= b
    *=Multiply AND assignment operator, It multiplies the right operand with the left operand and assigns the result to the left operand.
    a *= b
    /=Divide AND assignment operator, It divides left operand with the right operand and assigns the result to the left operand.
    a /= b
    %=Modulus AND assignment operator, It takes modulus using two operands and assigns the result to the left operand.
    a %= b
    <<=Left shift AND assignment operator.
    a <<= 2
    >>=Right shift AND assignment operator.
    a >>= 2 or a = a >> 2
    &=Bitwise AND assignment operator.
    a &= 2 or a = a & 2
    ^=Bitwise exclusive OR and assignment operator.
    a ^= 2 or a = a ^ 2
    |=Bitwise inclusive OR and assignment operator.
    a |= 2 or a = a | 2

    Example: C++ program for Assignment Operators

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 11;
       int result;
    
       result = a;
       cout << "=  Operator: " << result << endl;
    
       result += a;
       cout << "+= Operator: " << result << endl;
    
       result -= a;
       cout << "- -= Operator: " << result << endl;
    
       result *= a;
       cout << "*= Operator: " << result << endl;
    
       result /= a;
       cout << "/= Operator: " << result << endl;
    
       result = 100;
       result %= a;
       cout << "%= Operator: " << result << endl;
    
       result <<= 2;
       cout << "<<= Operator: " << result << endl;
    
       result >>= 2;
       cout << ">>= Operator: " << result << endl;
    
       result &= 2;
       cout << "&= Operator: " << result << endl;
    
       result ^= 2;
       cout << "^= Operator: " << result << endl;
    
       result |= 2;
       cout << "|= Operator: " << result << endl;
    
       return 0;
    }

    Output:

    =  Operator: 11
    += Operator: 22
    - -= Operator: 11
    *= Operator: 121
    /= Operator: 11
    %= Operator: 1
    <<= Operator: 4
    >>= Operator: 1
    &= Operator: 0
    ^= Operator: 2
    |= Operator: 2

  • C++ Relational Operators

    These operators are used to compare two values and return Boolean results. For example: it checks if the operand is equal to another operand or not or an operand is greater than the other operand or not or check less than between two values, etc.

    List of C++ relational operators:

    OperatorNameExample
    ==Equal to.A == B
    !=Not equal.A != B
    >Greater than.A > B
    <Less than.A < B
    >=Greater than or equal to.A >= B
    <=Less than or equal to.A <= B

    Example: C++ program for Relational Operators

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a, b;
       a = 3;
       b = 5;
       bool result;
    
       if (a == b)	// false
          cout << "a == b is true" << endl;
       else
          cout << "a == b is false" << endl;
    
       if (a != b)	// true
          cout << "a != b is true" << endl;
       else
          cout << "a != b is false" << endl;
    
       if (a > b)	// false
          cout << "a > b is true" << endl;
       else
          cout << "a > b is false" << endl;
    
       if (a < b)	// true
          cout << "a < b is true" << endl;
       else
          cout << "a < b is false" << endl;
    
       if (a >= b)	// false
          cout << "a >= b is true" << endl;
       else
          cout << "a >= b is false" << endl;
    
       if (a <= b)	// true
          cout << "a <= b is true" << endl;
       else
          cout << "a <= b is false" << endl;
    
       return 0;
    }

    Output:

    a == b is false
    a != b is true
    a > b is false
    a < b is true
    a >= b is false
    a <= b is true

  • C++ Logical Operators

    Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. They are used to combine two different expressions together.

    The following are the C++ Logical Operators. Assume X holds the value 1 and Y holds 0

    OperatorDescriptionExample
    && (logical and)If both the operands are non-zero, then the condition becomes true.(X && Y) is false
    || (logical or)If any of the two operands are non-zero, then the condition becomes true.(X || Y) is true
    ! (logical not)Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(X && Y) is true

    C++ program for Logical Operators

    Let us see the following example to understand logical operators better.

    #include <iostream>
    using namespace std;
    
    int main()
    {
       int a = 7, b = 3, c = 8, d = 6;
    
      	//both the condition has to be true
       if (a == b && c > d)
          cout << "a equals to b AND c is greater than d, TRUE\n";
       else
          cout << "AND operation is FALSE\n";
    
      	//any one the condition has to be true
       if (a == b || c > d)
          cout << "a equals to b OR c is greater than d, TRUE\n";
       else
          cout << "OR operation is FALSE\n";
    
       if (!b)
          cout << "b is zero\n";
       else
          cout << "b is not zero";
    
       return 0;
    }

    Output:

    AND operation is FALSE
    a equals to b OR c is greater than d, TRUE
    b is not zero