Search here

Custom Search

Follow by Email

5/28/2012

Part 4: FRP Dumps | C Puzzle | C++ Puzzle | DataStructure Puzzle



PART 1          PART 2          PART 3           PART 4            PART 5            PART 6            PART 7



130)     main()
{
while (strcmp(“some”,”some\0”))
printf(“Strings are not equal\n”);
            }
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop.





131)     main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2))
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.

132)     main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:                       Compiler Error: Lvalue required.
Explanation:
As we know that increment operators return rvalues and  hence it cannot appear on the left hand side of an assignment operation.

133)     void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.
           
134)     void main()
{
static int i;
while(i<=10)
(i>2)?i++:i--;
            printf(“%d”, i);
}
Answer:                       32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.

135)     main()
{
                        int i=10,j=20;
            j = i, j?(i,j)?i:j:j;
                        printf("%d %d",i,j);
}

Answer:
10 10
Explanation:
                        The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the question can be written as:
                        if(i,j)
                             {
if(i,j)
                             j = i;
                        else
                            j = j;                        
                        }
               else
                        j = j;                


136)     1. const char *a;
2. char* const a;
3. char const *a;
-Differentiate the above declarations.

Answer:
1. 'const' applies to char * rather than 'a' ( pointer to a constant char )
            *a='F'       : illegal
                                    a="Hi"       : legal

2. 'const' applies to 'a'  rather than to the value of a (constant pointer to char )
            *a='F'       : legal
            a="Hi"       : illegal

3. Same as 1.

137)     main()
{
                        int i=5,j=10;
            i=i&=j&&10;
                        printf("%d %d",i,j);
}

Answer:1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result.

138)     main()
{
                        int i=4,j=7;
            j = j || i++ && printf("YOU CAN");
                        printf("%d %d", i, j);
}

Answer:
4 1
Explanation:
The boolean expression needs to be evaluated only till the truth value of the expression is not known. j is not equal to zero itself means that the expression’s truth value is 1. Because it is followed by || and true || (anything) => true where (anything) will not be evaluated. So the remaining expression is not evaluated and so the value of i remains the same.
Similarly when && operator is involved in an expression, when any of the operands become false, the whole expression’s truth value becomes false and hence the remaining expression will not be evaluated.    
            false && (anything) => false where (anything) will not be evaluated.

139)     main()
{
                        register int a=2;
            printf("Address of a = %d",&a);
                        printf("Value of a   = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
                         & (address of ) operator cannot be applied on register variables.
           
140)     main()
{
                        float i=1.5;
            switch(i)
                        {
                        case 1: printf("1");
                                    case 2: printf("2");
                                    default : printf("0");
            }
}
Answer:
Compiler Error: switch expression not integral
Explanation:
                        Switch statements can be applied only to integral types.

141)     main()
{         
                        extern i;
            printf("%d\n",i);
                        {
                                    int i=20;
                        printf("%d\n",i);
                        }
}
Answer: Linker Error : Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in resolving it.

142)     main()
{
                        int a=2,*f1,*f2;
            f1=f2=&a;
                        *f2+=*f2+=a+=2.5;
            printf("\n%d %d %d",a,*f1,*f2);
}
Answer:
16 16 16
Explanation:
f1 and f2 both refer to the same memory location a. So changes through f1 and f2 ultimately affects only the value of a.
           
143)     main()
{
                        char *p="GOOD";
            char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p), strlen(p));
            printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
}
Answer:
                        sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
            sizeof(a) = 5, strlen(a) = 4
Explanation:
                        sizeof(p) => sizeof(char*) => 2
            sizeof(*p) => sizeof(char) => 1
                        Similarly,
            sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array and it is not the same as the sizeof the pointer variable. Here the sizeof(a) where a is the character array and the size of the array is 5 because the space necessary for the terminating NULL character should also be taken into account.

144)     #define DIM( array, type) sizeof(array)/sizeof(type)
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr, int));   
}
Answer:
10  
Explanation:
The size  of integer array of 10 elements is 10 * sizeof(int). The macro expands to sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10.

145)     int DIM(int array[])
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));   
}
Answer:
1  
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int) that happens to be equal in this case.

146)     main()
{
            static int a[3][3]={1,2,3,4,5,6,7,8,9};
            int i,j;
            static *p[]={a,a+1,a+2};
                        for(i=0;i<3;i++)
            {
                                    for(j=0;j<3;j++)
                                    printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
                                    *(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
                        }
}
Answer:
                                    1       1       1       1
                                    2       4       2       4
                        3       7       3       7
                                    4       2       4       2
                                    5       5       5       5
                        6       8       6       8
                                    7       3       7       3
                                    8       6       8       6
                        9       9       9       9
Explanation:
                        *(*(p+i)+j) is equivalent to p[i][j].

147)     main()
{
                        void swap();
            int x=10,y=8;    
                        swap(&x,&y);
            printf("x=%d y=%d",x,y);
}

void swap(int *a, int *b)
{
   *a ^= *b,  *b ^= *a, *a ^= *b;
}         
Answer:
x=10 y=8
Explanation:
Using ^ like this is a way to swap two variables without using a temporary variable and that too in a single statement.
Inside main(), void swap(); means that swap is a function that may take any number of arguments (not no arguments) and returns nothing. So this doesn’t issue a compiler error by the call swap(&x,&y); that has two arguments.
This convention is historically due to pre-ANSI style (referred to as Kernighan and Ritchie style) style of function declaration. In that style, the swap function will be defined as follows,
void swap()
int *a, int *b
{
   *a ^= *b,  *b ^= *a, *a ^= *b;
}
where the arguments follow the (). So naturally the declaration for swap will look like, void swap() which means the swap can take any number of arguments.

148)     main()
{
                        int i = 257;
            int *iPtr = &i;
                        printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}
Answer:
                        1 1
Explanation:
The integer value 257 is stored in the memory as, 00000001 00000001, so the individual bytes are taken by casting it to char * and get printed.

149)     main()
{
                        int i = 258;
            int *iPtr = &i;
                        printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
}         
Answer:
                        2 1
Explanation:
The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are ‘small-endian’ machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.  

150)     main()
{
                        int i=300;
            char *ptr = &i;
                        *++ptr=2;
            printf("%d",i);
}
Answer:
556
Explanation:
The integer value 300  in binary notation is: 00000001 00101100. It is  stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it  is  00000010 00101100 => 556.

151)     #include <stdio.h>
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
                  least = (*ptr<least ) ?*ptr :least;
printf("%d",least);
}
Answer:
0
Explanation:   
After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.

152)     Declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Answer:
                        (char*(*)( )) (*ptr[N])( );

153)     main()
{    struct student
{
char name[30];
struct date dob;
}stud;
struct date
        { 
         int day,month,year;
         };
     scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month,      &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Inside the struct definition of ‘student’ the member of type struct date is given. The compiler doesn’t have the definition of date structure (forward  reference is not allowed in C in this case) so it issues an error.

154)     main()
{
struct date;
struct student
{
char name[30];
struct date dob;
}stud;
struct date
            {
         int day,month,year;
 };
scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Only declaration of struct date is available inside the structure definition of ‘student’ but to have a variable of type struct date the definition of the structure is required.

155)     There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?
void main()
{
struct student
{         
char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
 {
                        fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}
Explanation:
fread reads 10 records and prints the names successfully. It will return EOF only when fread tries to read another record and fails reading EOF (and returning EOF). So it prints the last record again. After this only the condition feof(fp) becomes false, hence comes out of the while loop.

156)     Is there any difference between the two declarations,
1.      int foo(int *arr[]) and
2.      int foo(int *arr[2])
Answer:
No
Explanation:
Functions can only pass pointers and not arrays. The numbers that are allowed inside the [] is just for more readability. So there is no difference between the two declarations.


157)     What is the subtle error in the following code segment?
void fun(int n, int arr[])
{
int *p=0;
int i=0;
while(i++<n)
                        p = &arr[i];
*p = 0;
}
Answer & Explanation:
If the body of the loop never executes p is assigned no address. So p remains NULL where *p =0 may result in problem (may rise to runtime error “NULL pointer assignment” and terminate the program).    

158)     What is wrong with the following code? 
int *foo()
{
int *s = malloc(sizeof(int)100);
assert(s != NULL);
return s;
}
Answer & Explanation:
assert macro should be used for debugging and finding out bugs. The check s != NULL is for error/exception handling and for that assert shouldn’t be used. A plain if and the corresponding remedy statement has to be given.

159)     What is the hidden bug with the following  statement?
assert(val++ != 0);
Answer & Explanation:
Assert macro is used for debugging and removed in release version. In assert, the experssion involves side-effects. So the behavior of the code becomes different in case of debug version and the release version thus leading to a subtle bug.
Rule to Remember:
Don’t use expressions that have side-effects in assert statements. 




160)     void main()
{
int *i = 0x400;  // i points to the address 400
*i = 0;              // set the value of memory location pointed by i;
}
Answer:
Undefined behavior
Explanation:
The second statement results in undefined behavior because it points to some location whose value may not be available for modification.  This type of pointer in which the non-availability of the implementation of the referenced location is known as 'incomplete type'.

161)     #define assert(cond) if(!(cond)) \
  (fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
 __FILE__,__LINE__), abort())

void main()
{
int i = 10;
if(i==0)           
    assert(i < 100);
else
    printf("This statement becomes else for if in assert macro");
}
Answer:
No output
Explanation:
The else part in which the printf is there becomes the else for if in the assert macro. Hence nothing is printed.
The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s, file %s, line %d \n",#cond, __FILE__,__LINE__), abort()))

Note:
However this problem of “matching with nearest else” cannot be solved by the usual method of placing the if statement inside a block like this,
#define assert(cond) { \
if(!(cond)) \
  (fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
 __FILE__,__LINE__), abort()) \
}

162)     Is the following code legal?
struct a
    {        int x;
 struct a b;
    }
Answer:                       No
Explanation:
Is it not legal for a structure to contain a member that is of the same
type as in this case. Because this will cause the structure declaration to be recursive without end.

163)     Is the following code legal?
struct a
    {
int x;
            struct a *b;
    }
Answer:
Yes.
Explanation:
*b is a pointer to type struct a and so is legal. The compiler knows, the size of the pointer to a structure even before the size of the structure
is determined(as you know the pointer to any type is of same size). This type of structures is known as ‘self-referencing’ structure.

164)     Is the following code legal?
typedef struct a
    {
int x;
 aType *b;
    }aType
Answer:
                        No
Explanation:
The typename aType is not known at the point of declaring the structure (forward references are not made for typedefs).

165)     Is the following code legal?
typedef struct a aType;
struct a
{
int x;
aType *b;
};
Answer:
            Yes
Explanation:
The typename aType is known at the point of declaring the structure, because it is already typedefined.

166)     Is the following code legal?
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
      aType *b;
              };
}
Answer:
                        No
Explanation:
                        When the declaration,
typedef struct a aType;
is encountered body of struct a is not known. This is known as ‘incomplete types’.

167)     void main()
{
printf(“sizeof (void *) = %d \n“, sizeof( void *));
            printf(“sizeof (int *)    = %d \n”, sizeof(int *));
            printf(“sizeof (double *)  = %d \n”, sizeof(double *));
            printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *));
            }
Answer            :
sizeof (void *) = 2
sizeof (int *)    = 2
sizeof (double *)  =  2
sizeof(struct unknown *) =  2
Explanation: The pointer to any type is of same size.

168)     char inputString[100] = {0};
To get string input from the keyboard which one of the following is better?
            1) gets(inputString)
            2) fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
The second one is better because gets(inputString) doesn't know the size of the string passed and so, if a very big input (here, more than 100 chars) the charactes will be written past the input string. When fgets is used with stdin performs the same operation as gets but is safe.

169)     Which version do you prefer of the following two,
1) printf(“%s”,str);      // or the more curt one
2) printf(str);
Answer & Explanation:
Prefer the first one. If the str contains any  format characters like %d then it will result in a subtle bug.
170)     void main()
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);
}         
Answer:
Compiler Error: “Unexpected end of file in comment started in line 5”.
Explanation:
The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
int k = *ip/ *jp;           
// give space explicity separating / and *
//or
int k = *ip/(*jp);
// put braces to force the intention 
will solve the problem. 

171)     void main()
{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c   %d \n“, ch, ch);
}
Answer:
            Implementaion dependent
