In: Computer Science
Assume m=5 and n=2 in each case. Answer the questions..
What are the output of the codes:
1) m*=n++; cout<<(--m)++<<","<<--n<<'\n';
2) Values of m and n after execution of codes: m*=n++;
3) What values of m, n will be after the statement: m+=--n; ?
4) What values of m and n will be after the statement: m*=n; ?
5) What values of m and n will be after the statement: m /=++n; ?
The output of the following programs are as follows:
1. 9,2
It is beacause initially the value of m = 5 and then m = m*n++
-> m = 5*2++
= 10
This is use then increment operator as ++ comes after the operand. Now, we execute the statement --m which means that decrement and then use. So, the current value of m is 10 which will be decremented to 9 due to the operator --m.
Regarding the second output after 9 that is 2. It comes because --n is in the pattern "--n", Now in the first statement that is
m*=n++, the value of n is 2 because it is post increment use and increment. Now, after this --n comes. As a result, the value of n will be decremented and then it will be suddenly decremented again due to pre-increment operator.
In other words, m*=n++;
The value of m is 10 and n is 2
cout<<(--m)++; The value of m is 9 (pre increment ie, increment comes first).
Also, cout<<--n<<'\n'; The value of n is 2 (because now n is incremented due to n++ in the statement [ m*=n++] to 3 and again decremented to 2 [due to --n] in the statement.
2. values of m and n after execution of codes m*=n++ is
m = 5*2 = 10
because initial value of m is 5 and n will not increment and remain as 2 in this step .
The value of n is 2 itself.
3. The value of m and n after the statement m+=--n; is as follows:
Let us say the current (initial value of m and n is 5 and 2 respectively)
m = m+--n;
= 5+(--2)
= 5 + 1
= 6 ,
The value of n is n=n-1=2-1=1
m=6 and n=1
because the value of n will be decremented ( decrement and use pre increment strategy).
4. The value of m and n after the statement m*=n; is as follows:
Let us say the initial values of m and n are 5 and 2 respectively.
m = m*n;
= 5*2
= 10
n = 2
m = 10 and n =2
5. The values of m and n after statement m /=++n is as follows:
Let us say the initial values of m=5 and n=2. Then,
m = m/++n
= 5/ (++2)
= 5/ (2+1) /* Pre Increment ie increment and then use */
= 5/3
= 1.6 , but
if m is declared as int then the value of m is 1
if m is declared as float, then the value of m is 1.6
However, the value of n is 3 ( n=n+1).
In general, questions from 1 to 5 is based on the concepts of post and pre increment/decrement operators.
The concept is this, in case of pre increment/decrement operator, initially the operand will be performed by the operation and the we will use it. As far as post increment/dcrement is concerned, the operand will be used first and then only increment or decrement will be done on the operand. You just understand these concepts.