a)

 #include<iostream.h>

void main()

{

int i=10;

cout<<i<<i++<<++i;

getch();

}

Explanation

The cout object works as a stack. The associativity is from right to left.

 

Here is the step-by-step explanation:

 

 

 

i=11

[++i

i=i+1]

 

 

 

i=11[postfix] i=i+1

i=11

 

i=12

i=11

i=11

 

If you are not sure about postfix and prefix expressions, let me explain it. There is no difference between i++ and ++i when they are given as separate statements. that is

i++;

Consider this:

 

A)

int i=10;

k=i++;

 

B)

int i=10;

k=++i;

 

In the first occasion, 10 is first stored in k and then k is incremented. It is equivalent to two separate statements.

k=i; i=i+1;

 

In the second occasion, i is incremented to 11 and afterwards it is stored in k. it is equivalent to two separate statements.

i=i+1;k=i;

 

The same rule applies when you give it in cout.

 

 Therefore the output is 12 11 11

 

 

b)

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int i=1,a=3;

i=a++;

cout<<i;

getch();

}

 

Explanation

As we have seen in the earlier program value of a gets stored in i and then a gets incremented.

i=a;a++;

Output:3

Note: The value stored in a doesn’t get printed. When it comes to output, give only the value that is given in cout.

 

 

c)

 

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int i=3, x;

x=i?i++ : ++i;

cout<<x;

getch();

}

 

 

Explanation:

If there is any check condition without any relational operator, it means that it’s being checked for a non-zero value.

 

if(i) is equivalent to if(i!=0)

 

The syntax of the ternary operator is

condition? True part: False part

The value stored in i is not equal to 0. therefore i++ is stored in x.

x=i;i++;

Output:3

 

 

d)

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int z, x=3, y=2;

z=--x + y++;

cout<<z;

getch();

}

Explanation: y is added with decremented x and then y is incremented.

z=2+2;y=3

output:4

 

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

char ch=’a’;

ch=(ch==’b’)?ch:’b’;

cout<<ch;

getch();

}

 

Explanation:

Ternary operator is used. If ch contains b ch is again stored in ch, else ‘b’ is stored. In either case ‘b’ is stored in ch.

 

Output: b

 

 

 

 

Hosted by www.Geocities.ws

1