Explanation:
The char type may be signed or unsigned by default. If it is signed then ch++ is executed after ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.

172)     Is this code legal?
int *ptr;
ptr = (int *) 0x400;
Answer:
                        Yes
Explanation:
The pointer ptr will point at the integer in the memory location 0x400.
173)     main()
{           char a[4]="HELLO";
printf("%s",a);
}         
Answer:
                        Compiler error: Too many initializers
Explanation:
The array a is of size 4 but the string constant requires 6 bytes to get stored.

174)     main()
{         char a[4]="HELL";
printf("%s",a);
}
Answer:
                        HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string “HELL” and doesnt have enough space to store the terminating null character. So it prints the HELL correctly and continues to print garbage values till it    accidentally comes across a NULL character.

175)     main()
{
                        int a=10,*j;
            void *k;
                        j=k=&a;
            j++; 
                        k++;
            printf("\n %u %u ",j,k);
}
Answer:
                        Compiler error: Cannot increment a void pointer
Explanation:
Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.

176)     main()
                        {
                                    extern int i;
                        {          int i=20;
                         {        
                           const volatile unsigned i=30; printf("%d",i);
                         }
                        printf("%d",i);
                        }
                          printf("%d",i);
            }         
            int i;

177)     Printf can be implemented by using  __________ list.
Answer:
                        Variable length argument lists
178) char *someFun()
            {
            char *temp = “string constant";
            return temp;
            }
            int main()
            {
            puts(someFun());
            }
Answer:
            string constant
Explanation:
            The program suffers no problem and gives the output correctly because the character constants are stored in code/data area and not allocated in stack, so this doesn’t lead to dangling pointers.

179)     char *someFun1()
            {
            char temp[ ] = “string";
            return temp;
            }
            char *someFun2()
            {
            char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
            return temp;
            }
            int main()
            {
            puts(someFun1());
            puts(someFun2());
            }
Answer:
            Garbage values.
Explanation:
            Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.







C++ Aptitude and OOPS


C++ Aptitude and OOPS

Note : All the programs are tested under Turbo C++ 3.0, 4.5 and Microsoft VC++ 6.0 compilers. 
It is assumed that,
Ø       Programs run under Windows environment,
Ø       The underlying machine is an x86 based system,
Ø       Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).

1) class Sample
{
public:
        int *ptr;
        Sample(int i)
        {
        ptr = new int(i);
        }
        ~Sample()
        {
        delete ptr;
        }
        void PrintVal()
        {
        cout << "The value is " << *ptr;
        }
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
}
int main()
{
Sample s1= 10;
SomeFunc(s1);
s1.PrintVal();
}
Answer:
Say i am in someFunc
Null pointer assignment(Run-time error)

Explanation:
As the object is passed by value to SomeFunc  the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr  that has been freed.The solution is to pass the Sample object  by reference to SomeFunc:

void SomeFunc(Sample &x)
{
cout << "Say i am in someFunc " << endl;
}
because when we pass objects by refernece that object is not destroyed. while returning from the function.

2)      Which is the parameter that is added to every non-static member function when it is called?
Answer:
            ‘this’ pointer

3) class base
        {
        public:
        int bval;
        base(){ bval=0;}
        };

class deri:public base
        {
        public:
        int dval;
        deri(){ dval=1;}
        };
void SomeFunc(base *arr,int size)
{
for(int i=0; i<size; i++,arr++)
        cout<<arr->bval;
cout<<endl;
}

int main()
{
base BaseArr[5];
SomeFunc(BaseArr,5);
deri DeriArr[5];
SomeFunc(DeriArr,5);
}

Answer:
 00000
 01010
Explanation:  
The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ).

4) class base
        {
        public:
            void baseFun(){ cout<<"from base"<<endl;}
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<<endl;}
        };
void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from base
Explanation:
            As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called.

5) class base
        {
        public:
            virtual void baseFun(){ cout<<"from base"<<endl;}
        };
 class deri:public base
        {
        public:
            void baseFun(){ cout<< "from derived"<<endl;}
        };

void SomeFunc(base *baseObj)
{
        baseObj->baseFun();
}
int main()
{
base baseObject;
SomeFunc(&baseObject);
deri deriObject;
SomeFunc(&deriObject);
}
Answer:
            from base
            from derived
Explanation:
            Remember that baseFunc is a virtual function. That means that it supports run-time polymorphism. So the function corresponding to the derived class object is called.
           

void main()
{
            int a, *pa, &ra;
            pa = &a;
            ra = a;
            cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}
/*
Answer :
            Compiler Error: 'ra',reference must be initialized
Explanation :
            Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.
*/

const int size = 5;
void print(int *ptr)
{
            cout<<ptr[0];
}

void print(int ptr[size])
{
            cout<<ptr[0];
}

void main()
{
            int a[size] = {1,2,3,4,5};
            int *b = new int(size);
            print(a);
            print(b);
}
/*
Answer:
            Compiler Error : function 'void print(int *)' already has a body

Explanation:
            Arrays cannot be passed to functions, only pointers (for arrays, base addresses)
can be passed. So the arguments int *ptr and int prt[size] have no difference 
as function arguments. In other words, both the functoins have the same signature and
so cannot be overloaded.
*/

class some{
public:
            ~some()
            {
                        cout<<"some's destructor"<<endl;
            }
};

void main()
{
            some s;
            s.~some();
}
/*
Answer:
            some's destructor
            some's destructor
Explanation:
            Destructors can be called explicitly. Here 's.~some()' explicitly calls the
destructor of 's'. When main() returns, destructor of s is called again,
hence the result.
*/

#include <iostream.h>

class fig2d
{
            int dim1;
            int dim2;

public:
            fig2d() { dim1=5; dim2=6;}

            virtual void operator<<(ostream & rhs);
};

void fig2d::operator<<(ostream &rhs)
{
            rhs <<this->dim1<<" "<<this->dim2<<" ";
}

/*class fig3d : public fig2d
{
            int dim3;
public:
            fig3d() { dim3=7;}
            virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
            fig2d::operator <<(rhs);
            rhs<<this->dim3;
}
*/

void main()
{
            fig2d obj1;
//          fig3d obj2;

            obj1 << cout;
//          obj2 << cout;
}
/*
Answer :
            5 6
Explanation:
            In this program, the << operator is overloaded with ostream as argument.
This enables the 'cout' to be present at the right-hand-side. Normally, 'cout'
is implemented as global function, but it doesn't mean that 'cout' is not possible
to be overloaded as member function.
    Overloading << as virtual member function becomes handy when the class in which
it is overloaded is inherited, and this becomes available to be overrided. This is as opposed
to global friend functions, where friend's are not inherited.
*/

class opOverload{
public:
            bool operator==(opOverload temp);
};

bool opOverload::operator==(opOverload temp){
            if(*this  == temp ){
                        cout<<"The both are same objects\n";
                        return true;
            }
            else{
                        cout<<"The both are different\n";
                        return false;
            }
}

void main(){
            opOverload a1, a2;
            a1= =a2;
}

Answer :
            Runtime Error: Stack Overflow
Explanation :
            Just like normal functions, operator functions can be called recursively. This program just illustrates that point, by calling the operator == function recursively, leading to an infinite loop.


class complex{
            double re;
            double im;
public:
            complex() : re(1),im(0.5) {}
            bool operator==(complex &rhs);
            operator int(){}
};

bool complex::operator == (complex &rhs){
            if((this->re == rhs.re) && (this->im == rhs.im))
                        return true;
            else
                        return false;
}

int main(){
            complex  c1;
            cout<<  c1;
}

Answer : Garbage value

Explanation:
            The programmer wishes to print the complex object using output
re-direction operator,which he has not defined for his lass.But the compiler instead of giving an error sees the conversion function
and converts the user defined object to standard object and prints
some garbage value.


class complex{
            double re;
            double im;
public:
            complex() : re(0),im(0) {}
            complex(double n) { re=n,im=n;};
            complex(int m,int n) { re=m,im=n;}
            void print() { cout<<re; cout<<im;}  
};

void main(){
            complex c3;
            double i=5;
            c3 = i;
            c3.print();
}

Answer:
            5,5
Explanation:
            Though no operator= function taking complex, double is defined, the double on the rhs is converted into a temporary object using the single argument constructor taking double and assigned to the lvalue.


void main()
{
            int a, *pa, &ra;
            pa = &a;
            ra = a;
            cout <<"a="<<a <<"*pa="<<*pa <<"ra"<<ra ;
}

Answer :
            Compiler Error: 'ra',reference must be initialized
Explanation :
            Pointers are different from references. One of the main
differences is that the pointers can be both initialized and assigned,
whereas references can only be initialized. So this code issues an error.

Try it Yourself

1) Determine the output of the 'C++' Codelet.          
            class base
            { 
            public :
                        out()
                        {
                                    cout<<"base "; 
                        } 
            };
            class deri{
            public : out()
            {
            cout<<"deri ";
            }  
            };
            void main()
            {          deri dp[3];
                        base *bp = (base*)dp;
                        for (int i=0; i<3;i++)
                        (bp++)->out();
            }

2)      Justify the use of virtual constructors and destructors in C++.

3)      Each C++ object possesses the 4 member fns,(which can be declared by the programmer explicitly or by the implementation if they are not available). What are those 4 functions?

4)       What is wrong with this class declaration?
            class something
            {
                        char *str;
                        public:
                           something(){
                           st = new char[10]; }
                          ~something()
                          {
                                    delete str;
                          }
             };

5) Inheritance is also known as -------- relationship. Containership as   ________ relationship.

6)  When is it necessary to use member-wise initialization list  (also known as header initialization list) in C++?

7) Which is the only operator in C++ which can be overloaded but NOT inherited.

8) Is there anything wrong with this C++ class declaration?
            class temp
            {
              int value1;
              mutable int value2;
              public :
                        void fun(int val)
                        const{
                        ((temp*) this)->value1 = 10;
                        value2 = 10;
                        }          };


1.  What is a modifier?
Answer:
          A modifier, also called a modifying function is a member function that changes the value of at least one data member. In other words, an operation that modifies the state of an object. Modifiers are also known as ‘mutators’.

2.  What is an accessor?
Answer:
          An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

3.   Differentiate between a template class and class template.
Answer:
Template class:
A generic definition or a parameterized class not instantiated until the client provides the needed information. It’s jargon for plain templates.
Class template:
A class template specifies how individual classes can be constructed much like the way a class specifies how individual objects can be constructed. It’s jargon for plain classes.

4.   When does a name clash occur?
Answer:
            A name clash occurs when a name is defined in more than one place. For example., two different class libraries could give two different classes the same name. If you try to use many class libraries at the same time, there is a fair chance that you will be unable to compile or link the program because of name clashes.

5.   Define namespace.
Answer: 
            It is a feature in c++ to minimize name collisions in the global name space. This namespace keyword assigns a distinct name to a library that allows other libraries to use the same identifier names without creating any name collisions. Furthermore, the compiler uses the namespace signature for differentiating the definitions.

6.   What is the use of ‘using’ declaration.
Answer:
            A using declaration makes it possible to use a name from a namespace without the scope operator.

7.   What is an Iterator class?
Answer:  
            A class that is used to traverse through the objects maintained by a container class. There are five categories of iterators:           
Ø        input iterators,
Ø       output iterators,
Ø       forward iterators,
Ø       bidirectional iterators,
Ø        random access.
An iterator is an entity that gives access to the contents of a container object without violating encapsulation constraints. Access to the contents is granted on a one-at-a-time basis in order. The order can be storage order (as in lists and queues) or some arbitrary order (as in array indices) or according to some ordering relation (as in an ordered binary tree). The iterator is a construct, which provides an interface that, when called, yields either the next element in the container, or some value denoting the fact that there are no more elements to examine. Iterators hide the details of access to and update of the elements of a container class.
The simplest and safest iterators are those that permit read-only access to the contents of a container class. The following code fragment shows how an iterator might appear in code:
           cont_iter:=new cont_iterator();
           x:=cont_iter.next();
           while x/=none do
                 ...
                 s(x);
                 ...
                 x:=cont_iter.next();
          end;
         In this example, cont_iter is the name of the iterator. It is created on the first line by instantiation of cont_iterator class, an iterator class defined to iterate over some container class, cont. Succesive elements from the container are carried to x. The loop terminates when x is bound to some empty value. (Here, none)In the middle of the loop, there is s(x) an operation on x, the current element from the container. The next element of the container is obtained at the bottom of the loop.

