C# Assignment Operators Example

C# example for assignment operators: Here, we are writing a C# program to demonstrate example of all assignment operators. By IncludeHelp Last updated : April 15, 2023

Assignment Operators

Assignment operators (Assignment (=) and compound assignments (+=, -+, *=, /=, %=)) are used to assign the value or an expression's result to the left side variable, following are the set of assignment operators,

  1. "=" – it is used to assign value or an expression's result to the left side variable
  2. "+=" – it is used to add second operand to the existing operand's value and assigns it back (a+=b is equal to a=a+b)
  3. "-=" – it is used to subtract second operand from the existing operand's value and assigns it back (a-=b is equal to a=a-b)
  4. "/=" – it is used to divide second operand from the existing operand's value and assigns it back (a/=b is equal to a=a+b)
  5. "*=" – it is used to multiply second operand with the existing operand's value and assigns it back (a*=b is equal to a=a*b)
  6. "%=" – it is used to get the remainder by dividing second operand with the existing operand's value and assigns it back (a%=b is equal to a=a%b)

Example

    Input:
    int a = 10;
    int b = 3;

    //operations & outputs
    a = 100;    //value of a will be 100
    a += b;     //value of a will be 103
    a -= b;     //value of a will be 100
    a *= b;     //value of a will be 300
    a /= b;     //value of a will be 100
    a %= b;     //value of a will be 1

C# code to demonstrate the example of assignment operators

// C# program to demonstrate example of 
// assignment operators 

using System;
using System.IO;
using System.Text;

namespace IncludeHelp {
  class Test {
    // Main Method 
    static void Main(string[] args) {
      int a = 10;
      int b = 3;

      Console.WriteLine("a: {0}", a);
      a = 100; //assigment
      Console.WriteLine("a: {0}", a);
      a += b;
      Console.WriteLine("a: {0}", a);
      a -= b;
      Console.WriteLine("a: {0}", a);
      a *= b;
      Console.WriteLine("a: {0}", a);
      a /= b;
      Console.WriteLine("a: {0}", a);
      a %= b;
      Console.WriteLine("a: {0}", a);

      //hit ENTER to exit the program
      Console.ReadLine();
    }
  }
}

Output

a: 10
a: 100
a: 103
a: 100
a: 300
a: 100
a: 1

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.