Author: admin

  • C# Assignment Operators

    These 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 = 5;
    
    //the value of b (10) is assigned to a
    int b = 10;
    int a = b;
    int a += 2; //a=a+2

    You can combine write in short version such as instead of writing, int a = a+5, you can write it as 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 of C# Assignment Operators

    using System;
    
    namespace Operators
    {
       class Assignment
       {
          static void Main(string[] args)
          {
             int a = 11;
             int result;
    
             result = a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result += a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result -= a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result *= a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result /= a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result = 200;
             result %= a;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result <<= 2;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result >>= 2;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result &= 2;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result ^= 2;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result |= 2;
             Console.WriteLine("'+' operator, Result: {0}", result);
          }
       }
    }

    Output:

    '+' operator, Result: 11
    '+' operator, Result: 22
    '+' operator, Result: 11
    '+' operator, Result: 121
    '+' operator, Result: 11
    '+' operator, Result: 2
    '+' operator, Result: 8
    '+' operator, Result: 2
    '+' operator, Result: 2
    '+' operator, Result: 0
    '+' operator, Result: 2

  • C# Arithmetic Operators

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

    The following are the Arithmetic Operators

    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 of Arithmetic Operators in C#

    using System;
    
    namespace Operators
    {
       class Arithmetic
       {
          static void Main(string[] args)
          {
             int a = 11;
             int b = 5;
             int result;
    
             result = a + b;
             Console.WriteLine("'+' operator, Result: {0}", result);
    
             result = a - b;
             Console.WriteLine("'-' operator, Result: {0}", result);
    
             result = a * b;
             Console.WriteLine("'*' operator, Result: {0}", result);
    
             result = a / b;
             Console.WriteLine("'/' operator, Result: {0}", result);
    
             result = a % b;
             Console.WriteLine("'%' operator, Result: {0}", result);
    
             Console.ReadLine();
          }
       }
    }

    Output:

    '+' operator, Result: 16
    '-' operator, Result: 6
    '*' operator, Result: 55
    '/' operator, Result: 2
    '%' operator, Result: 1

  • C# Operators

    Operators are the foundation of any programming language, the program is incomplete without the operators as we use them in all of our programs.

    Operators are the symbol that performs a specific mathematical or logical operation on operands.
    Example: Addition : 2 + 3, where 2 and 3 are the operands and + is the operator.

    Following are the types of Operators in C#.

    • Arithmetic Operators
    • Assignment Operators
    • Relational Operators
    • Logical Operators
    • Unary Operators
    • Bitwise Operators
    • Ternary or Conditional Operator
    • Miscellaneous Operators

    C# Arithmetic Operators

    Arithmetic Operators 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.

    Click Here for example of Arithmetic Operators operators.


    C# Assignment Operators

    These 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 = 5;
    
    //the value of b (10) is assigned to a
    int b = 10;
    int a = b;
    int a += 2; //a=a+2

    You can combine write in short version such as instead of writing, int a = a+5, you can write it as 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

    Click Here for example of Assignment Operators operators.


    C# Relational Operators

    These operators are used in a program to check the relationship between two operands and accordingly, it returns boolean values, true or false. These are used with loops and Decision-Making Statements during condition checking.

    List of relational operators in C#:

    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

    Click Here for example of Relational Operators operators.


    C# Logical Operators

    These operators are used to compute the logical operation in a program such as &&|| and !. They are used to evaluate the condition.

    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

    Click Here for example of Logical Operators operators.


    C# Unary Operators

    These operators are the Increment and Decrement Operators. 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.

    • 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.

    Click Here for example of Unary Operators operators.


    C# Bitwise Operators

    Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.

    You can see the truth table below.

    pqp & qp | qp ^ q~p
    000001
    010111
    111100
    100110

    Below are the list of Bitwise operators:

    OperatorsName of operators
    &Bitwise AND
    |Bitwise OR
    ^Bitwise XOR
    ~Bitwise complement
    <<Shift left
    >>Shift right

    Click Here for example of Bitwise Operators operators.


    C# Ternary or Conditional Operator (?:)

    It is a short-hand version of the if-else statement that operates on three operands. The ternary operator (or Conditional operator) returns a true or false after checking the condition.

    Syntax of ternary operator:

    //syntax
    condition ? expression1 : expression2;

    Explanation:

    • condition: It checks the condition for a true or false value.
    • expression1: If the condition is true expression1 is evaluated.
    • expression2: If the condition is false expression2 is evaluated.

    Example of Ternary Operator in C#

    using System;
    
    namespace Operator
    {
       class TernaryOperator
       {
          public static void Main(string[] args)
          {
             int num = 10;
             string result;
    
             result = (num % 2 == 0) ? "Even Number" : "Odd Number";
             Console.WriteLine("{0} is {1}", num, result);
          }
       }
    }

    Output:

    15 is Odd Number

    Miscellaneous Operators

    Apart from the above operators, there are various other operators used in C# programming and they are:

    sizeof()It returns the size of a variable, constant, array, etc. sizeof is a keyword in C#.
    Example:
    sizeof(int); // returns 4
    typeof()Returns the type of a class
    Example:
    typeof(StreamReader);

    &
    This is a pointer operator, used to point the address of a variable, or we can say that it represents the memory address of the operand to which it points.
    Example:
    &a;, This points to the actual address of the variable a.
    *This is also a pointer variable, Indirection Operator. It returns the value of the variable that it points to.
    isThis operator checks an object is of a certain type.
    Example:
    If(mercedes is Car) // checks if Mercedes is an object of the Car class.
    asThis operator cast without raising an exception
    Example:
    Object ob = new StringReader("World");
    StringReader r = ob as StringReader;

    Operator Precedence in C#

    In a program, there may be an expression that uses more than one operator, in such case operator precedence determines which is to be evaluated first and next.

    Let us take an example:

    int result = 10 + 5 * 10; 
    
    //Output:
    60

    The output of the above expression is 60 because the precedence of multiplication is higher than the addition. So first (5 * 10) is evaluated and then 10 is added to the result.

    The following shows the precedence and associativity of C# operators:

    Associativity refers to the direction of the operators to be evaluated first and next. It may be right to left or left to right.

    CategoryOperatorAssociativity
    Postfix() [] -> . ++ – –Left to right
    Unary+ – ! ~ ++ – – (type)* & sizeofRight to left
    Multiplicative* / %Left to right
    Additive+ –Right to left
    Shift<< >>Left to right
    Relational< <= > >=Left to right
    Equality== !=/td>Right to left
    Bitwise AND&Left to right
    Bitwise XOR^Left to right
    Bitwise OR|Right to left
    Logical AND&&Left to right
    Logical OR||Left to right
    Conditional?:Right to left
    Assignment= += -= *= /= %=>>= <<= &= ^= |=Right to left
    Comma,Left to right

  • 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# Program Structure

    Before we begin further in this tutorial, it is important to know the basic building of C# programming. You need to have the basic knowledge on what C# program structure contain of.

    C# Program Structure

    Let us check the basic program written in C#.

    using System;
    
    /* Hello World Program */
    namespace HelloWorldApplication 
    {
       public class HelloWorld 
       {
          static void Main(string[] args) 
          {
    
             Console.WriteLine("Hello World!");
          }
       }
    }

    After execution of the above program, following output will be displayed.

    Hello World!

    Now let us understand each of these parts individually:

    using System; This is first-line, “using” is a keyword in C# that is used to include the System namespace in the program. If System is included before in the program, then we do not need to specify a system for accessing the class of this namespace. In the above program, we use the Console without specifying the System.

    /* Hello World Program */: This is the comment section of the program. These lines are not included during execution but these are for the programmer to comment on the necessary section as required. It is considered to be good practice for coders. However, you can also use // for single line comment and /**/ is used for multiple line comment.

    namespace: Next is a namespace, It is the collection of classes that is we can create a class inside the namespace in order to maintain the classes in categories. We need to give that namespace name (above eg:- “HelloWorldApplication”).

    public class: public is one of the modifiers used in C#. Making the class public means that it can be accessed from outside the class. class in C# contains all the data and methods used in a program and multiple methods can be created inside the class (above example, Main() is the method inside HelloWorld class).

    Main: The main method is an entry point of the program when executed. The execution of the program starts from the Main method.

    Console.WriteLine("Hello World!"); The Console class is defined in the namespace as used on first line of the program and WriteLine is the method of the Console class that displays the message on the screen.

    {...}: This curly braces signifies the extent of the particular function. The blocks under the { } cannot be used outside the curly braces.


    Compilation and Execution of C# Program

    Go through the following step to compile and run the C# programs using the command-line.

    • First, open a text editor(eg notepad) on your computer and write your C# code.
    • Then, save the file as file_name.cs
    • Then open a command prompt and go to the directory where you have saved the file.
    • And on the command prompt type “csc file_name.cs” and press enter to compile your code. If there is no error then the command prompt takes you to the next line and the file_name.exe executable file will be created.
    • Type file_name to execute the program.
    • Then Hello world will be printed on the screen (considering the above code).

    C# Basic Syntax

    During the program, we use many programming components such as keywords, variables, member function, member variables, etc, which we will be studying in detail in further tutorial.

    You can also write the C# program in 4 different ways as shown below.

    1. Simple Syntax

    class HelloWorld  
    {  
      static void Main(string[] args)  
      {  
        System.Console.WriteLine("Hello World!");  
      }  
    }  

    2. Using System

    using System;
    
    class HelloWorld
    {
       static void Main(string[] args)
       {
          Console.WriteLine("Hello World!");
       }
    }  

    3. Using modifier (public)

    using System;
    
    public class HelloWorld
    {
       public static void Main(string[] args)
       {
          Console.WriteLine("Hello World!");
       }
    }

    4. Using namespace

    using System;
    
    /* Hello World Program */
    namespace HelloWorldApplication 
    {
       public class HelloWorld 
       {
          static void Main(string[] args) 
          {
    
             Console.WriteLine("Hello World!");
          }
       }
    }

    You can write C# program in any one of the above ways in a program according to your need and your comfortability.


  • C# Features

    C# is an Object0oriented programming having many features. Some of the main features are explained briefly below, point by point.

    What are the Features of C++ programming Language?

    • Simple and easy to use
    • Modern and General-purpose
    • Type safe (security)
    • Object-Oriented language
    • C# is Interoperability, Scalable and Updatable
    • Component-Oriented and Structured Programming Language
    • Rich in Library and Fast in Speed

    Details on some main features of C#

    Simple and easy to use

    Being a modern language, C# is simple and easy to use programming language. It inherits many features which makes it more suitable to use such as, it is mention above that it is a structured language that is it breaks the problems into parts making it easy to understand. Not only that but C# is also rich in Library providing various function to use.


    Modern and General-purpose

    C# was created keeping the mind on the current trend, making it powerful to use in every developer platform. The use of C# makes it suitable for building interoperable, scalable, robust applications and yet very powerful.


    Type safe (security)

    Well, there is always a question of safety and C# provides it. It can only access to those elements or memory space on which it has granted the permission to execute. The unsafe casting such as converting double to boolean is restricted, the initialization of data-types and array are checked along with the overflow of types.


    Object-Oriented language

    Like java, C# is also an object-oriented programming language. The use of objects divides the programs into modules making it simpler to use which is not possible in Procedure-Oriented programming language. In POP, code grows as project size increases.

    Unlike java, C# uses Structure that is structs that allow the primitive data-types to be used as objects. OOP supports the concept of Inheritance, Polymorphism, Interfaces, Data Encapsulation.


    C# is Interoperability, Scalable and Updatable

    Interoperability enables you to preserve and take advantage of existing investments in unmanaged code. This process gives the ability to C# to do any actions as the native C++ can do and provide native support for the COM and windows based applications.

    Scalable and updatable are automatic in C#. If we wish to update then we need to replace the old files with the new ones. No need for lining the other library.


    Component-Oriented and Structured Programming Language

    C# supports component-oriented programming through the concepts of properties, methods, events, and attributes (or metadata). It is a process of developing an application by mixing the already exists and new components.

    C# is a structured language that simply refers to the breaking down of the programs into modules or parts using function so that it becomes easy to use, understand and can be easily modified.


    Rich in Library and Fast in Speed

    It is also mentioned above that C# has a rich Library as it is based on the .NET framework that has a huge library. It consists of various inbuilt functions and classes that increase the speed of development.

    The speed of C# to compile and execute is fast that provide fast development of applications.

    Hope this article was helpful for the learner and keep visiting simple2code.com for more article on programming.


  • Sphenic Number in Java

    In this tutorial, we will start by learning what is Sphenic Number and write a Java Program to check for the Sphenic Number.

    Sphenic Number

    A Sphenic Number is a positive integer n which is a product of exactly three distinct prime numbers. Or we can say that n is a sphenic integer if n = a * b * c (a, b, and c are three distinct prime numbers and their product is equal to n).

    Example: 30, 42, 66, 70, 78, 102, 105, etc.

    Explanation:

    Input : 110
    Output : Yes
    Explanation : Factors of 110 are = 1, 2, 5, 10, 11, 22,55 and 110
                  Take the smallest three prime factors: 2, 5, 11
                   Product of these smallest prime factors:  2*5*11
                                                                                            = 110
                                                                                            = Input =110
                   Hence the number is Sphenic Number.

    Java Program to Check if the Number is Sphenic Number or not

    import java.util.*;
    
    public class SphenicNumberExample1
    {
       static boolean arr[] = new boolean[10000];
    
       static void findPrime()
       {
          Arrays.fill(arr, true);
    
          for (int p = 2; p * p < 10000; p++)
          {
             //if p is not changed, then it is a prime  
             if (arr[p])
             {
                for (int i = p * 2; i < 10000; i = i + p)
                   arr[i] = false;
             }
          }
       }
     
       //checks if the given number is sphenic or not  
       static int isSphenic(int N)
       {
          int[] arr1 = new int[8];
          int count = 0, j = 0;
    
          for (int i = 1; i <= N; i++)
          {
             if (N % i == 0 && count < 8)
             {
                //increments the count by 1      
                count++;
                arr1[j++] = i;
             }
          }
    
          if (count == 8 && (arr[arr1[1]] && arr[arr1[2]] && arr[arr1[3]]))
             return 1;
          return 0;
       }
    
       //main function
       public static void main(String args[])
       {
          int n, result;
    
          findPrime();
          Scanner sc = new Scanner(System.in);
    
          System.out.print("Enter a number: ");
          n = sc.nextInt();
    
          result = isSphenic(n);
    
          if (result == 1)
             System.out.print(n + " is a sphenic Number.");
          else
             System.out.print(n + " is not a sphenic Number.");
       }
    }

    Output:

    //First Execution
    Enter a number: 30
    30 is a sphenic Number.

    //Second Execution
    Enter a number: 165
    165 is a sphenic Number.


  • 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