9.   List out some of the OODBMS available.
Answer:
Ø           GEMSTONE/OPAL of Gemstone systems.
Ø           ONTOS of Ontos.
Ø           Objectivity of  Objectivity inc.
Ø           Versant of Versant object technology.
Ø            Object store of Object Design.
Ø            ARDENT of ARDENT software.
Ø            POET of POET software.

10.   List out some of the object-oriented methodologies.
Answer:
Ø            Object Oriented Development  (OOD) (Booch 1991,1994).
Ø            Object Oriented Analysis and Design  (OOA/D) (Coad and Yourdon 1991).
Ø            Object Modelling Techniques  (OMT)  (Rumbaugh 1991).
Ø            Object Oriented Software Engineering  (Objectory) (Jacobson 1992).
Ø            Object Oriented Analysis  (OOA) (Shlaer and Mellor 1992).
Ø            The Fusion Method  (Coleman 1991).

11.   What is an incomplete type?
Answer:
            Incomplete types refers to pointers in which there is non availability of the implementation of the referenced location or it points to some location whose value is not available for modification.
Example:
                 int *i=0x400  // i points to address 400
                *i=0;        //set the value of memory location pointed by i.
Incomplete types are otherwise called uninitialized pointers.

12.   What is a dangling pointer?
Answer:
A dangling pointer arises when you use the address of an object after its lifetime is over.
This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

13.   Differentiate between the message and method.
Answer:
          Message                                                                   Method
Objects communicate by sending messages     Provides response to a message.
to each other.
A message is sent to invoke a method.             It is an implementation of an operation.

14.   What is an adaptor class or Wrapper class?
Answer:
A class that has no functionality of its own. Its member functions hide the use of a third party software component or an object with the non-compatible interface or a non- object- oriented implementation.

15.   What is a Null object?
Answer:
It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

16.   What is class invariant?
Answer:
A class invariant is a condition that defines all valid states for an object. It is a logical condition to ensure the correct working of a class. Class invariants must hold when an object is created, and they must be preserved under all operations of the class. In particular all class invariants are both preconditions and post-conditions for all operations or member functions of the class.

17.   What do you mean by Stack unwinding?
Answer:
It is a process during exception handling when the destructor is called for all local objects between the place where the exception was thrown and where it is caught.
              
18.   Define precondition and post-condition to a member function.
Answer:
Precondition:
            A precondition is a condition that must be true on entry to a member function. A class is used correctly if preconditions are never false. An operation is not responsible for doing anything sensible if its precondition fails to hold.
For example, the interface invariants of stack class say nothing about pushing yet another element on a stack that is already full. We say that isful() is a precondition of the push operation.

Post-condition:
            A post-condition is a condition that must be true on exit from a member function if the precondition was valid on entry to that function. A class is implemented correctly if post-conditions are never false.
For example, after pushing an element on the stack, we know that isempty() must necessarily hold. This is a post-condition of the push operation.

19.   What are the conditions that have to be met for a condition to be an invariant of the class?
Answer:
Ø       The condition should hold at the end of every constructor.
Ø       The condition should hold at the end of every mutator(non-const) operation.
     
20.   What are proxy objects?
Answer:
            Objects that stand for other objects are called proxy objects or surrogates.
Example:
                  template<class T>
                  class Array2D
                  {
                         public:
                              class Array1D
                               {
                                     public:
                                 T& operator[] (int index);
                                 const T& operator[] (int index) const;
                                 ...
                               };
                              Array1D operator[] (int index);
                              const Array1D operator[] (int index) const;
                              ...
                   };
      
            The following then becomes legal:
                   Array2D<float>data(10,20);
               ........
               cout<<data[3][6];     //  fine

            Here data[3] yields an Array1D object and the operator [] invocation on that object yields the float in position(3,6) of the original two dimensional array. Clients of the Array2D class need not be aware of the presence of the Array1D class. Objects of this latter class stand for one-dimensional array objects that, conceptually, do not exist for clients of Array2D. Such clients program as if they were using real, live, two-dimensional arrays. Each Array1D object stands for a one-dimensional array that is absent from a conceptual model used by the clients of Array2D. In the above example, Array1D is a proxy class. Its instances stand for one-dimensional arrays that, conceptually, do not exist.
      
21.   Name some pure object oriented languages.
Answer:
Ø         Smalltalk,
Ø         Java,
Ø         Eiffel, 
Ø         Sather.

22.   Name the operators that cannot be overloaded.   
Answer:
sizeof   .          .*         .->        ::          ?:                      

23.   What is a node class?
Answer:
A node class is a class that,
Ø       relies on the base class for services and implementation,
Ø       provides a wider interface to te users than its base class,
Ø       relies primarily on virtual functions in its public interface
Ø       depends on all its direct and indirect base class
Ø       can be understood only in the context of the base class
Ø       can be used as base for further derivation
Ø       can be used to create objects.
A node class is a class that has added new services or functionality beyond the services inherited from its base class.   

24.   What is an orthogonal base class?
Answer:
If two base classes have no overlapping methods or data they are said to be independent of, or orthogonal to each other. Orthogonal in the sense means that two classes operate in different dimensions and do not interfere with each other in any way. The same derived class may inherit such classes with no difficulty.

25. What is a container class? What are the types of container classes?
Answer:
A container class is a class that is used to hold objects in memory or external storage. A container class acts as a generic holder. A container class has a predefined behavior and a well-known interface. A container class is a supporting class whose purpose is to hide the topology used for maintaining the list of objects in memory. When a container class contains a group of mixed objects, the container is called a heterogeneous container; when the container is holding a group of objects that are all the same, the container is called a homogeneous container.

26. What is a protocol class?
Answer:
An abstract class is a protocol class if:
Ø       it neither contains nor inherits from classes that contain member data, non-virtual functions, or private (or protected) members of any kind.
Ø       it has a non-inline virtual destructor defined with an empty implementation,
Ø       all member functions other than the destructor including inherited functions, are declared pure virtual functions and left undefined.

27. What is a mixin class?
Answer:
A class that provides some but not all of the implementation for a virtual base class is often called mixin. Derivation done just for the purpose of redefining the virtual functions in the base classes is often called mixin inheritance. Mixin classes typically don't share common bases.

28. What is a concrete class?
Answer:
A concrete class is used to define a useful object that can be instantiated as an automatic variable on the program stack. The implementation of a concrete class is defined. The concrete class is not intended to be a base class and no attempt to minimize dependency on other classes in the implementation or behavior of the class.

29.What is the handle class?
Answer:
A handle is a class that maintains a pointer to an object that is programmatically accessible through the public interface of the handle class.
Explanation:
In case of abstract classes, unless one manipulates the objects of these classes through pointers and references, the benefits of the virtual functions are lost. User code may become dependent on details of implementation classes because an abstract type cannot be allocated statistically or on the stack without its size being known. Using pointers or references implies that the burden of memory management falls on the user. Another limitation of abstract class object is of fixed size. Classes however are used to represent concepts that require varying amounts of storage to implement them.
A popular technique for dealing with these issues is to separate what is used as a single object in two parts: a handle providing the user interface and a representation holding all or most of the object's state. The connection between the handle and the representation is typically a pointer in the handle. Often, handles have a bit more data than the simple representation pointer, but not much more. Hence the layout of the handle is typically stable, even when the representation changes and also that handles are small enough to move around relatively freely so that the user needn’t use the pointers and the references.   
  
 30. What is an action class?
Answer:
The simplest and most obvious way to specify an action in C++ is to write a function. However, if the action has to be delayed, has to be transmitted 'elsewhere' before being performed, requires its own data, has to be combined with other actions, etc then it often becomes attractive to provide the action in the form of a class that can execute the desired action and provide other services as well. Manipulators used with iostreams is an obvious example.
Explanation:
            A common form of action class is a simple class containing just one virtual function.
         class Action
       {
               public:
                    virtual int do_it( int )=0;
                    virtual ~Action( );
         }
Given this, we can write code say a member that can store actions for later execution without using pointers to functions, without knowing anything about the objects involved, and without even knowing the name of the operation it invokes. For example:
class write_file : public Action
     {
              File& f;
              public:
                  int do_it(int)
                 {
                       return fwrite( ).suceed( );
                 }
      };
     class error_message: public Action
     {
                response_box db(message.cstr( ),"Continue","Cancel","Retry");
                switch (db.getresponse( ))
                {
                        case 0: return 0;
                        case 1: abort();
                        case 2: current_operation.redo( );return 1;
                 }
      };  

A user of the Action class will be completely isolated from any knowledge of derived classes such as write_file and error_message.

31. When can you tell that a memory leak will occur?
Answer:
A memory leak occurs when a program loses the ability to free a block of dynamically allocated memory.

32.What is a parameterized type?
Answer:
A template is a parameterized construct or type containing generic code that can use or manipulate any type. It is called parameterized because an actual type is a parameter of the code body. Polymorphism may be achieved through parameterized types. This type of polymorphism is called parameteric polymorphism. Parameteric polymorphism is the mechanism by which the same code is used on different types passed as parameters.

33. Differentiate between a deep copy and a shallow copy?
Answer:
Deep copy involves using the contents of one object to create another instance of the same class. In a deep copy, the two objects may contain ht same information but the target object will have its own buffers and resources. the destruction of either object will not affect the remaining object. The overloaded assignment operator would create a deep copy of objects.
Shallow copy involves copying the contents of one object into another instance of the same class thus creating a mirror image. Owing to straight copying of references and pointers, the two objects will share the same externally contained contents of the other object to be unpredictable.
Explanation:
Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.
If the object has any pointers a deep copy needs to be executed. With the deep copy of an object, memory is allocated for the object in free store and the elements pointed to are copied. A deep copy is used for objects that are returned from a function.

34. What is an opaque pointer?
Answer:
A pointer is said to be opaque if the definition of the type to which it points to is not included in the current translation unit. A translation unit is the result of merging an implementation file with all its headers and header files.

35. What is a smart pointer?
Answer:
A smart pointer is an object that acts, looks and feels like a normal pointer but offers more functionality. In C++, smart pointers are implemented as template classes that encapsulate a pointer and override standard pointer operators. They have a number of advantages over regular pointers. They are guaranteed to be initialized as either null pointers or pointers to a heap object. Indirection through a null pointer is checked. No delete is ever necessary. Objects are automatically freed when the last pointer to them has gone away. One significant problem with these smart pointers is that unlike regular pointers, they don't respect inheritance. Smart pointers are unattractive for polymorphic code. Given below is an example for the implementation of smart pointers.
Example: 
   template <class X>
   class smart_pointer
   {
              public:
                   smart_pointer();                          // makes a null pointer
                   smart_pointer(const X& x)            // makes pointer to copy of x

                   X& operator *( );
                   const X& operator*( ) const;
                   X* operator->() const;

                   smart_pointer(const smart_pointer <X> &);
                   const smart_pointer <X> & operator =(const smart_pointer<X>&);
                   ~smart_pointer();
              private:
                   //...
    };
This class implement a smart pointer to an object of type X. The object itself is located on the heap. Here is how to use it:
            smart_pointer <employee> p= employee("Harris",1333);
Like other overloaded operators, p will behave like a regular pointer,
cout<<*p;
p->raise_salary(0.5);

36. What is reflexive association?
Answer:
The 'is-a' is called a reflexive association because the reflexive association permits classes to bear the is-a association not only with their super-classes but also with themselves. It differs from a 'specializes-from' as  'specializes-from' is usually used to describe the association between a super-class and a sub-class. For example:
Printer is-a printer.

37.  What is slicing?
Answer:
Slicing means that the data added by a subclass are discarded when an object of the subclass is passed or returned by value or from a function expecting a base class object.    
Explanation:
Consider the following class declaration:
               class base
              {
                     ...
                     base& operator =(const base&);
                     base (const base&);
              }
              void fun( )
              {
                    base e=m;
                    e=m;
              }
As base copy functions don't know anything about the derived only the base part of the derived is copied. This is commonly referred to as slicing. One reason to pass objects of classes in a hierarchy is to avoid slicing. Other reasons are to preserve polymorphic behavior and to gain efficiency.

