Monday, February 4, 2013

Understand the ++ and -- operator

//Please don't copy-paste this program ; make your own implementation
#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    int a;
    a = 5;
    cout << ++a << endl; // pre-increment -- 6
    cout << --a << endl; // pre-decrement -- 4
    cout << a++ << endl; // post-incremenr -- 5
    cout << a-- << endl; // post-decrement -- 5
   
    cout << a++ << a++ << endl; // 5 -(+1)-> 6
   
    cout << a++ + a++ + a++ << endl ; // 5 -(+1)-> 6 -(+1)-> 7 = 18
   
    //This goes left-to-right
    cout << a++ + a++ + --a; // 5 -(+1)-> 6 -(+1)-> 7 (-1) -->6 =17
   
    // it goes right-to-left
    cout << a++ , a++ , a++;  //7, <-(+1)- 6, <-(+1)- 5
   
    //it goes 1st right-to-left and then left-to-right
    cout << a++ + a++ + a--, ++a; // 21,6
   
    printf ( "%d %d %d %d %d\n",x++, x--, ++x, --x, x++);  // 5 6 6 5 5
   
    //For Practice

    int b = 5, c = 5, i, j, j1;
    i = a++ + a++ + a++;               
    j = ++b + ++b + ++b;
    j1 = c++ + c++ + c--;
   
    printf ("\n value of i using printf:%d\n", i);
    cout << "\n Value of  i : " << i << endl
          << "\n Value of  j : " << j << endl
          << "\n Value of j1 : " << j1 << endl;
       
    printf("value of 1st print is: %d\n", 59);
    printf("value of 2nd print is: %c\n\n", 59);
}

-----------------------------------------------------------------------------------------------

//What is the output of this program
#include <stdio.h>
int main()
{
    int x=20,y=35;

    x=x++ + y++;

    y=++x + ++y;

    printf ( "%d, %d", x,y);
    return 0;
}

The output for your program is 57, 94.

Explanation:
x = 20, y = 35

x = x++ + y++ = 20 + 35 (x and y would be incremented after the addition) = 55
x++ -----> x = 55 + 1 = 56
y++ -----> y = 35 + 1 = 36

++x -----> x = 56 + 1 = 57 (x and y would be incremented
++y -----> y = 36 + 1 = 37 before the addition)
y = ++x + ++y = 57 + 37 = 94

Hence final values of x and y are 57 and 94 respectively. 


Understand this way:
d=x++; //the value of x is stored to d and d is increment by 1.x remains the same.d=20 x=21
printf ("%d %d",d,x);   // 20 21

x = x++;     
printf("%d",x);    //21

d = x++ + 1; 
x = x++ + 1;   
printf("%d %d");     //d=21 x=22
 

d=++x; //here increment is done first after that value is stored=x=21


For further detail click here.

No comments:

Post a Comment