Search This Blog

Thursday, 3 January 2013

What will be the output of the following program in c++?

What will be the output of the following program in c++?
when value of a is input as (i)6 , (ii)0:


int a, b=3 ;
cin >> a ;
if (a)
b=a++ -1;

cout<<"a="<<a<<endl ;
cout<<"b="<<b<<endl ;
--------------------------------------…
I want to know to know how the result came?
so please explain me.

Answer:
if (a), when a is either positive or negative as int x = -1;
if (x)
cout << "R";// This will be printed => Condition is true.
When anything within brackets is +ve or negative in if's brackets condition is considered as true.
Similarly if within the bracket of if 0 comes, the condition is False i.e.
if (0)
cout << "R"; // R will not be printed.

In your program, when user enters 6, a number other than ZERO, condition becomes true and the thing with in the body of if is executed => b's value will be replaced by (6-1) = 5. (if user enters 6 as 'a')
When user enters 0, the statement within the if body will not be executed, and value stored in b will remain unchanged (i.e. b = 3).

(i) a = 6 + 1 = 7 // 6 + 1 because it was incremented.
    b = 6 - 1 = 5

(ii) a = 0 
     b = 3.


Question:
1. Which of the following is true?
A. 1
B. 66
C. .1
D. -1
E. All of the above

Wednesday, 2 January 2013

What is the difference between a pointer and an array?

What is the difference between a pointer and an array?

Pointers are variable. You point to one variable, and after sometime you start pointing to another variable with the same pointer.
Example:
int x = 1;
int *p = &x;
//in the next line you can say
*p = &b; // if b has been initialized.

Array name is the address to the first index of array. Array name is a CONSTANT Pointer => You cannot do a = a + 1; if a is an array. It will generate an error since it always point to same location.
When we do for example cout << *(a+1); (a is arraY) We give an offset and elements at 2nd index is printed. a still points to the first location.