38. What is name mangling?
Answer:
Name mangling is the process through which your c++ compilers give each function in your program a unique name. In C++, all programs have at-least a few functions with the same name. Name mangling is a concession to the fact that linker always insists on all function names being unique.
Example:
            In general, member names are made unique by concatenating the name of the member with that of the class e.g. given the declaration:
    class Bar
     {
            public:
                int ival;
                ...
      };

ival becomes something like:
      // a possible member name mangling
     ival__3Bar
Consider this derivation:
     class Foo : public Bar
    { 
          public:
              int ival;
              ...
    }
The internal representation of a Foo object is the concatenation of its base and derived class members.
     // Pseudo C++ code
    // Internal representation of Foo
    class Foo
    {
         public:
             int ival__3Bar;
             int ival__3Foo;
             ...
    };
Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique).  

39. What are proxy objects?
Answer:
Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
40. Differentiate between declaration and definition in C++.
Answer:
A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program.
A declaration is a definition unless:
Ø       it declares a function without specifying its body,
Ø       it contains an extern specifier and no initializer or function body,
Ø       it is the declaration of a static class data member without a class definition,
Ø       it is a class name definition,
Ø       it is a typedef declaration.
            A definition is a declaration unless:
Ø       it defines a static class data member,
Ø       it defines a non-inline member function.
41. What is cloning?
Answer: An object can carry out copying in two ways i.e. it can set itself to be a copy of another object, or it can return a copy of itself. The latter process is called cloning.

42. Describe the main characteristics of static functions.
Answer:
            The main characteristics of static functions include,
Ø       It is without the a this pointer,
Ø       It can't directly access the non-static members of its class
Ø       It can't be declared const, volatile or virtual.
Ø       It doesn't need to be invoked through an object of its class, although for convenience, it may.             

43. Will the inline function be compiled as the inline function always? Justify.
Answer:
            An inline function is a request and not a command. Hence it won't be compiled as an inline function always.
Explanation:
            Inline-expansion could fail if the inline function contains loops, the address of an inline function is used, or an inline function is called in a complex expression. The rules for inlining are compiler dependent.

44. Define a way other than using the keyword inline to make a function inline.
Answer:
            The function must be defined inside the class.  

45. How can a '::' operator be used as unary operator?
Answer:
            The scope operator can be used to refer to members of the global namespace. Because the global namespace doesn’t have a name, the notation :: member-name refers to a member of the global namespace. This can be useful for referring to members of global namespace whose names have been hidden by names declared in nested local scope. Unless we specify to the compiler in which namespace to search for a declaration, the compiler simple searches the current scope, and any scopes in which the current scope is nested, to find the declaration for the name.

46. What is placement new?
Answer:
            When you want to call a constructor directly, you use the placement new. Sometimes you have some raw memory that's already been allocated, and you need to construct an object in the memory you have. Operator new's special version placement new allows you to do it.
           class Widget
          {
               public :
                     Widget(int widgetsize);
                      ...
                      Widget* Construct_widget_int_buffer(void *buffer,int widgetsize)
                       {
                              return new(buffer) Widget(widgetsize);
                       }
          };
            This function returns a pointer to a Widget object that's constructed within the buffer passed to the function. Such a function might be useful for applications using shared memory or memory-mapped I/O, because objects in such applications must be placed at specific addresses or in memory allocated by special routines.


OOAD

1.      What do you mean by analysis and design?
Analysis:
Basically, it is the process of determining what needs to be done before how it should be done. In order to accomplish this, the developer refers the existing systems and documents. So, simply it is an art of discovery.
     Design:
It is the process of adopting/choosing the one among the many, which best accomplishes the users needs. So, simply, it is compromising mechanism.

2.      What are the steps involved in designing?
Before getting into the design the designer should go through the SRS prepared by the System Analyst.
            The main tasks of design are Architectural Design and Detailed Design.
            In Architectural Design we find what are the main modules in the problem domain.
In Detailed Design we find what should be done within each module.

3.      What are the main underlying concepts of object orientation?
            Objects, messages, class, inheritance and polymorphism are the main concepts of object orientation.

4.      What do u meant by "SBI" of an object?
SBI stands for State, Behavior and Identity. Since every object has the above three.
Ø       State:        
It is just a value to the attribute of an object at a particular time.
Ø       Behaviour:
It describes the actions and their reactions of that object.
Ø       Identity:
An object has an identity that characterizes its own existence. The identity makes it possible to distinguish any object in an unambiguous way, and independently from its state.

5.      Differentiate persistent & non-persistent objects?
Persistent refers to an object's ability to transcend time or space. A persistent object stores/saves its state in a permanent storage system with out losing the information represented by the object.
A non-persistent object is said to be transient or ephemeral. By default objects are considered as non-persistent.

6.      What do you meant by active and passive objects?
Active objects are one which instigate an interaction which owns a thread and they are responsible for handling control to other objects. In simple words it can be referred as client.
Passive objects are one, which passively waits for the message to be processed. It waits for another object that requires its services. In simple words it can be referred as server.

Diagram:
                        client     server
            (Active)    (Passive)

7.      What is meant by software development method?
Software development method describes how to model and build software systems in a reliable and reproducible way. To put it simple, methods that are used to represent ones' thinking using graphical notations.

8.      What are models and meta models?
Model:
It is a complete description of something (i.e. system).
Meta model:
It describes the model elements, syntax and semantics of the notation that allows their manipulation.

9.      What do you meant by static and dynamic modeling?
Static modeling is used to specify structure of the objects that exist in the problem domain. These are expressed using class, object and USECASE diagrams.
            But Dynamic modeling refers representing the object interactions during runtime. It is represented by sequence, activity, collaboration and statechart diagrams.

10.  How to represent the interaction between the modeling elements?
              Model element is just a notation to represent (Graphically) the entities that exist in the problem domain. e.g. for modeling element is class notation, object notation etc.
              Relationships are used to represent the interaction between the modeling elements.
              The following are the Relationships.

Ø       Association: Its' just a semantic connection two classes.
e.g.:
                                                           


Ø       Aggregation: Its' the relationship between two classes which are related in the fashion that master and slave. The master takes full rights than the slave. Since the slave works under the master. It is represented as line with diamond in the master area.
        ex:
           car contains wheels, etc.
              
                                    car      

Ø       Containment: This relationship is applied when the part contained with in the whole part, dies when the whole part dies.
              It is represented as darked diamond at the whole part.
              example:
                        class A{
               //some code
                              };

                  class B
                 {
                                    A aa; // an object of class A;
                                    // some code for class B;
                             };
              In the above example we see that an object of class A is instantiated with in the class  B. so the object class A dies when the object class B dies.we can represnt it in                    diagram like this.
                                               
                       


Ø       Generalization: This relationship used when we want represents a class, which captures the common states of objects of different classes. It is represented as arrow line pointed at the class, which has captured the common states.
           
                          


                                                           
                                   
             


Ø       Dependency: It is the relationship between dependent and independent classes. Any change in the independent class will affect the states of the dependent class.
               DIAGRAM:
                                    class A     class B

11.  Why generalization is very strong?
             Even though Generalization satisfies Structural, Interface, Behaviour properties. It is mathematically very strong, as it is Antisymmetric and Transitive.
            Antisymmetric: employee is a person, but not all persons are employees. Mathematically all As’ are B, but all Bs’ not A.
             Transitive: A=>B, B=>c then A=>c.
              A. Salesman.
                          B. Employee.           
                          C. Person.
             Note: All the other relationships satisfy all the properties like Structural properties, Interface properties, Behaviour properties.

12.  Differentiate Aggregation and containment?
            Aggregation is the relationship between the whole and a part. We can add/subtract some   properties in the part (slave) side. It won't affect the whole part.
            Best example is Car, which contains the wheels and some extra parts. Even though the parts are not there we can call it as car.
            But, in the case of containment the whole part is affected when the part within that got affected. The human body is an apt example for this relationship. When the whole body dies the parts (heart etc) are died.

13.  Can link and Association applied interchangeably?
            No, You cannot apply the link and Association interchangeably. Since link is used represent the relationship between the two objects.
            But Association is used represent the relationship between the two classes.
            link ::                student:Abhilash         course:MCA
            Association::    student                  course
                       
14.  what is meant by "method-wars"?
            Before 1994 there were different methodologies like Rumbaugh, Booch, Jacobson, Meyer etc who followed their own notations to model the systems. The developers were in a dilemma to choose the method which best accomplishes their needs.     This particular span was called as "method-wars"

15.  Whether unified method and unified modeling language are same or different?
      Unified method is convergence of the Rumbaugh and Booch.
      Unified modeling lang. is the fusion of Rumbaugh, Booch and Jacobson as well as Betrand Meyer (whose contribution is "sequence diagram"). Its' the superset of all the methodologies.

16.  Who were the three famous amigos and what was their contribution  to the object community?
            The Three amigos namely,
Ø       James Rumbaugh (OMT): A veteran in analysis who came up with an idea about the   objects and their Relationships (in particular Associations).
Ø       Grady Booch: A veteran in design who came up with an idea about partitioning of systems into subsystems.
     
Ø       Ivar Jacobson (Objectory): The father of USECASES, who described about the user and system interaction.

17.  Differentiate the class representation of Booch, Rumbaugh and UML?
            If you look at the class representaiton of Rumbaugh and UML, It is some what similar and both are very easy to draw.
      Representation:   OMT                                                                 UML.
      Diagram:



     
            Booch: In this method classes are represented as "Clouds" which are not very easy to draw as for as the developer's view is concern.
      Diagram:





18.  What is an USECASE? Why it is needed?
            A Use Case is a description of a set of sequence of actions that a system performs that yields an observable result of value to a particular action.
In SSAD process <=> In OOAD USECASE. It is represented elliptically.
            Representation:







19.  Who is an Actor?
            An Actor is someone or something that must interact with the system.In addition to that   an Actor initiates the process(that is USECASE).
            It is represented as a stickman like this.
            Diagram:






20.  What is guard condition?
            Guard condition is one, which acts as a firewall. The access from a particular object can be made only when the particular condition is met.
            For Example,
                        customer      check customer number   ATM.
Here the object on the customer accesses the ATM facility only when the guard condition is met.

21.  Differentiate the following notations?
                        I:          :obj1               :obj2
    
                        II:        :obj1               :obj2


            In the above representation I, obj1 sends message to obj2. But in the case of II the data is transferred from obj1 to obj2.

22.  USECASE is an implementation independent notation. How will the designer give the implementation details of a particular USECASE to the programmer?
This can be accomplished by specifying the relationship called "refinement” which             talks about the two different abstraction of the same thing.
            Or example,
           
            calculate pay                 calculate
                                               
                                                class1   class2 class3
           
23.  Suppose a class acts an Actor in the problem domain, how to represent it in the static model?
            In this scenario you can use “stereotype”. Since stereotype is just a string that gives extra semantic to the particular entity/model element. It is given with in the <<  >>.

                        class A
                        << Actor>>
                        attributes
           
                        methods.

24.  Why does the function arguments are called as "signatures"?
            The arguments distinguish functions with the same name (functional polymorphism). The name alone does not necessarily identify a unique function.  However, the name and its arguments (signatures) will uniquely identify a function.
            In real life we see suppose, in class there are two guys with same name, but they can be     easily identified by their signatures. The same concept is applied here.
            ex:
                        class person
                        {
                  public:
                                    char getsex();
                                    void setsex(char);
                                    void setsex(int);
                        };
            In the above example we see that there is a function setsex() with same name but with different signature.



                                                   Playing with scanf function
                                                   Operators & Expressions
                               _____   _____________________________________



[Q001]. Determine which of the following are VALID identifiers. If invalid, state the reason.
            (a) sample1      (b) 5sample      (c) data_7        (d) return         (e) #fine
            (f) variable       (g) 91-080-100            (h) name & age            (i) _val (j) name_and_age
Ans.     (a) VALID
            (b) Invalid, since an identifier must begin with a letter or an underscore
            (c) VALID
            (d) Invalid, since return is a reserved word
            (e) Invalid, since an identifier must begin with a letter or an underscore
            (f) VALID
            (g) Invalid, since an identifier must begin with a letter or an underscore
            (h) Invalid, since blank spaces are not allowed
            (i) VALID
            (j) VALID
_________________________________________________________________________________________________
           
[Q002]. Determine which of the following are VALID character constants. If invalid, state the reason.
            (a) 'y'               (b) '\r'   (c) 'Y'              (d) '@'             (e) '/r'
            (f) 'word'         (g) '\0'  (h) '\?'  (i) '\065'           (j) '\''    (k) ' '
