Tuesday 28 February 2017

C Programming Questions with Explanation

Q:: What will be the output::
void main()
{
          int x;
          scanf("%d",&x);
          if((x)&&(!x))
               printf("Hello");
          if((x)||(!x))
               printf("World");
}
(A) HelloWorld                                                       (B) World
(C)Hello                                                                  (D) Depends upon value of 'x'

Ans:: (B)
Explanation::

In C programming the logical not operator performs the complement operation i.e. it converts a condition from true to false or false to true. In other words it converts a non-zero number to zero and zero to one.
So the first 'if' will always be false and the second 'if' always be true.

Sunday 19 February 2017

C Programming Questions with Explanation

The following statement ::
     
               printf("%d",++5);
will print:

a)5  b) 6  c) error  d)garbage

Answer:: (C)

Explanation::

The statement will be expanded like
         5=5+1;
i.e. a constant on left side of expression which is not allowed in 'C' hence it will generate error.

Saturday 18 February 2017

C Programming Questions with Explanation

Q:: What will the output of following?

           for(i=0;i<10;++i)
                   printf("%d",i&1);
(a)0101010101 (b)0111111111
(c)0000000000 (d)1111111111

Answer :: (A)
Explanation::

Binary representation of 1 is 0000000000000001 in 16 bit

In first iteration i=0

     i=0000000000000000
    1=0000000000000001
i&1=0000000000000000=(0)

In second iteration i=1

     i=0000000000000001
    1=0000000000000001
i&1=0000000000000001=(1)

In third iteration i=2

     i=0000000000000000
    1=0000000000000010
i&1=0000000000000000=(0)
In fourth iteration i=3

     i=0000000000000011
    1=0000000000000001
i&1=0000000000000001=(1)

So it will produce 0 when 'i' is even
and  '1' if 'i' is odd
Output will be 0101010101

C Programming Questions with Explanation

Q:: What will be the output for following loop :->

for(putchar('c');putchar('a');putchar('r'))
{
                putchar('t');
}

 (a)error             (B)cartrt
(C)catrat            (D)catratratrat...

As per for loop execute

for(1. Initialization;2.Condition Check; 3. Iteration Variable change)

Now as per given question
1. Initialization is given by putchar('c)
2. Condition Check by putchar('a')
3. Iteration by putchar('r')

In for loop statement putchar('t') is there

Also sequence is 
1. Initialization only once putchar('c')
2. Condition check putchar('a')
3. Statement putchar('t')
4. Iteration putchar('r')
2. putchar('a')
3. putchar('t')
4. putchar('r')
2. putchar('a')
3. putchar('t')
.
.
.
and so on so result will catratratrat.... Infinite times