Sunday, 21 August 2022

Increment & Decrement Operators

  • Increment (++) operator is used to increase the value of a variable by 1.

  • Decrement (--) operator is used to decrease the value of a variable by 1.

  • Both the operators are unary i.e. they only require one operand.

  • There are two forms in which ++ and - can be used:
    1.  Prefix
    2. Postfix

  • Prefix: In this form operator is written before the operand: ++a, --b.
  • Postfix: In this form operator is written after the operand: at+, b-.
  • If there is no assignment then prefix and postfix will give same result.
    Eg:




















In both cases a = 11 and b = 19


  • If there is assignment then prefix and postfix may give different result.





    x = 11 a = 11
    y = 21 b = 21

    x = 10 a = 11
    y = 20 b = 21



    Prefix


    int a =10, x;

    x=++a;

    It is calculated as a two step process:

    Step 1:a=a+1:// a will become 11

    Step 2:x=a;// x will become 11

    In case of prefix rule is:

    First increment/decrement is performed then assignment is performed.


    Postfix

    int a=10, x;

    x=a++;

    It is calculated as a two step process:


    Step 1:x=a;//
    x will become 10

    Step 2:a=a+1;//
    a will become 11

    In case of postfix rule is:

    First assignment is performed then 
    increment/decrement is performed.

    In case of following for loops both postfix & prefix will give same result:




     
    Both loops will print 1 to 5


    In case of printf functions result may vary:


    It will print a = 11
    It will print a = 10
    Finally a will be 11
    in both case.



    #codingmadeasy #codingmadeasy #clanguage #cprogramming #java #javaprogramming #datastructure #algorithms #complexity #coding #codeforfun #codinglife #coderlife #programming #program #computerscience #it #technology #ugc #gate #gate #nta #net

No comments:

Post a Comment