Ans.     (a) VALID
            (b) VALID
            (c) VALID
            (d) VALID
            (e) Invalid, since escape sequences must be written with a backward slash (i.e. \)
            (f) Invalid, since a character constant cannot consist of multiple characters
            (g) VALID (null-character escape sequence)
            (h) VALID
            (i) VALID (Octal escape sequence)
            (j) VALID
            (k) VALID
_________________________________________________________________________________________________

[Q003]. Determine which of the following are VALID string constants. If invalid, state the reason.
            (a) 'Hi Friends'                        (b) "abc,def,ghi"                      (c) "Qualification
            (d) "4325.76e-8"                     (e) "Don\'t sleep"                     (f) "He said, "You\'re great"
            (g) ""                                        (h) "            "                (i) "Rs.100/-"
Ans.     (a) Invalid, since a string constant must be enclosed in double quotation marks
            (b) VALID
            (c) Invalid, since trailing quotation mark is missing
            (d) VALID
            (e) VALID (single-quote escape sequence)
            (f) Invalid, since the quotation marks and (optionally) apostrophe within the string
                cannot be expressed without the escape sequences.
            (g) VALID
            (h) VALID
            (i) VALID
_________________________________________________________________________________________________

[Q004]. Determine which of the following numerical values are valid constants. If a constant is
valid, specify whether it is integer or real. Also, specify the base for each valid integer constant.
            (a) 10,500        (b) 080             (c) 0.007          (d) 5.6e7          (e) 5.6e-7
            (f) 0.2e-0.3      (g) 0.2e 0.3      (h) 0xaf9s82    (i) 0XABCDEFL        (j) 0369CF
            (k) 87654321l  (l) 87654321   
Ans.     (a) Invalid, since illegal character(,)
            (b) VALID
            (c) VALID
            (d) VALID
            (e) VALID
            (f) VALID
            (g) Invalid, since illegal character(blank space)
            (h) Invalid, since illegal character(s)
            (i) VALID
            (j) Invalid, since illegal characters (9, C, F), if intended as an octal constant.
            (k) VALID
            (l) VALID
_________________________________________________________________________________________________

[Q005]. Determine which of the following floating-point constants are VALID for the quantity (5 * 100000).
            (a) 500000       (b) 0.5e6          (c) 5E5                        (d) 5e5             (e) 5e+5
            (f) 500E3         (g) .5E6           (h) 50e4           (i) 50.E+4        (j) 5.0E+5
            (k) All of the above                 (l) None of these
Ans. (k)
_________________________________________________________________________________________________

[Q006]. What will be the output of the following program :
            void main()
            {
          printf("%f",123.);
            }
(a)123                          (b)Compile-Time Error                        (c)123.00                     (d)123.000000
Ans. (d)
_________________________________________________________________________________________________

[Q007]. What will be the output of the following program :
            void main()
            {
          printf("%d",sizeof(integer));
            }
(a)2                              (b)Compile-Time Error                        (c)4                              (d)None of these
Ans. (b) since there is no such data type called 'integer'.
_________________________________________________________________________________________________

[Q008]. What will be the output of the following program :
            void main()
            {
          char str[]="C For Swimmers";
              printf("%d",sizeof str);
            }
(a)14                            (b)Compile-Time Error                        (c)15                            (d)None of these
Ans. (a)--c
_________________________________________________________________________________________________

[Q009]. What will be the output of the following program :
            void main()
            {
          char str[]="C For Swimmers";
              printf("%d",++(sizeof(str)));
            }
(a)14                            (b)Compile-Time Error                        (c)15                            (d)None of these
Ans. (b)
_________________________________________________________________________________________________

[Q010]. What will be the output of the following program :
            void main()
            {
          char str[]="C For Swimmers";
              printf("%d",-sizeof(str));
            }
(a)14                            (b)Compile-Time Error                        (c)-15                           (d)-14
Ans. (c)
_________________________________________________________________________________________________

[Q011]. What will be the output of the following program :
            void main()
            {
          printf("%d",!(100==100)+1);
            }
(a)100                          (b)0                                          (c)1                              (d)2
Ans. (c)
_________________________________________________________________________________________________

[Q012]. What will be the output of the following program :
            void main()
            {
          int x=5,y=6,z=2;
              z/=y/z==3?y/z:x*y;
              printf("%d",z);
            }
(a)Compile-Time Error            (b)2                                          (c)0                              (d)1
Ans. (c)
_________________________________________________________________________________________________

[Q013]. What will be the output of the following program :
            void main()
            {
          printf("%d %d %d",5,!5,25 - !25);
            }
(a)5 10 22                    (b)5 5 25                                  (c)5 0 25                      (d)5 1 24
Ans. (c)
_________________________________________________________________________________________________

[Q014]. What will be the output of the following program :
            int main()
            {
              int a=500,b=100,c=30,d=40,e=19;
              a+=b-=c*=d/=e%=5;
              printf("%d %d %d %d %d",a,b,c,d,e);
            }
(a)500 100 30 40 4      (b)Run-Time Error      (c)700 200 300 10 4    (d)300 -200 300 10 4
Ans. (d)
_________________________________________________________________________________________________

[Q015]. What will be the output of the following program :
            void main()
            {
          int a=500,b=100,c=30,d=40,e=19;
              if ((((a > b) ? c : d) >= e) && !((e <= d) ? ((a / 5) == b) : (c == d)))
                        printf("Success");
              else
                        printf("Failure");
            }
(a)VALID : Success   (b)VALID : Failure     (c)INVALID              (d)None of these
Ans. (b)
_________________________________________________________________________________________________

[Q016]. What will be the output of the following program :
            void main()
            {
          int a=1,b=2,c=3,d=4;
              printf("%d",!a?b?!c:!d:a);
            }
(a)1                              (b)2                              (c)3                              (d)4
Ans. (a)
_________________________________________________________________________________________________

[Q017]. What will be the output of the following program :
            void main()
            {
              int i=12345,j=-13579,k=-24680;
              long ix=123456789;
              short sx=-2222;
              unsigned ux=5555;
              printf("\n%d %d %d %ld %d %u",i,j,k,ix,sx,ux);
              printf("\n\n%3d %3d %3d\n%3ld %3d %3u",i,j,k,ix,sx,ux);
              printf("\n\n%8d %8d %8d\n%15ld %8d %8u",i,j,k,ix,sx,ux);
              printf("\n\n%-8d %-8d\n%-8d %-15ld\n%-8d %-8u",i,j,k,ix,sx,ux);
              printf("\n\n%+8d %+8d\n%+8d %+15ld\n%+8d %8u",i,j,k,ix,sx,ux);
              printf("\n\n%08d %08d\n%08d %015ld\n%08d %08u",i,j,k,ix,sx,ux);
            }
Ans. 12345 -13579 -24680 123456789 -2222 5555
    
     12345 -13579 -24680
     123456789 -2222 5555

        12345   -13579   -24680
           123456789    -2222     5555

     12345    -13579
     -24680   123456789
     -2222    5555

       +12345   -13579
       -24680      +123456789
        -2222     5555

     00012345 -0013579
     -0024680 000000123456789
     -0002222 00005555
_________________________________________________________________________________________________

[Q018]. What will be the output of the following program :
            void main()
            {
          int i=12345,j=0xabcd9,k=077777;
              printf("%d %x %o",i,j,k);
              printf("\n%3d %3x %3o",i,j,k);
              printf("\n%8d %8x %8o"i,j,k);
              printf("\n%-8d %-8x %-8o",i,j,k);
              printf("\n%+8d %+8x %+8o",i,j,k);
              printf("\n%08d %#8x %#8o",i,j,k);
            }
Ans. 12345 abcd9 77777
     12345 abcd9 77777
        12345    abcd9    77777
     12345    abcd9    77777
       +12345    abcd9    77777
     00012345  0xabcd9   077777
_________________________________________________________________________________________________

[Q019]. What will be the output of the following program :
            void main()
            {
              char c1='A', c2='B', c3='C';
              printf("%c %c %c",c1,c2,c3);
              printf("\n%c%c%c",c1,c2,c3);
              printf("\n%3c %3c %3c",c1,c2,c3);
              printf("\n%3c%3c%3c",c1,c2,c3);
              printf("\nc1=%c c2=%c c3=%c",c1,c2,c3);
            }
Ans. A B C
     ABC
       A   B   C
       A  B  C
     c1=A c2=B c3=C
_________________________________________________________________________________________________

[Q020]. What will be the output of the following program :
            void main()
            {
              float a=2.5, b=0.0005, c=3000.;
              printf("%f %f %f",a,b,c);
              printf("\n%3f %3f %3f",a,b,c);
              printf("\n%8f %8f %8f",a,b,c);
              printf("\n%8.4f %8.4f %8.4f",a,b,c);
              printf("\n%8.3f %8.3f %8.3f",a,b,c);
              printf("\n%e %e %e",a,b,c);
              printf("\n%3e %3e %3e",a,b,c);
              printf("\n%12e %12e %12e",a,b,c);
              printf("\n%8.2e %8.2e %8.2e",a,b,c);
              printf("\n%-8f %-8f %-8f",a,b,c);
              printf("\n%+8f %+8f %+8f",a,b,c);
              printf("\n%08f %08f %08f",a,b,c);
              printf("\n%#8f %#8f %#8f",a,b,c);
              printf("\n%g %g %g",a,b,c);
              printf("\n%#g %#g %#g"a,b,c);
            }

Ans. 2.500000 0.000500 3000.000000
     2.500000 0.000500 3000.000000
     2.500000 0.000500 3000.000000
       2.5000   0.0005 3000.0000
        2.500    0.001 3000.000
     2.500000e+000 5.000000e-004 3.000000e+003
     2.500000e+000 5.000000e-004 3.000000e+003
     2.500000e+000 5.000000e-004 3.000000e+003
      2.5000e+000  5.0000e-004  3.0000e+003
     2.50e+000 5.00e-004 3.00e+003
     2.500000 0.000500 3000.000000
     +2.500000 +0.000500 +3000.000000
     2.500000 0.000500 3000.000000
     2.500000 0.000500 3000.000000
     2.5 0.0005 3000
     2.500000 0.000500 3000.000000
_________________________________________________________________________________________________

[Q021]. What will be the output of the following program :
            void main()
            {
              char str[]="C For Swimmers";
              printf("%s",str);
              printf("\n%.5s",str);
              printf("\n%8.*s",5,str);
              printf("\n%-10s %.1s",str+6,str);
            }
Ans. C For Swimmers
     C For
        C For
     Swimmers   C  
_________________________________________________________________________________________________

[Q022]. What will be the output of the following program :
            void main()
            {
              int a=1,b=2,c=3;
              scanf("%d %*d %d",&a,&b,&c);
              printf("a=%d b=%d c=%d",a,b,c);
            }
[NOTE : 3 values entered by the user are:100 200 300]
(a)1 2 3                        (b)100 200 300                                    (c)100 200 3                (d)100 300 3 
Ans. (d)
_________________________________________________________________________________________________

[Q023]. What will be the output of the following program :
            void main()
            {
              char line[80];  // Max. length=80 Chars
              scanf("%[^,]s",line);
              printf("\n%s",line);
            }
[NOTE : THE USER INPUT IS:Dear Friends, What is the output?]
(a)Compile-Time Error            (b)Dear Friends                                   (c)What is the output?            (d)None of these
Ans. (b)          
_________________________________________________________________________________________________

[Q024]. What will be the output of the following program :
            void main()
            {
              char a,b,c;
              scanf("%c%c%c",&a,&b,&c);
              printf("a=%c b=%c c=%c",a,b,c);
            }
[NOTE : THE USER INPUT IS :A B C]
(a)a=A b=B c=C                     (b)a=A b=  c=B                                   (c)a=A b=  c=C                       (d)None of these
Ans. (b)
_________________________________________________________________________________________________

[Q025]. What will be the output of the following program :
            void main()
            {
              int i=1;
              float f=2.25;
              scanf("%d a %f",&i,&f);
              printf("%d %.2f",i,f);
            }
[NOTE : THE USER INPUT IS:5 5.75]
(a)1 2.25                      (b)5 5.75                                  (c)5 2.25                      (d)None of these
Ans. (c)          
_________________________________________________________________________________________________

[Q026]. What will be the output of the following program :
            void main()
            {
              char a,b,c;
              scanf("%c %c %c",&a,&b,&c);
              printf("a=%c b=%c c=%c",a,b,c);
            }
[NOTE : THE USER INPUT IS :ABC DEF GHI]
(a)a=ABC b=DEF c=GHI                  (b)a=A b=B c=C                     (c)a=A b=D c=G                     (d)None of these
Ans. (b)
_________________________________________________________________________________________________

[Q027]. What will be the output of the following program :
            void main()
            {
              char a[80],b[80],c[80];
                          scanf("%1s %5s %3s",a,b,c);
              printf("%s %s %s",a,b,c);
            }
[NOTE : THE USER INPUT IS:CMeansSea Ocean Vast]
(a)C O V         (b)C Means Sea                                               (c)C Ocean Vas                       (d)None of these
Ans. (b)          
_________________________________________________________________________________________________

[Q028]. What will be the output of the following program :
            void main()
            {
              int a,b,c;
              scanf("%1d %2d %3d",&a,&b,&c);
              printf("Sum=%d",a+b+c);
            }
                        [NOTE : THE USER INPUT IS :123456 44 544]
(a)Sum=480                (b)Sum=594                            (c)Sum=589                (d)None of these
Ans. (a)
_________________________________________________________________________________________________

[Q029]. What happens when the following program is executed :
            void main()
            {
              char line[80];
              scanf("%[^1234567890\n]",line);
            }
(a)Accepts the string that contains DIGITS only.
(b)Accepts the string that contains DIGITS and NEWLINE characters.
(c)Accepts the string that contains anything other than the DIGITS and NEWLINE characters.
(d)None of these
Ans. (c)          
_________________________________________________________________________________________________

[Q030]. What happens when the following program is executed :
            void main()
            {
              char line[80];
          scanf("%[^*]",line);
            }
(a)Accepts the string that contains DIGITS & ALPHABETS only.
(b)Accepts the string that contains * or asterisk characters only.
(c)Accepts the string that contains anything other than the * or asterisk character.
(d)None of these
Ans. (c)          
_________________________________________________________________________________________________
                                   
[Q001]. What will be the output of the following program :
            void main()
            {
           printf();
            }
(a)Run-Time Error       (b)Compile-Time Error                        (c)No Output              (d)None of these
Ans. (b) Since there must be enough arguments for the format.
_____________________________________________________
           
[Q002]. What will be the output  of the following program :
            void main()
            {
          printf(NULL);
            }
(a)Run-Time Error       (b)Compile-Time Error                        (c)No Output              (d)None of these
Ans. (c) Since NULL is a constant value or NULL pointer value or a NULL string.
____________________________________________________

[Q003]. What will be the output of the following program :
            void main()
            {
          printf("%%",7);
            }
(a)7                              (b)Compile-Time Error                        (c)%                             (d)%%
Ans. (c) Since % is a format specifier & excess arguments (more than required by the format) are
merely ignored.
__________________________________________________________

[Q004]. What will be the output of the following program :
            void main()
        {
          printf("//",5);
            }
(a)5                              (b)Compile-Time Error                        (c)/                               (d)//
Ans. (d) Since // is taken as string
_____________________________________________________________

[Q005]. What will be the output of the following program :
            void main()
            {
          printf("d%",8);
            }
(a)8                              (b)Compile-Time Error                        (c)d%                          (d)None of these
Ans. (c) Since excess arguments (more than required by the format) are merely ignored.
__________________________________________________________

[Q006]. What will be the output of the following program :
            void main()
            {
          printf("%d"+0,123);
            }
(a)123                          (b)Compile-Time Error                        (c)No Output              (d)None of these
Ans. (a)   since"%d"+0 has no effect on the output operation.
__________________________________________________________________

[Q007]. What will be the output of the following program :
            void main()-----------------doubt
            {
          printf("%d"+1,123);
            }

(a)123                          (b)Compile-Time Error                        (c)d      (d)No Output

Ans. (c)  since "%d"+1 (i.e 1 or > 0) affects the program output by considering "%d" as string and ignores 123
Where 1 refers to the index i.e. 2nd character in the array or string "%d".
_______________________________________________________________

[Q008]. What will be the output of the following program :
            void main()
            {
          printf("%d",printf("Hi!")+printf("Bye"));
            }
(a)ByeHi!6      (b)Hi!Bye6                  (c)Compile-Time Error            (d)None of these
Ans. (b) Since L->R priority & the length of the strings 'Hi!' & 'Bye' is 3+3=6
____________________________________________________________

[Q009]. What will be the output of the following program :
            void main()
            {
          printf("%d",printf("Hi!")*printf("Bye"));
            }
(a)ByeHi!6                  (b)Hi!Bye9                  (c)Hi!Bye                                (d)None of these
Ans. (b) Since L->R priority & the length of the strings 'Hi!' & 'Bye' is 3*3=9
________________________________________________________

[Q010]. What will be the output of the following program :
            void main()
            {
          printf("%d",printf("")+printf(""));
            }
(a)0                  (b)No Output              (c)Compile-Time Error            (d)None of these
Ans. (a) Since L->R priority & the length of the 2 empty strings are : 0+0=0
____________________________________________________________

[Q011]. What will be the output of the following program :
            void main()
            {
          printf("Hi Friends"+3);
            }
(a)Hi Friends               (b)Friends        (c)Hi Friends3             (d)None of these

Ans. (b) Since (base adress)+0 points to the value 'H'. Now the NEW (base address) equals (base address)+3 that points to the character 'F'. Thus it prints the string from 'F' onwards.
___________________________________________________________

[Q012]. What will be the output of the following program :
            void main()
            {
          printf("C For ") + printf("Swimmers");
            }
(a)Compile-Time Error            (b)C For Swimmers     (c)Run-Time Error                   (d)None of these
Ans. (b) It is a VALID C statement.
____________________________________________________________

[Q013]. What will be the output of the following program :
            void main()
            {
          printf("\/\*\-*\/");
            }
(a)Run-Time Error       (b)\/*-*\/                      (c)/*-*/                         (d)None of these
Ans. (c) Since \ is an escape sequence character. Be careful while analyzing such statements.
_______________________________________________________________

[Q014]. What will be the output of the following program :
            int main()
            {
              int main=7;
              {
            printf("%d",main);
                return main;
              }
          printf("Bye");
            }
(a)Compile-Time Error            (b)Run-Time Error      (c)7Bye        (d)7

Ans. (d) It is a VALID C statement. Prints 7 and returns the same to the OS. NOTE: Last printf  statement will not be executed.
________________________________________________________

[Q015]. What will be the output of the following program :
            void main()
            {
          main();
            }
(a)Compile-Time Error            (b)Run-Time Error      (c)Infinite Loop    (d)None of these
Ans. (c) It is a VALID C statement. It is like a recursive function & the statements get executed infinite number of times. (All compilers will not support)
_____________________________________________________________

[Q016]. What will be the output of the following program :
            void main()
            {
          printf("Work" "Hard");
            }
(a)Work           (b)Hard           (c)No Output                          (d)WorkHard
Ans. (d) Since L->R priority. First it prints the word 'Work' & then 'Hard'.
______________________________________________________________

[Q017]. What will be the output of the following program :
            void main()
            {
          char str[]="%d";
          int val=25;
              printf(str,val);
            }
(a)Compile-Time Error            (b)Run-Time Error      (c)25    (d)None of these
Ans. (c) It is a VALID C statement. First parameter contains the format specifier & the Second  parameter contains the actual value 25.
________________________________________________________

[Q018]. What will be the output of the following program :
            void main()
            {
          int val=75;
              printf("%d",val,.,.);
            }
(a)Compile-Time Error            (b)Unpredictable         (c)75    (d)None of these
Ans. (b) Output is Unpredictable B'coz there are not enough arguments for the format. But it is a VALID C statement.
____________________________________________________

[Q019]. What will be the output of the following program :
            void main()---------------------doubt
            {
          int val=10;
              printf("%d",val+1,"%d",val--);
            }
(a)10                            (b)11 10                       (c)11 9                                     (d)10    9
Ans. (a)  Since R->L priority. The second format specifier “%d” is an excess argument and it is ignored.
______________________________________________________________

[Q020]. What will be the output of the following program :
            void main()
            {
          int val=5;
              printf("%d %d %d %d",val,--val,++val,val--);
            }
(a)3 4 6 5         (b)5 5 6 5                     (c)4 4 5 5         (d)None of these
Ans. (c) Since R->L priority.
___________________________________________________________














[Q021]. What will be the output of the following program :
            void main()
            {
          int val=5,num;
              printf("%d",scanf("%d %d",&val,&num));
            }
[NOTE : ASSUME 2 values are entered by the user are stored in the variables 'val' & 'num' respectively.]
(a)1                              (b)2                              (c)5                                          (d)None of these
Ans. (b) Since scanf statement returns the number of input fields successfully scanned, converted
& stored.
_________________________________________________________________________________________________

[Q022]. What will be the output of the following program :
            #define Compute(x,y,z) (x+y-z)---------------doubt
            void main()
            {
          int x=2,y=3,z=4;
              printf("%d",Compute(y,z,(-x+y)) * Compute(z,x,(-y+z)));
            }
(a)40                            (b)30                            (c)Compile-Time Error                        (d)None of these
Ans. (b) Since it is macro function. NOTE : Be careful while doing such type of calculations.
_________________________________________________________________________________________________

[Q023]. What will be the output of the following program :
            void main()
            {
          int m=10,n=20;
              printf("%d %d %d",m/* m-value */,/* n-value */n,m*/* Compute m*n */n);
            }
(a)Run-Time Error       (b)10 20 200                (c)Compile-Time Error                        (d)None of these
Ans. (b) Since comments /*...*/ are ignored by the compiler.
_________________________________________________________________________________________________

[Q024]. What will be the output of the following program :
            void main()
            {
          int m=10,n=20;
              /* printf("%d",m*n);
            }
(a)VALID but No Output      (b)VALID : Prints 200           (c)Compile-Time Error                        (d)None of these
Ans. (c) Since COMMENT statement not ended properly i.e */ is missing in the above program.
_________________________________________________________________________________________________

[Q025]. What will be the output of the following program :
            void main()
            {
          int val=97;
              "Printing..."+printf("%c",val);
            }
(a)Printing...97            (b)97                            (c)Compile-Time Error                        (d)a
Ans. (d) Since alphabet 'a' is the ASCII equivalent of 97.
_________________________________________________________________________________________________

[Q026]. What will be the output of the following program :
            void main()
            {
          int val=5;
              val=printf("C") + printf("Skills");
          printf("%d",val);
            }
(a)Skills5                     (b)C1                           (c)Compile-Time Error                        (d)CSkills7
Ans. (d) VALID Since 'printf' function return the no. of bytes output.
_________________________________________________________________________________________________

[Q027]. What will be the output of the following program :
            void main()
            {
          char str[]="Test";
              if ((printf("%s",str)) == 4)
            printf("Success");
              else
                        printf("Failure");
            }
(a)TestFailure              (b)TestSuccess                        (c)Compile-Time Error                        (d)Test
Ans. (b) VALID Since 'printf' function return the no. of bytes output.
_________________________________________________________________________________________________

[Q028]. What will be the output of the following program :
            void main()
            {
          int val=5;
              printf("%*d",val);
            }
(a)     5             (b)5                              (c)Compile-Time Error                        (d)None of these
Ans. (a) VALID Since '*' specifies the precision (i.e. the next argument in the precision). If no
precision is specified then the value itself will be the precision value. Thus it prints 5 BLANK
SPACES & then the value 5.
_________________________________________________________________________________________________

[Q029]. What will be the output of the following program :
            void main()--------------------------doubt
            {
          int val=5;
              printf("%d5",val);
            }
(a)Compile-Time Error            (b)5                              (c)55                                        (d)     5
Ans. (c)
_________________________________________________________________________________________________

[Q030]. What will be the output of the following program :
            void main()
            }
          int val=5;
              printf("%d",5+val++);
            {
(a)Compile-Time Error            (b)5                              (c)10                                        (d)11
Ans. (a) Since incorrect usage of pair of braces } and {. Correct usage : Each compound statement
should be enclosed within a pair of braces, i.e { and }.
_________________________________________________________________________________________________
 

                 Topic : Decision-making, Branching, Looping & Bit-wise operations

 [Q001]. What will be the output of the following program :
            void main()
            {
              printf("Hi!");
              if (-1)
                printf("Bye");
            }
(a)No Output              (b)Hi!                                      (c)Bye                         (d)Hi!Bye
Ans. (d)          
_________________________________________________________________________________________________
           
[Q002]. What will be the output of the following program :
            void main()
            {
              printf("Hi!");
              if (0 || -1)
                printf("Bye");
            }
(a)No Output              (b)Hi!                                      (c)Bye                         (d)Hi!Bye
Ans. (d)          
_________________________________________________________________________________________________

[Q003]. What will be the output of the following program :
            void main()
            {
              printf("Hi!");
              if (!1)
                printf("Bye");
            }
(a)Compile-Time error (b)Hi!                                      (c)Bye                         (d)Hi!Bye
Ans. (b)
_________________________________________________________________________________________________
           
[Q004]. What will be the output of the following program :
            void main()
            {
              printf("Hi!");
              if !(0)
                printf("Bye");
            }
(a)Compile-Time error (b)Hi!                                      (c)Bye                         (d)Hi!Bye
Ans. (a)
_________________________________________________________________________________________________

[Q005]. What will be the output of the following program :
            void main()
            {
                        printf("Hi!");
                        if (-1+1+1+1-1-1-1+(-1)-(-1))
                                    printf("Bye");
            }
(a)No Output              (b)Hi!                                      (c)Bye                         (d)Hi!Bye
Ans. (d)
_________________________________________________________________________________________________
           
[Q006]. What will be the output of the following program :
            void main()
            {
              if (sizeof(int) && sizeof(float) && sizeof(float)/2-sizeof(int))
                        printf("Testing");            
              printf("OK");
            }
(a)No Output              (b)OK                                      (c)Testing                    (d)TestingOK
Ans. (b)
_________________________________________________________________________________________________

[Q007]. What will be the output of the following program :
            void main()
            {
              int a=1,b=2,c=3,d=4,e;
              if (e=(a & b | c ^ d))
                  printf("%d",e);
            }
(a)0                              (b)7                                          (c)3                              (d)No Output
Ans. (b)          
_________________________________________________________________________________________________
           
[Q008]. What will be the output of the following program :
            void main()
            {
              unsigned val=0xffff;
              if (~val)
                printf("%d",val);
              printf("%d",~val);
            }
(a)Compile-Time error (b)-1                                        (c)0                              (d)-1 0
Ans. (c)
_________________________________________________________________________________________________

[Q009]. What will be the output of the following program :
            void main()
            {
              unsigned a=0xe75f,b=0x0EF4,c;
              c=(a|b);
              if ((c > a) && (c > b))
                printf("%x",c);
            }
(a)No Output              (b)0xe75f                                (c)0xefff                      .(d)None of these
Ans. (c)
_________________________________________________________________________________________________
           
[Q010]. What will be the output of the following program :
            void main()
            {
              unsigned val=0xabcd;
              if (val>>16 | val<<16)
                {
                        printf("Success");
                        return;
                }
              printf("Failure");
            }
(a)No Output              (b)Success                               (c)Failure                     (d)SuccessFailure
Ans.(b)           
_________________________________________________________________________________________________

[Q011]. What will be the output of the following program :
            void main()
            {
              unsigned x=0xf880,y=5,z;
              z=x<<y;
              printf("%#x %#x",z,x>>y-1);
            }
(a)1000 f87                 (b)8800 0xf88                         (c)1000 f88                 (d)0x1000 0xf88
Ans. (d)
_________________________________________________________________________________________________
           
[Q012]. What will be the output of the following program :
            void main()
            {
              register int a=5;
              int *b=&a;
              printf("%d %d",a,*b);
            }
(a)Compile-Time error (b)Run-Time error                   (c)5 5                           (d)Unpredictable
Ans. (a)          
_________________________________________________________________________________________________

[Q013]. What will be the output of the following program :
            auto int a=5;
            void main()
            {
              printf("%d",a);
            }
(a)Compile-Time error (b)Run-Time error                   (c)5                              (d)Unpredictable
Ans. (a)
_________________________________________________________________________________________________
           
[Q014]. What will be the output of the following program :
            void main()
            {
              auto int a=5;
              printf("%d",a);
            }
(a)Compile-Time error (b)Run-Time error                   (c)5                              (d)Unpredictable
Ans. (c)          
_________________________________________________________________________________________________

[Q015]. What will be the output of the following program :
            void main()
            {
              int a=1,b=2,c=3,d=4;
              if (d > c)
                 if (c > b)
                        printf("%d %d",d,c);
                 else if (c > a)
                        printf("%d %d",c,d);
              if (c > a)
                        if (b < a)
                           printf("%d %d",c,a);
                        else if (b < c)
                           printf("%d %d",b,c);

            }
(a)4 3 3 4                     (b)4 3 3 2                                 (c)4 32 3                      (d)4 33 1
Ans. (c)
_________________________________________________________________________________________________
           
[Q016]. What will be the output of the following program :
            void main()
            {
              int a=1,b=2,c=3,d=4;
              if (d > c)
                 if (c > b)
                        printf("%d %d",d,c);
                 if (c > a)
                        printf("%d %d",c,d);
              if (c > a)
                        if (b < a)
                           printf("%d %d",c,a);
                        if (b < c)
                           printf("%d %d",b,c);

            }
(a)4 32 3                      (b)4 33 42 3                             (c)4 3 3 4 2 3               (d)None of these
Ans. (b)
_________________________________________________________________________________________________

[Q017]. What will be the output of the following program :
            void main()
            {
              int a=1;
              if (a == 2);
                 printf("C Program");
            }
(a)No Output              (b)C Program                          (c)Compile-Time Error
Ans. (b)          
_________________________________________________________________________________________________
           
[Q018]. What will be the output of the following program :
            void main()
            {
              int a=1;
              if (a)
                 printf("Test");
              else;
                 printf("Again");
            }
(a)Again                      (b)Test                                     (c)Compile-Time Error            (d)TestAgain
Ans. (d)          
_________________________________________________________________________________________________

[Q019]. What will be the output of the following program :
            void main()
            {
              int i=1;
              for (; i<4; i++);
                  printf("%d\n",i);
            }
(a)No Output              (b)1                                          (c)4                              (d)None of these
                                       2
                                       3
Ans. (c)          
_________________________________________________________________________________________________
           
[Q020]. What will be the output of the following program :
            void main()
            {
              int a,b;
              for (a=0; a<10; a++);
                 for (b=25; b>9; b-=3);
                    printf("%d %d",a,b);
            }
(a)Compile-Time error (b)10 9                                     (c)10 7                         (d)None of these
Ans. (c)          
_________________________________________________________________________________________________

[Q021]. What will be the output of the following program :
            void main()
            {
              float i;
              for (i=0.1; i<0.4; i+=0.1)
                  printf("%.1f",i);
            }
(a)0.10.20.3                 (b)Compile-Time Error                        (c)Run-Time Error       (d)No Output
Ans. (a)          
_________________________________________________________________________________________________
           
[Q022]. What will be the output of the following program :
            void main()
            {
              int i;
              for (i=-10; !i; i++);
                        printf("%d",-i);
            }
(a)0                              (b)Compile-Time Error                        (c)10                            (d)No Output
Ans. (c)          
_________________________________________________________________________________________________

[Q023]. What will be the output of the following program :
            void main()
            {
              int i=5;
              do;
                printf("%d",i--);
              while (i>0);
            }
(a)5                              (b)54321                                  (c)Compile-Time Error            (d)None of these
Ans. (c)          
_________________________________________________________________________________________________
           
[Q024]. What will be the output of the following program :
            void main()
            {
              int i;
              for (i=2,i+=2; i<=9; i+=2)
              printf("%d",i);
            }
(a)Compile-Time error (b)2468                                                (c)468                          (d)None of these
Ans. (c)          
_________________________________________________________________________________________________

[Q025]. What will be the output of the following program :
            void main()
            {
              int i=3;
              for (i--; i<7; i=7)
                 printf("%d",i++);
            }
(a)No Output              (b)3456                                                (c)23456                      (d)None of these
Ans. (d)          
_________________________________________________________________________________________________
           
[Q026]. What will be the output of the following program :
            void main()
            {
              int i;
              for (i=5; --i;)
                        printf("%d",i);
            }
(a)No Output              (b)54321                                  (c)4321                                    (d)None of these
Ans. (c)          
_________________________________________________________________________________________________

[Q027]. What will be the output of the following program :
            void main()
            {
              int choice=3;
              switch(choice)
              {
                 default:
                    printf("Default");
           
                 case 1:
                    printf("Choice1");
                    break;
           
                 case 2:
                    printf("Choice2");
                    break;
              }
            }
(a)No Output              (b)Default                               (c)DefaultChoice1      (d)None of these
Ans. (c)          
_________________________________________________________________________________________________
           
[Q028]. What will be the output of the following program :
            void main()
            {
              static int choice;
              switch(--choice,choice-1,choice-1,choice+=2)
              {
                 case 1:
                    printf("Choice1");
                    break;
           
                 case 2:
                    printf("Choice2");
                    break;

                 default:
                    printf("Default");
              }
            }
(a)Choice1                   (b)Choice2                              (c)Default                    (d)None of these
Ans. (a)          
_________________________________________________________________________________________________

[Q029]. What will be the output of the following program :
            void main()
            {
              for (;printf(""););
            }
(a)Compile-Time error (b)Executes ONLY once                    (c)Executes INFINITELY     (d)None of these
Ans. (b)          
_________________________________________________________________________________________________
           
[Q030]. What will be the output of the following program :
            void main()
            {
              int i;
              for (;(i=4)?(i-4):i++;)
                 printf("%d",i);
            }
(a)Compile-Time error (b)4                                          (c)Infinite Loop          (d)No Output
Ans. (d)          
_________________________________________________________________________________________________

[Q031]. What will be the output of the following program :
            void main()
            {
              static int j;
              for (j<5; j<5; j+=j<5)
                  printf("%d",j++);
            }
(a)024                          (b)Compile-Time Error                        (c)01234                      (d)No Output
Ans.    
_________________________________________________________________________________________________
           
[Q032]. What will be the output of the following program :
            void main()
            {
              int i=9;
              for (i--; i--; i--)
                  printf("%d ",i);
            }
(a)9 6 3                        (b)Compile-Time Error                        (c)7 5 3 1                     (d)Infinite Loop
Ans.    
_________________________________________________________________________________________________

[Q033]. What will be the output of the following program :
            void main()
            {
              int i;
              for (i=5; ++i; i-=3)
                  printf("%d ",i);
            }
(a)6 4 2                        (b)Compile-Time Error                        (c)6 3 1                        (d)Infinite Loop
Ans.    
_________________________________________________________________________________________________

[Q034]. Which of the following code causes INFINITE Loop :
(a)do while(1);                        (b)do;while(1);                                    (c)do;                           (d)do{}while(1);
                                                                                       while(1);

(i)Only (a)                   (ii)Only (b), (c) & (d)              (iii)None of these        (iv)All of these
                                                                                                                          
Ans.                            
_________________________________________________________________________________________________

[Q035]. What will be the output of the following program :
            #define Loop(i) for (j=0; j<i; j++){ \
                            sum += i+j;     \
                        }
            void main()
            {
               int i,j,sum=0;
               for (i=0; i<=3; i++)
                  Loop(i)
               printf("%d",sum);
            }

(a)Run-Time Error       (b)Compile-Time Error                        (c)18                           (d)0
Ans.    
_________________________________________________________________________________________________

(1) What will be output if you will compile and execute the following c code?
void main(){

int i=320;

char *ptr=(char *)&i;

printf("%d",*ptr);

}



(a)320

(b)1

(c)64

(d)Compiler error

(e)None of above

Output: (c)

Explanation:

As we know size of int data type is two byte while char pointer can pointer one
byte at time.

Memory representation of int i=320

So char pointer ptr is pointing to only first byte as shown above figure.

*ptr i.e. content of first byte is 01000000 and its decimal value is 64.



How to represent char, int and float data in memory?

Data type tutorial.



(2) What will be output if you will compile and execute the following c code?



#define x 5+2

void main(){

int i;

i=x*x*x;

printf("%d",i);

}

(a)343

(b)27

(c)133

(d)Compiler error

(e)None of above

Output: (b)

Explanation:

As we know #define is token pasting preprocessor it only paste the value of
micro constant in the program before the actual compilation start. If you will
see intermediate file you will find:



test.c 1:

test.c 2: void main(){

test.c 3: int i;

test.c 4: i=5+2*5+2*5+2;

test.c 5: printf("%d",i);

test.c 6: }

test.c 7:





You can absorb #define only pastes the 5+2 in place of x in program. So,

i=5+2*5+2*5+2

=5+10+10+2

=27



What is intermediate file and how to see intermediate file?

Preprocessor tutorial.



(3) What will be output if you will compile and execute the following c code?
void main(){

char c=125;

c=c+10;

printf("%d",c);

}

(a)135

(b)+INF

(c)-121

(d)-8

(e)Compiler error

Output: (c)

Explanation:

As we know char data type shows cyclic properties i.e. if you will increase or
decrease the char variables beyond its maximum or minimum value respectively it
will repeat same value according to following cyclic order:

So,

125+1= 126

125+2= 127

125+3=-128

125+4=-127

125+5=-126

125+6=-125

125+7=-124

125+8=-123

125+9=-122

125+10=-121



What is cyclic nature of data type?



Data type tutorial.

(4) What will be output if you will compile and execute the following c code?

void main(){

float a=5.2;

if(a==5.2)

printf("Equal");

else if(a<5.2)

printf("Less than");

else

printf("Greater than");

}
(a)Equal

(b)Less than

(c)Greater than

(d)Compiler error

(e)None of above

Output: (b)

Explanation:

5.2 is double constant in c. In c size of double data is 8 byte while a is float
variable. Size of float variable is 4 byte.
So double constant 5.2 is stored in memory as:

101.00 11001100 11001100 11001100 11001100 11001100 11001101

Content of variable a will store in the memory as:

101.00110 01100110 01100110

It is clear variable a is less than double constant 5.2

Since 5.2 is recurring float number so it different for float and double. Number
likes 4.5, 3.25, 5.0 will store same values in float and double data type.



Note: In memory float and double data is stored in completely different way. If
you want to see actual memory representation goes to question number (60) and
(61).

Data type tutorial.

(5) What will be output if you will compile and execute the following c code?

void main(){

int i=4,x;

x=++i + ++i + ++i;

printf("%d",x);

}

(a)21

(b)18

(c)12

(d)Compiler error

(e)None of above

Output: (a)

Explanation:

In ++a, ++ is pre increment operator. In any mathematical expression pre
increment operator first increment the variable up to break point then starts
assigning the final value to all variable.



Step 1: Increment the variable I up to break point.

Step 2: Start assigning final value 7 to all variable i in the expression.

So, i=7+7+7=21



What is break point?



Operator tutorial.



(6) What will be output if you will compile and execute the following c code?
void main(){

int a=2;

if(a==2){

a=~a+2<<1;

printf("%d",a);

}

else
{ break;

}
}

(a)It will print nothing.

(b)-3

(c)-2

(d)1

(e)Compiler error

Output: (e)

Explanation:

Keyword break is not part of if-else statement. Hence it will show compiler
error: Misplaced break

Where we can use break keyword?
Control statement tutorial

(7) What will be output if you will compile and execute the following c code?



void main(){

int a=10;

printf("%d %d %d",a,a++,++a);

}



(a)12 11 11

(b)12 10 10

(c)11 11 12

(d)10 10 12

(e)Compiler error

Output: (a)

Explanation:

In c printf function follows cdecl parameter passing scheme. In this scheme
parameter is passed from right to left direction.
So first ++a will pass and value of variable will be a=10 then a++ will pass now
value variable will be a=10 and at the end a will pass and value of a will be
a=12.

What is cedecl and pascal parameter passing convention?
Function tutorial.

(8) What will be output if you will compile and execute the following c code?



void main(){

char *str="Hello world";

printf("%d",printf("%s",str));



}



(a) 11Hello world

(b) 10Hello world

(c) Hello world10

(d) Hello world11

(e) Compiler error

Output: (d)

Explanation:

Return type of printf function is integer and value of this integer is exactly
equal to number of character including white space printf function prints. So,
printf(“Hello world”) will return 13.



What is prototype of printf function?



Formatted I/O tutorial.



(9) What will be output if you will compile and execute the following c code?



#include "stdio.h"

#include "string.h"

void main(){

char *str=NULL;

strcpy(str,"cquestionbank");

printf("%s",str);

}



(a)cquestionbank

(b)cquestionbank\0

(c)(null)

(d)It will print nothing

(e)Compiler error

Output: (c)

Explanation:

We cannot copy any thing using strcpy function to the character pointer pointing
to NULL.

String tutorial.



More questions of string.



(10) What will be output if you will compile and execute the following c code?



#include "stdio.h"

#include "string.h"

void main(){

int i=0;

for(;i<=2;)

printf(" %d",++i);

}

(a)0 1 2

(b)0 1 2 3

(c)1 2 3

(d)Compiler error

(e)Infinite loop

Output: (c)

Explanation:

In for loop each part is optional.



Complete tutorial of looping in C.



(11) What will be output if you will compile and execute the following c code?



void main(){

int x;

for(x=1;x<=5;x++);

printf("%d",x);

}



(a)4

(b)5

(c)6

(d)Compiler error

(e)None of above











Output: (c)

Explanation:

Body of for loop is optional. In this question for loop will execute until value
of variable x became six and condition became false.



Looping tutorial.



(12) What will be output if you will compile and execute the following c code?



void main(){

printf("%d",sizeof(5.2));

}



(a)2

(b)4

(c)8

(d)10

(e)Compiler error









Output: (c)

Explanation:

Default type of floating point constant is double. So 5.2 is double constant and
its size is 8 byte.



Detail explanation of all types of constant in C.



(13) What will be output if you will compile and execute the following c code?



#include "stdio.h"

#include "string.h"

void main(){

char c='\08';

printf("%d",c);

}



(a)8

(b)’8’

(c)9

(d)null

(e)Compiler error

Output: (e)

Explanation:

In c any character is starting with character ‘\’ represents octal number in
character. As we know octal digits are: 0, 1, 2, 3, 4, 5, 6, and 7. So 8 is not
an octal digit. Hence ‘\08’ is invalid octal character constant.


Octal character constantan.



Hexadecimal character constant.



(14) What will be output if you will compile and execute the following c code?

#define call(x,y) x##y

void main(){

int x=5,y=10,xy=20;

printf("%d",xy+call(x,y));

}
(a)35

(b)510

(c)15

(d)40

(e)None of above


Output: (d)

Explanation:

## is concatenation c preprocessor operator. It only concatenates the operands
i.e.

a##b=ab



If you will see intermediate file then you will find code has converted into
following intermediate code before the start of actual compilation.

Intermediate file:



test.c 1:

test.c 2: void main(){

test.c 3: int x=5,y=10,xy=20;

test.c 4: printf("%d",xy+xy);

test.c 5: }

test.c 6:



It is clear call(x, y) has replaced by xy.



What is macro call?

Preprocessor tutorial.



(15) What will be output if you will compile and execute the following c code?
int * call();

void main(){

int *ptr;

ptr=call();

clrscr();

printf("%d",*ptr);

}

int * call(){

int a=25;

a++;
return &a;
}
(a)25
(b)26
(c)Any address
(d)Garbage value
(e)Compiler error

Output: (d)

Explanation:

In this question variable a is a local variable and its scope and visibility is
within the function call. After returning the address of a by function call
variable a became dead while pointer ptr is still pointing to address of
variable a. This problem is known as dangling pointer problem.



Complete pointer tutorial.



(16) What is error in following declaration?



struct outer{

int a;

struct inner{

char c;

};

};



(a)Nesting of structure is not allowed in c.

(b)It is necessary to initialize the member variable.

(c)Inner structure must have name.

(d)Outer structure must have name.

(e)There is not any error.



Output: (c)

Explanation:

It is necessary to assign name of inner structure at the time of declaration
other wise we cannot access the member of inner structure. So correct
declaration is:



struct outer{

int a;

struct inner{

char c;

}name;

};



Structure tutorial.



Union tutorial.



(17) What will be output if you will compile and execute the following c code?



void main(){

int array[]={10,20,30,40};

printf("%d",-2[array]);

}



(a)-60

(b)-30

(c)60

(d)Garbage value

(e)Compiler error













Output: (b)

Explanation:

In c,

array[2]=*(array+2)=*(2+array)=2[array]=30



Array tutorial.



Array of pointer.



How to read complex pointers.



(18) What will be output if you will compile and execute the following c code?



void main(){

int i=10;

static int x=i;

if(x==i)

printf("Equal");

else if(x>i)

printf("Greater than");

else

printf("Less than");
}
(a)Equal

(b)Greater than

(c)Less than

(d)Compiler error

(e)None of above

Output: (d)

Explanation:

static variables are load time entity while auto variables are run time entity.
We can not initialize any load time variable by the run time variable.

In this example i is run time variable while x is load time variable.



What is storage class?



(18) What will be output if you will compile and execute the following c code?



void main(){

int i=5,j=2;

if(++i>j++||i++>j++)

printf("%d",i+j);

}



(a)7

(b)11

(c)8

(d)9

(e)Compiler error



Output: (d)

Explanation:

|| is logical OR operator. In C logical OR operator doesn’t check second operand
if first operand is true.

++i>j++ || i++>j++

First operand: ++i>j++

Second operand: i++>j++

First operand

++i > j++

=> 6 > 2

Since first operand is true so it will not check second operand.

Hence i= 6 and j=3



Properties of && operator.



Operator tutorial with examples.





(19) What will be output if you will compile and execute the following c code?



#define max 5;

void main(){

int i=0;

i=max++;

printf("%d",i++);

}



(a)5

(b)6

(c)7

(d)0

(e)Compiler error

Output: (e)

Explanation:

#define is token pasting preprocessor. If you will see intermediate file: test.i



test.c 1:

test.c 2: void main(){

test.c 3: int i=0;

test.c 4: i=5++;

test.c 5: printf("%d",i++);

test.c 6: }

test.c 7:



It is clear macro constant max has replaced by 5. It is illegal to increment the
constant number. Hence compiler will show Lvalue required.





What is Lvalue and Rvalue?



How to see intermediate file?



Preprocessor questions and answer.



(20) What will be output if you will compile and execute the following c code?



void main(){

double far* p,q;

printf("%d",sizeof(p)+sizeof q);

}



(a)12

(b)8

(c)4

(d)1

(e)Compiler error









Output: (a)

Explanation:

It is clear p is far pointer and size of far pointer is 4 byte while q is double
variable and size of double variable is 8 byte.



What is near pointer?



What is far pointer?



What is huge pointer?



Complete pointer tutorial.



(21) What will be output if you will compile and execute the following c code?



void main(){

int a=5;

float b;

printf("%d",sizeof(++a+b));

printf(" %d",a);

}



(a)2 6

(b)4 6

(c)2 5

(d)4 5

(e)Compiler error

Output: (d)

Explanation:

++a +b

=6 + Garbage floating point number

=Garbage floating point number

//From the rule of automatic type conversion

Hence sizeof operator will return 4 because size of float data type in c is 4
byte.

Value of any variable doesn’t modify inside sizeof operator. Hence value of
variable a will remain 5.



Properties of sizeof operator.



Operators tutorial



(22) What will be output if you will compile and execute the following c code?

void main(){

char huge *p=(char *)0XC0563331;

char huge *q=(char *)0XC2551341;

if(p==q)

printf("Equal");

else if(p>q)

printf("Greater than");

else

printf("Less than");

}
(a)Equal

(b)Greater than

(c)Less than

(d)Compiler error

(e)None of above











Output: (a)

Explanation:

As we know huge pointers compare its physical address.

Physical address of huge pointer p



Huge address: 0XC0563331

Offset address: 0x3331

Segment address: 0XC056



Physical address= Segment address * 0X10 + Offset address

=0XC056 * 0X10 +0X3331

=0XC0560 + 0X3331

=0XC3891



Physical address of huge pointer q



Huge address: 0XC2551341

Offset address: 0x1341

Segment address: 0XC255



Physical address= Segment address * 0X10 + Offset address

=0XC255 * 0X10 +0X1341

=0XC2550 + 0X1341

=0XC3891



Since both huge pointers p and q are pointing same physical address so if
condition will true.


1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java EE Online Training from India . Nowadays Java has tons of job opportunities on various vertical industry.



    Java Online Training

    ReplyDelete