Give the output of the programs in each case unless mentioned otherwise

wheatauditorΛογισμικό & κατασκευή λογ/κού

30 Οκτ 2013 (πριν από 3 χρόνια και 11 μήνες)

430 εμφανίσεις

Give the output of the programs in each case unless mentioned otherwise


1.

void main()

{



int d=5;



printf("%f",d);

}
Ans: Undefined

2.

void main()

{



int i;



for(i=1;i<4,i++)




















































































switch(i)



case 1: printf("%d",i);break;

{


case 2:printf("%d",i);break;


case 3:printf("%d",i);break;

}


switch(i) case 4:printf("%d",i);

}
Ans: 1,2,3,4

3.

void main()

{


char *s="
\
12345s
\
n";


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

}
Ans: 6

4.

void main()

{



unsigned i=1; /
* unsigned char k=
-
1 => k=255; */



signed j=
-
1; /* char k=
-
1 => k=65535 */

/* unsigned or signed int k=
-
1 =>k=65535 */



































if(i<j)



printf("less");

else

if(i>j)



printf("greater");

else

if(i==j)



printf("equal");

}
Ans:
less

5.

void main()

{



float j;



j=1000*1000;



printf("%f",j);

}


1. 1000000

2. Overflow

3. Error

4. None

Ans: 4

6.

How do you declare an array of N pointers to functions returning


pointers to functions
returning pointers to characters?





Ans: The first pa
rt of this question can be answered in at
least








three ways:

7.

Build the declaration up incrementally, using typedefs:









typedef char *pc;




/* pointer to char */









typedef pc fpc();




/* function returning pointer to char */









type
def fpc *pfpc;




/* pointer to above */









typedef pfpc fpfpc();




/* function returning... */









typedef fpfpc *pfpfpc;




/* pointer to... */









pfpfpc a[N];








/* array of... */

8.

Use the cdecl program, which turns English into C and

vice versa:



















cdecl> declare a as array of pointer to function returning


pointer to function returning
pointer to char








char *(*(*a[])())()

cdecl can also explain complicated declarations, help with


casts, and indicate which set o
f
parentheses the arguments



go in (for complicated function definitions, like the
one



above).


Any good book on C should explain how to read these complicated



C
declarations "inside out" to understand them ("declaration mimics use"). The pointer
-
to
-
f
unction declarations in the examples above have not included parameter type information.
When the parameters have complicated types, declarations can *really* get messy. (Modern
versions of cdecl can help here, too.)

9.

A structure pointer is defined of the t
ype time . With 3 fields min,sec hours having
pointers to intergers.





Write the way to initialize the 2nd element to 10.

10.

In the above question an array of pointers is declared. Write the statement to initialize
the 3rd element of the 2 element to 10

11.

int

f()

void main()

{



f(1);



f(1,2);



f(1,2,3);

}

f(int i,int j,int k)

{



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

}What are the number of syntax errors in the above?






















Ans: None.

12.

void main()

{



int i=7;



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

}
Ans: 56

13.

#define one
0

#ifdef one

printf("one is defined ");

#ifndef one

printf("one is not defined ");

Ans: "one is defined"

14.

void main()

{



intcount=10,*temp,sum=0;



temp=&count;



*temp=20;



temp=&sum;



*temp=count;



printf("%d %d %d ",count,*temp,sum);

}

Ans: 20 20 20

15.

There was question in c working only on unix machine with pattern matching.

16.

what is alloca()



Ans : It allocates and frees memory after use/after getting out of
scope

17.

main()

{



static i=3;



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



return i>0 ? main():0;

}

Ans: 321

18.

char *fo
o()

{



char result[100]);



strcpy(result,"anything is good");











































return(result);

}

void main()

{



char *j;



j=foo()



printf("%s",j);

}

Ans: anything is good.

19.

void main()

{



char *s[]={ "dharma","hewlett
-
packard"
,"siemens","ibm"};



char **p;



p=s;



printf("%s",++*p);



printf("%s",*p++);



printf("%s",++*p);

}
Ans: "harma" (p
-
>add(dharma) && (*p)
-
>harma)

"harma" (after printing, p
-
>add(hewlett
-
packard) &&(*p)
-
>harma)

"ewlett
-
packard"



Mistral Solutions

C
Section


1. What does the following program print?

#include <stio.h>


int sum,count;

void main(void)

{< BR> for(count=5;sum+=
--
count;)

printf("%d",sum);

}

a. The pgm goes to an infinite loop b. Prints 4791010974 c. Prints 4791001974

d. Prints 5802112085 e.

Not sure


2. What is the output of the following program?

#include <stdio.h>

void main(void)

{

int i;< BR> for(i=2;i<=7;i++)

printf("%5d",fno());

}

fno()

{

staticintf1=1,f2=1,f3;

return(f3=f1+f2,f1=f2,f2=f3);

}

a. produce syntax errors b. 2 3 5 8 13 21 wi
ll be displayed c. 2 2 2 2 2 2 will be displayed

d. none of the above e. Not sure


3. What is the output of the following program?

#include <stdio.h>

void main (void)

{

int x = 0x1234;

int y = 0x5678;

x = x & 0x5678;

y = y | 0x1234;

x = x^y;

printf("%x
\
t",
x);

x = x | 0x5678;

y = y & 0x1234;

y = y^x;

printf("%x
\
t",y);


}

a. bbb3 bbb7 b. bbb7 bbb3 c. 444c 4448

d. 4448 444c e. Not sure


4. What does the following program print?

#include <stdio.h>

void main (void)

{

int x;

x = 0;

if (x=0)

printf ("Value of x is

0");

else

printf ("Value of x is not 0");

}


a. print value of x is 0 b. print value of x is not 0 c. does not print anything on the screen

d. there is a syntax error in the if statement e. Not sure


5. What is the output of the following program?


#inclu
de <stdio.h>

#include <string.h>


int foo(char *);

void main (void)

{

char arr[100] = {"Welcome to Mistral"};

foo (arr);

}


foo (char *x)


{

printf ("%d
\
t",strlen (x));

printf ("%d
\
t",sizeof(x));

return0;

}


a. 100 100 b. 18 100 c. 18 18 d. 18 2 e. Not sur
e


6. What is the output of the following program?


#include <stdio.h>


display()

{

printf ("
\
n Hello World");

return 0;

}


void main (void)

{

int (* func_ptr) ();

func_ptr = display;

printf ("
\
n %u",func_ptr);

(* func_ptr) ();


}


a. it prints the address

of the function display and prints Hello World on the screen

b. it prints Hello World two times on the screen

c. it prints only the address of the fuction display on the screen


d. there is an error in the program e. Not sure


7. What is the output of the

following program?

#include <stdio.h>

void main (void)

{

int i = 0;

char ch = 'A';

do


putchar (ch);

while(i++ < 5 || ++ch <= 'F');

}

a. ABCDEF will be displayed b. AAAAAABCDEF will displayed


c. character 'A' will be displayed infinitely d. none e. Not s
ure


8. What is the output of the following program?


#include <stdio.h>

#define sum (a,b,c) a+b+c

#define avg (a,b,c) sum(a,b,c)/3

#define geq (a,b,c) avg(a,b,c) >= 60

#define lee (a,b,c) avg(a,b,c) <= 60

#define des (a,b,c,d) (d==1?geq(a,b,c):lee(a,b,c))


void main (void)

{

int num = 70;

char ch = '0';

float f = 2.0;

if des(num,ch,f,0) puts ("lee..");

else puts("geq...");

}


a. syntax error b. geq... will be displayed c. lee.. will be displayed

d. none e. Not sure


9. Which of the following statement is c
orrect?


a. sizeof('*') is equal to sizeof(int) b. sizeof('*') is equal to sizeof(char)

c. sizeof('*') is equal to sizeof(double) d. none e. Not sure


10. What does the following program print?


#include <stdio.h>

char *rev(int val);


void main(void)

{

ext
ern char dec[];

printf ("%c", *rev);

}

char *rev (int val)

{

char dec[]="abcde";

return dec;

}

a. prints abcde b. prints the address of the array dec

c. prints garbage, address of the local variable should not returned d. print a e. Not sure


11. What does

the following program print?


void main(void)

{

int i;

static int k;

if(k=='0')

printf("one");

else if(k== 48)

printf("two");

else

printf("three");

}

a. prints one b. prints two c. prints three

d. prints one three e. Not sure


12. What does the following
program print?


#include<stdio.h>


void main(void)

{

enum sub

{

chemistry, maths, physics

};

struct result

{

char name[30];

enum sub sc;

};

struct result my_res;

strcpy (my_res.name,"Patrick");

my_res.sc=physics;

printf("name: %s
\
n",my_res.name);

printf("p
ass in subject: %d
\
n",my_res.sc);

}


a. name: Patrick b. name: Patrick c. name: Patrick

pass in subject: 2 pass in subject:3 pass in subject:0

d. gives compilation errors e. Not sure


13. What does


printf("%s",_FILE_); and printf("%d",_LINE_); do?


a. the

first printf prints the name of the file and the second printf prints the line no: of the second
printf in the file

b. _FILE_ and _LINE_ are not valid parameters to printf function

c. linker errors will be generated d. compiler errors will be generated e.

Not sure


14. What is the output of the following program?


#include <stdio.h>

void swap (int x, int y, int t)

{

t = x;

x = y;

y = t;

printf ("x inside swap: %d
\
t y inside swap : %d
\
n",x,y);

}


void main(void)

{

int x;

int y;

int t;

x = 99;

y = 100;

swap
(x,y,t);

printf ("x inside main:%d
\
t y inside main: %d",x,y);

}


a. x inside swap : 100 y inside swap : 99 x inside main : 100 y inside main : 99

b. x inside swap : 100 y inside swap : 99 x inside main : 99 y inside main : 100

c. x inside swap : 99 y insid
e swap : 100 x inside main : 99 y inside main : 100

d. x inside swap : 99 y inside swap : 100 x inside main : 100 y inside main : 99

e. Not sure


15. Consider the following statements:


i) " while loop " is top tested loop ii) " for loop " is bottom tested

loop

iii) " do
-

while loop" is top tested loop iv) " while loop" and "do
-

while loop " are top tested loops.

Which among the above statements are false?


a. i only b. i & ii c. iii & i d. ii, iii & iv e. Not sure


16. Consider the following piece of cod
e:


char *p = "MISTRAL";

printf ("%c
\
t", *(++p));

p
-
=1;

printf ("%c
\
t", *(p++));


Now, what does the two printf's display?


a. M M b. M I c. I M d. M S e. Not sure



17. What does the following program print?


#include <stdio.h>

struct my_struct

{

int p:1
;

int q:1;

int r:6;

int s:2;

};


struct my_struct bigstruct;


struct my_struct1

{

char m:1;

};


struct my_struct1 small struct;


void main (void)

{

printf ("%d %d
\
n",sizeof (bigstruct),sizeof (smallstruct));

}


a. 10 1 b. 2 2 c. 2 1 d. 1 1 e. Not sure


18.

Consider the following piece of code:


FILE *fp;

fp = fopen("myfile.dat","r");


Now fp points to


a. the first character in the file.

b. a structure which contains a char pointer which points to the first character in the file.

c. the name of the file. d.

none of the above. e. Not sure.


19. What does the following program print?


#include <stdio.h>

#define SQR (x) (x*x)


void main(void)

{

int a,b=3;

a = SQR (b+2);

}

a. 25 b. 11 c. 17 d. 21 e. Not sure.


20. What does the declaration do?


int (*mist) (void

*, void *);

a. declares mist as a function that takes two void * arguments and returns a pointer to an int.

b. declares mist as a pointer to a function that has two void * arguments and returns an int.

c. declares mist as a function that takes two void *
arguments and returns an int.

d. there is a syntax error in the declaration. e. Not sure.



21. What does the following program print?


#include <stdio.h>

void main (void)

{

int mat [5][5],i,j;

int *p;

p = & mat [0][0];


for (i=0;i<5;i++)

for (j=0;j<5;j++)


mat[i][j] = i+j;

printf ("%d
\
t", sizeof(mat)); < BR> i=4;j=5;

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

}


a. 25 9 b. 25 5 c. 50 9 d. 50 5 e. Not sure


22. What is the output of the following program?


#include <stdio.h>

void main (void)

{

short x = 0x3333;

short y = 0x4
321;

long z = x;


z = z << 16;

z = z | y;

printf("%1x
\
t",z);


z = y;

z = z >> 16;

z = z | x;

printf("%1x
\
t",z);


z = x;

y = x && y;

z = y;

printf("%1x
\
t",z);


}


a. 43213333 3333 1 b. 33334321 4321 4321 c. 33334321 3333 1

d. 43213333 4321 4321 e. Not sure


23. What is the output of the following program?


#include <stdio.h>

void main (void)

{

char *p = "Bangalore";

#if 0

printf ("%s", p);

#endif

}


a. syntax error #if cannot be used inside main function b. prints Bangalore on the screen

c. does not print an
ything on the screen

d. program gives an error "undefined symbol if" e. Not sure


24. If x is declared as an integer, y is declared as float, consider the following expression:

y = *(float *)&x;


Which one of the following statments is true?


a. the progra
m containing the expression produces compilation errors;

b. the program containing the expression produces runtime errors;

c. the program containing the expression compiles and runs without any errors;

d. none of the above e. Not sure


25. What is the retu
rn type of calloc function?


a. int * b. void * c. no return type: return type is void

d. int e. Not sure



part 1 of paper




first aptitude having five sections (50 questions and 45 minutes)



part 2


second c debugging (test ur c skills
-

yashwant kanit
kar)(questions 20 time 30 min.)



paper 1



section one



15 questions (data sufficiency)


a alone is sufficient


b alone is sufficient


a and b are both sufficient


a and b both are insufficient



section two



five questions (reading comprehence )


very
easy



section three



15 questions (logical reasoning)


a pare is given and some hints are given u can fine


out the ans



one hotel has two zones (east and west)


not all east zone flats have ocean view but all weat zone
flats have harbour view


all ocea
n view flats has extra charge in harbour view flats above and on 3rd
floor have extra charge west zone flats lower than 3rd floor some has kitchen so extra charge all other
flats of east zone not having ocean view has kitchen so extra charges





section f
our



10 questions verbal reasoning four or five sentences are given related to single topic


four options are
given which are having order of


three sentences(abe or bec)


select correct order



sections five



five computational questions which were easy



* total 12 members half are in club a one third in b and one fourth in c how many are not in any club


ans 5(check)



these type of questions u can find in


R. S. Agrawal


or IMS package of CAT



in question it was written that all five sections carry t
heir cutoffs so attempt all but in electrical one
guy was selected who didnot attempt reading comprehension but attempted all 45 questions this
paper also has negative marking of 50%



paper 2



1.what does p in


const char *p


stands for


p can be changed

like this



2.main()


sturct date {


char name[20];


int age ;


float sal;


};


sturct data d ={"rajesh"};


printf("%d%f",d.age,d.sal);


}


tell the output



3.main()


int i=7;


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


output



4.void main()


{


int d ;


int i=10;


d =sizeo
f(++i);


printf("%d");


output



5.difference between


extern int f();


int f();



6.choose correct


(i)stack is automatically cleared


(ii)heap is automatically cleared


(iii)user has to clear stack and heap


(iv)system takes care of
----------



7. What'
ll be the output:


main()


{char *a,*f();


a=f();


printf("%s",a);


}


char *f()


{return("Hello World");



8.What'll be the output:


main()


{char*a,*f();


a=char*malloc(20*sizeof(char));


a=f();


printf("%s",a);


}


char *f()


{char n[20];


strcpy(n,"Hel
lo World");


return(n);


}


9.What is the error :


main()


{int j=10;


switch(j)


{ case 20:


pritnf("Less than 20");


break;


case 30:


printf("Less than 30");


break;


default:


printf("hello");


}



10.which is valid :


(i)char arr[10];


arr="hello";


(
ii) char arr[]="hello";



11.


main()


{


char *str;


str=char*malloc(20*sizeof(char));


strcpy(str,"test");


strcat(str,'!');


printf("%s",str);


}



12. How many times main is get called :


main()


{


printf("Jumboree");


main();


}


ans: till stack over
flow.



13. Which statement is true about main :


(i) Varible no. of Arguments can be passed main.


(ii) Main can be called from main();


(iii) We can't pass arguments are passed in main


(iv) main always returns an int



14. Output ?


main()


{


int i,j;


for(i=0,j=0;i<5,j<25;i++,j++);


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


}



15.main()


{


int i;


if(i=0) //it's assisnment not logical operator


printf(" Hell ");


else


printf("Heaven");


like this


no negative marking and more than one answers but paper I is cutoff pape
r i think c paper will not be
checked





Interview



they will give u puzzles in first round which will be from site techinterview.org this site has 70 puzzles
and their answers so go through them



second round has c coding of data structure circular que
se,tree etc also questions from c and c++ like
virtual functions


far near huge memory concepts like heap,stack etc



then in third round hr questions like hobbies and interets make ur curriculam vite and bring it with ur
file



they want people with good
aptitude in interview rounds ur aptitude and approach matters so solve
puzzles.






Ubinetics Test Pattern
-

July 2003


20 c objective Qs to be answered in 30 minutes


All questions

are related to basic c concepts like expression, arrays, loops ,structure

, pointers around
3 or 4 qs on array with loops



Since paper is very easy cutoff is very high.

They will select 20% of the student for the interview after written test. Freshersworld.com


point to remember.

Each correct ans 1 marks

Each wrong answer 1
-
v
e mark



Sample Paper













Some of the questions will not have answers .Please forgive us.




1. Difference b/n scanf("%s",msg);and scanf("%[
\
^n]",msg); where msg is a char array.


2. What is ure of comma operator in for loop.

3. int shw(int *a){


*
a = 10;


/* return stmt is missing */

}












main(){




int p=3,q=4;




q = shw(&p);




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












}




4. which is true




a. all automatic variables are declared with in the function



b. all variables are automatic




c. a
ll not declared variables are automatic




d. none



5. What is recursion. Recursive prog to generate Fibonacci series . Is it a best method?



6. write 7*a interms of +,
-
,<<



7. count number of 1's in a 32 bit integer.(i had not remembered whether ar
ray or integer).


8. main(){

char *s1 = "hello",*s2 ="abce";

strcpy(s1,"");














s2[0] = s1[0];



printf("%d%d",strlen(s1),strlen(s2));


}


9. regarding memset



10.Algorithm to delete a node in Double linked list.



11. Difference b/n fgets,fsc
anf which u will prefer.









Unix

11.What is creon and whats diff b/n 'at' command.



12. what is system call and lib function. whats diff b/n them. abt execve
-

expalin.



13.some thing abt makeall



14. write abt TCP,IP,ICMP




TEXAS INSTRUMENTS
PAPER
-

08 SEP 2005

Test Paper



01

1. Can we declare a static function as virtual?

Ans: No. The virtual function mechanism is used on the specific object that determines which virtual
function to call. Since the static functions are not any way related to

objects, they cannot be declared
as virtual.

2. Can user
-
defined object be declared as static data member of another class?

Ans: Yes. The following code shows how to initialize a user
-
defined object.







#include







class test







{







int i ;







public :







test ( int ii = 0 )







{







i = ii ;







}







} ;







class sample







{







static test s ;







} ;







test sample::s ( 26 ) ;

Here we have initialized the object s by calling the one
-
argument constructor. We

can
use the same convention to initialize the object by calling multiple
-
argument constructor.

3. What is forward referencing and when should it be used?

Ans: Consider the following program:






class test







{







public :







friend void fun ( sample
, test ) ;







} ;







class sample







{







public :







friend void fun ( sample, test ) ;







} ;







void fun ( sample s, test t )







{







// code







}







void main( )







{







sample s ;







test t ;







fun ( s, t
) ;







}

This program would not compile. It gives an error that sample is undeclared identifier in the statement
friend void fun ( sample, test ) ; of the class test. This is so because the class sample is defined below
the class test and we are using i
t before its definition. To overcome this error we need to give forward
reference of the class sample before the definition of class test. The following statement is the forward
reference of class sample. Forward referencing is generally required when we m
ake a class or a
function as a friend.

4. The istream_withassign class has been derived from the istream class and overloaded assignment
operator has been added to it. The _withassign classes are much like their base classes except that
they include overlo
aded assignment operators. Using these operators the objects of the _withassign
classes can be copied. The istream, ostream, and iostream classes are made uncopyable by making
their overloaded copy constructor and assignment operators private.

5. How do I
write my own zero
-
argument manipulator that should work same as hex?

Ans: This is shown in following program.







#include







ostream& myhex ( ostream &o )







{







o.setf ( ios::hex) ;







return o ;







}







void main( )







{







co
ut << endl << myhex << 2000 ;







}

6.We all know that a const variable needs to be initialized at the time of declaration. Then how come
the program given below runs properly even when we have not initialized p?







#include







void main( )







{







const char *p ;







p = "A const pointer" ;







cout << p ;







}

Ans: The output of the above program is 'A const pointer'. This is because in this program p is
declared as 'const char*' which means that value stored at p will be constant and

not p and so the
program works properly

7. How do I refer to a name of class or function that is defined within a namespace?

Ans: There are two ways in which we can refer to a name of class or function that is defined within a
namespace: Using scope resol
ution operator through the using keyword. This is shown in following
example:







namespace name1






{







class sample1







{







// code







} ;







}







namespace name2







{







class sample2







{







// code







} ;







}







using namespace name2 ;







void main( )







{







name1::sample1 s1 ;







sample2 s2 ;







}

Here, class sample1 is referred using the scope resolution operator. On the other hand we can directly
refer to class sample2 because of the stat
ement using namespace name2 ; the using keyword
declares all the names in the namespace to be in the current scope. So we can use the names without
any qualifiers.

8. While overloading a binary operator can we provide default values?

Ans: No!. This is beca
use even if we provide the default arguments to the parameters of the
overloaded operator function we would end up using the binary operator incorrectly. This is explained
in the following example:







sample operator + ( sample a, sample b = sample (2,
3.5f ) )







{







}







void main( )







{







sample s1, s2, s3 ;







s3 = s1 + ; // error







}

9. How do I carry out conversion of one object of user
-
defined type to another?

Ans: To perform conversion from one user
-
defined type to anothe
r we need to provide conversion
function. Following program demonstrates how to provide such conversion function.







class circle







{







private :







int radius ;







public:







circle ( int r = 0 )







{







radius = r ;







}







} ;







class rectangle







{







private :







int length, breadth ;







public :







rectangle( int l, int b )







{







length = l ;







breadth = b ;







}







operator circle( )







{







return circle ( length ) ;







}







} ;







void main( )







{







rectangle r ( 20, 10 ) ;







circle c;







c = r ;







}

Here, when the statement c = r ; is executed the compiler searches for an overloaded assignment
operator in the class circle which accepts the object
of type rectangle. Since there is no such
overloaded assignment operator, the conversion operator function that converts the rectangle object
to the circle object is searched in the rectangle class. We have provided such a conversion function in
the rectan
gle class. This conversion operator function returns a circle object. By default conversion
operators have the name and return type same as the object type to which it converts to. Here the
type of the object is circle and hence the name of the operator fu
nction as well as the return type is
circle.

10. How do I write code that allows to create only one instance of a class?

Ans: This is shown in following code snippet.







#include







class sample







{







static sample *ptr ;







private:







sample( )







{







}







public:







static sample* create( )







{







if ( ptr == NULL )







ptr = new sample ;







return ptr ;







}







} ;







sample *sample::ptr = NULL ;







void main( )







{







sample *a = sample::c
reate( ) ;







sample *b = sample::create( ) ;







}

Here, the class sample contains a static data member ptr, which is a pointer

to the object of same class. The constructor is private which avoids us from creating objects outside
the class. A static
member function called create( ) is used to create an object of the class. In this
function the condition is checked whether or not ptr is NULL, if it is then an object is created
dynamically and its address collected in ptr is returned. If ptr is not NULL
, then the same address is
returned. Thus, in main( ) on execution of the first statement one object of sample gets created
whereas on execution of second statement, b holds the address of the first object. Thus, whatever
number of times you call create( )

function, only one object of sample class will be available.

11. How do I write code to add functions, which would work as get and put properties of a class?

Ans: This is shown in following code.







#include







class sample







{







int data ;







public:







__declspec ( property ( put = fun1, get = fun2 ) )







int x ;







void fun1 ( int i )







{







if ( i < 0 )







data = 0 ;







else







data = i ;







}







int fun2( )







{







return data ;







}







} ;







void main( )







{







sample a ;







a.x =
-
99 ;







cout << a.x ;







}

Here, the function fun1( ) of class sample is used to set the given integer value into data, whereas
fun2( ) returns the current value of data. To set these functions
as properties of a class we have given
the statement as shown below:

__declspec ( property ( put = fun1, get = fun2 )) int x ;

As a result, the statement a.x =
-
99 ; would cause fun1( ) to get called to set the value in data. On
the other hand, the last
statement would cause fun2( ) to get called to return the value of data.

12. How do I write code to make an object work like a 2
-
D array?

Ans: Take a look at the following program.







#include







class emp







{







public :







int a[3][3] ;







emp( )







{







int c = 1 ;







for ( int i = 0 ; i <= 2 ; i++ )







{







for ( int j = 0 ; j <= 2 ; j++ )







{







a[i][j] = c ;







c++ ;







}







}







}







int* operator[] ( int i )







{







return a[i] ;







}







} ;







void main( )







{







emp e ;







cout << e[0][1] ;







}

The class emp has an overloaded operator [ ] function. It takes one argument an integer representing
an array index and returns an int pointer. The statement cout << e[0][1]

; would get converted into a
call to the overloaded [ ] function as e.operator[ ] ( 0 ). 0 would get collected in i. The function would
return a[i] that represents the base address of the zeroeth row. Next the statement would get
expanded as base address
of zeroeth row[1] that can be further expanded as *( base address + 1 ).
This gives us a value in zeroth row and first column.

13. What are formatting flags in ios class?

Ans: The ios class contains formatting flags that help users to format the stream dat
a. Formatting
flags are a set of enum definitions. There are two types of formatting flags:







On/Off flags







Flags that work in
-
group

The On/Off flags are turned on using the setf( ) function and are turned off using the unsetf( )
function. To set
the On/Off flags, the one argument setf( ) function is used. The flags working in
groups are set through the two
-
argument setf( ) function. For example, to left justify a string we can
set the flag as,







cout.setf ( ios::left ) ;







cout << "KICIT N
agpur" ;







To remove the left justification for subsequent output we can say,







cout.unsetf ( ios::left ) ;

The flags that can be set/unset include skipws, showbase, showpoint,

uppercase, showpos, unitbuf and stdio. The flags that work in a group c
an have only one of these flags
set at a time.

14. What is the purpose of ios::basefield in the following statement?







cout.setf ( ios::hex, ios::basefield ) ;

Ans: This is an example of formatting flags that work in a group. There is a flag for each n
umbering
system (base) like decimal, octal and hexadecimal. Collectively, these flags are referred to as
basefield and are specified by ios::basefield flag. We can have only one of these flags on at a time. If
we set the hex flag as setf ( ios::hex ) then
we will set the hex bit but we won't clear the dec bit
resulting in undefined behavior. The solution is to call setf( ) as setf ( ios::hex, ios::basefield ). This
call first clears all the bits and then sets the hex bit.

15. Can we get the value of ios for
mat flags?

Ans: Yes! The ios::flags( ) member function gives the value format flags. This function takes no
arguments and returns a long ( typedefed to fmtflags) that contains the current format flags.

16. Is there any function that can skip certain number

of characters present in the input stream?

Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this function is as shown
below:







istream& ignore ( int n = 1, int d =EOF ) ;

Sometimes it happens that some extra characters are le
ft in the input stream while taking the input
such as, the ?
\
n? (Enter) character. This extra character is then passed to the next input and may
pose problem.

To get rid of such extra characters the cin::ignore( ) function is used. This is equivalent to ff
lush (
stdin ) used in C language. This function ignores the first n characters (if present) in the input stream,
stops if delimiter d is encountered.

17. Write a program that implements a date class containing day, month and year as data members.
Implemen
t assignment operator and copy constructor in this class.

Ans: This is shown in following program:







#include







class date







{







private :







int day ;







int month ;







int year ;







public :







date ( int d = 0, int m = 0,
int y = 0 )







{







day = d ;







month = m ;







year = y ;







}







// copy constructor







date ( date &d )







{







day = d.day ;







month = d.month ;







year = d.year ;







}







// an overloaded assignment operator







date operator = ( date d )







{







day = d.day ;







month = d.month ;







year = d.year ;







return d ;







}







void display( )







{







cout << day << "/" << month << "/" << year ;







}







} ;







void main( )







{







date d1 ( 25, 9, 1979 ) ;







date d2 = d1 ;







date d3 ;







d3 = d2 ;







d3.display( ) ;







}

18. When should I use unitbuf flag?

Ans: The unit buffering (unitbuf) flag should be turned on when we want to ensure that each character
is o
utput as soon as it is inserted into an output stream. The same can be done using unbuffered
output but unit buffering provides a better performance than the unbuffered output.

19.What are manipulators?

Ans: Manipulators are the instructions to the output
stream to modify the output in various ways. The
manipulators provide a clean and easy way for formatted output in comparison to the formatting flags
of the ios class. When manipulators are used, the formatting instructions are inserted directly into the
s
tream. Manipulators are of two types, those that take an argument and those that don?t.

20. What is the difference between the manipulator and setf( ) function?

Ans: The difference between the manipulator and setf( ) function are as follows:

The setf( ) fu
nction is used to set the flags of the ios but manipulators directly insert the formatting
instructions into the stream. We can create user
-
defined manipulators but setf( ) function uses data
members of ios class only. The flags put on through the setf( )
function can be put off through unsetf(
) function. Such flexibility is not available with manipulators.

21. How do I get the current position of the file pointer?

Ans: We can get the current position of the file pointer by using the tellp( ) member functi
on of
ostream class or tellg( ) member function of istream class. These functions return (in bytes) positions
of put pointer and get pointer respectively.

22. What are put and get pointers?

Ans: These are the long integers associated with the streams. The
value present in the put pointer
specifies the byte number in the file from where next write would take place in the file. The get pointer
specifies the byte number in the file from where the next reading should take place.

23. What do the nocreate and nor
eplace flag ensure when they are used for opening a file?

Ans: nocreate and noreplace are file
-
opening modes. A bit in the ios class defines these modes. The
flag nocreate ensures that the file must exist before opening it. On the other hand the flag norep
lace
ensures that while opening a file for output it does not get overwritten with new one unless ate or app
is set. When the app flag is set then whatever we write gets appended to the existing file. When ate
flag is set we can start reading or writing at

the end of existing file.

24. What is the limitation of cin while taking input for character array?

Ans: To understand this consider following statements,







char str[5] ;







cin >> str ;

While entering the value for str if we enter more than 5 char
acters then there is no provision in cin to
check the array bounds. If the array overflows, it may be dangerous. This can be avoided by using
get( ) function. For example, consider following statement,







cin.get ( str, 5 ) ;

On executing this statement

if we enter more than 5 characters, then get( ) takes only first five
characters and ignores rest of the characters. Some more variations of get( ) are available, such as
shown below:







get ( ch ) ? Extracts one character only







get ( str, n ) ? E
xtracts up to n characters into str







get ( str, DELIM ) ? Extracts characters into array str until specified delimiter (such as '
\
n').
Leaves delimiting character in stream.







get ( str, n, DELIM ) ? Extracts characters into array str until n char
acters or DELIM character,
leaving delimiting character in stream.

25. What is the purpose of istream class?

Ans: The istream class performs activities specific to input. It is derived from the ios class. The most
commonly used member function of this cla
ss is the overloaded >> operator which can extract values
of all basic types. We can extract even a string using this operator.

26. Would the following code work?







#include







void main( )







{







ostream o ;







o << "Dream. Then make it h
appen!" ;







}

Ans: No! This is because we cannot create an object of the ostream class since its constructor and
copy constructor are declared private.

27. Can we use this pointer inside static member function?

Ans: No! The this pointer cannot be used
inside a static member function. This is because a static
member function is never called through an object.

28. What is strstream?

Ans: strstream is a type of input/output stream that works with the memory. It allows using section of
the memory as a strea
m object. These streams provide the classes that can be used for storing the
stream of bytes into memory. For example, we can store integers, floats and strings as a stream of
bytes. There are several classes that implement this in
-
memory formatting. The c
lass ostrstream
derived from ostream is used when output is to be sent to memory, the class istrstream derived from
istream is used when input is taken from memory and strstream class derived from iostream is used
for memory objects that do both input and
output.


Ans: When we want to retrieve the streams of
bytes from memory we can use istrestream. The following example shows the use of istrstream class.







#include







void main( )







{







int age ;







float salary ;







char name[50] ;







char str[] = "22 12004.50 K. Vishwanatth" ;







istrstream s ( str ) ;







s >> age >> salary >> name ;







cout << age << endl << salary << endl << name ;







cout << endl << s.rdbuf( ) ;







}

Here, s is the object of the class istrstream.
When we are creating the object s, the constructor of
istrstream gets called that receives a pointer to the zero terminated character array str. The
statement s >> age >> salary >> name ; extracts the age, salary and the name from the istrstream
object s.
However, while extracting the name, only the first word of name gets extracted. The balance
is extracted using rdbuf( ).

29. When the constructor of a base class calls a virtual function, why doesn't the override function of
the derived class gets called?

Ans: While building an object of a derived class first the constructor of the base class and then the
constructor of the derived class gets called. The object is said an immature object at the stage when
the constructor of base class is called. This object

will be called a matured object after the execution
of the constructor of the derived class. Thus, if we call a virtual function when an object is still
immature, obviously, the virtual function of the base class would get called. This is illustrated in t
he
following example.







#include







class base







{







protected :







int i ;







public :







base ( int ii = 0 )







{







i = ii ;







show( ) ;







}







virtual void show( )







{







cout << "base's show( )" << endl
;







}







} ;







class derived : public base







{







private :







int j ;







public :







derived ( int ii, int jj = 0 ) : base ( ii )







{







j = jj ;







show( ) ;







}







void show( )







{







cout << "derived's

show( )" << endl ;







}







} ;







void main( )







{







derived dobj ( 20, 5 ) ;







}







The output of this program would be:







base's show( )







derived's show( )

30. Can I have a reference as a data member of a class? If yes,
then how do I initialise it?

Ans: Yes, we can have a reference as a data member of a class. A reference as a data member of a
class is initialized in the initialization list of the constructor. This is shown in following program.







#include







class

sample







{







private :







int& i ;







public :







sample ( int& ii ) : i ( ii )







{







}







void show( )







{







cout << i << endl ;







}







} ;







void main( )







{







int j = 10 ;







sample s ( j ) ;







s.show( ) ;







}

Here, i refers to a variable j allocated on the stack. A point to note here is that we cannot bind a
reference to an object passed to the constructor as a value. If we do so, then the reference i would
refer to the function paramete
r (i.e. parameter ii in the constructor), which would disappear as soon
as the function returns, thereby creating a situation of dangling reference.

31. Why does the following code fail?







#include







class sample







{







private :







char
*str ;







public :







sample ( char *s )







{







strcpy ( str, s ) ;







}







~sample( )







{







delete str ;







}







} ;







void main( )







{







sample s1 ( "abc" ) ;







}

Ans: Here, through the destructor we are t
rying to deal locate memory, which has been allocated
statically. To remove an exception, add following statement to the constructor.







sample ( char *s )







{







str = new char[strlen(s) + 1] ;







strcpy ( str, s ) ;







}

Here, first we ha
ve allocated memory of required size, which then would get deal located through the
destructor.

32. assert( ) macro...

We can use a macro called assert( ) to test for conditions that should not occur in a code. This macro
expands to an if statement. If tes
t evaluates to 0, assert prints an error message and calls abort to
abort the program.







#include







#include







void main( )







{







int i ;







cout << "
\
nEnter an integer: " ;







cin >> i ;







assert ( i >= 0 ) ;







cout << i
<< endl ;







}

33. Why it is unsafe to deal locate the memory using free( ) if it has been

allocated using new?

Ans: This can be explained with the following example:







#include







class sample







{







int *p ;







public :







sample(
)







{







p = new int ;







}







~sample( )







{







delete p ;







}







} ;







void main( )







{







sample *s1 = new sample ;







free ( s1 ) ;







sample *s2 = ( sample * ) malloc ( sizeof ( sample ) ) ;







delete s2
;







}

The new operator allocates memory and calls the constructor. In the constructor we have allocated
memory on heap, which is pointed to by p. If we release the object using the free( ) function the
object would die but the memory allocated in the c
onstructor would leak. This is because free( ) being
a C library function does not call the destructor where we have deal located the memory.

As against this, if we allocate memory by calling malloc( ) the constructor would not get called. Hence
p holds a
garbage address. Now if the memory is deal located using delete, the destructor would get
called where we have tried to release the memory pointed to by p. Since p contains garbage this may
result in a runtime error.

34. Can we distribute function template
s and class templates in object libraries?

Ans: No! We can compile a function template or a class template into object code (.obj file). The code
that contains a call to the function template or the code that creates an object from a class template
can get

compiled. This is because the compiler merely checks whether the call matches the declaration
(in case of function template) and whether the object definition matches class declaration (in case of
class template). Since the function template and the class

template definitions are not found, the
compiler leaves it to the linker to restore this. However, during linking, linker doesn't find the
matching definitions for the function call or a matching definition for object creation. In short the
expanded versi
ons of templates are not found in the object library. Hence the linker reports error.

35. What is the difference between an inspector and a mutator ?

Ans: An inspector is a member function that returns information about an object's state (information
store
d in object's data members) without changing the object's state. A mutator is a member function
that changes the state of an object. In the class Stack given below we have defined a mutator and an
inspector.







class Stack







{







public :







i
nt pop( ) ;







int getcount( ) ;







}

In the above example, the function pop( ) removes top element of stack thereby changing the state of
an object. So, the function pop( ) is a mutator. The function getcount( ) is an inspector because it
simply cou
nts the number of elements in the stack without changing the stack.

36. Namespaces:

The C++ language provides a single global namespace. This can cause problems with global name
clashes. For instance, consider these two C++ header files:







// file1.h







float f ( float, int ) ;







class sample { ... } ;







// file2.h







class sample { ... } ;

With these definitions, it is impossible to use both header files in a single program; the sample classes
will clash. A namespace is a declarative reg
ion that attaches an additional identifier to any names
declared inside it. The additional identifier thus avoids the possibility that a name will conflict with
names declared elsewhere in the program. It is possible to use the same name in separate
namesp
aces without conflict even if the names appear in the same translation unit. As long as they
appear in separate namespaces, each name will be unique because of the addition of the namespace
identifier. For example:






// file1.h







namespace file1







{







float f ( float, int ) ;







class sample { ... } ;







}







// file2.h







namespace file2







{







class sample { ... } ;







}

Now the class names will not clash because they become file1::sample and file2::sample,
respectivel
y.

37. What would be the output of the following program?







#include







class user







{







int i ;







float f ;







char c ;







public :







void displaydata( )







{







cout << endl << i << endl << f << endl << c ;







}







} ;







void main( )







{







cout << sizeof ( user ) ;







user u1 ;







cout << endl << sizeof ( u1 ) ;







u1.displaydata( ) ;







}

Ans: The output of this program would be,







9 or 7







9 or 7







Garbage







Garbage







G
arbage

Since the user class contains three elements, int, float and char its size would be 9 bytes (int
-
4, float
-
4, char
-
1) under Windows and 7 bytes (int
-
2, float
-
4, char
-
1) under DOS. Second output is again the
same because u1 is an object of the class u
ser. Finally three garbage values are printed out because i,
f and c are not initialized anywhere in the program.

Note that if you run this program you may not get the answer shown here. This is because packing is
done for an object in memory to increase t
he access efficiency. For example, under DOS, the object
would be aligned on a 2
-
byte boundary. As a result, the size of the object would be reported as 6
bytes. Unlike this, Windows being a 32
-
bit OS the object would be aligned on a 4
-
byte boundary.
Hence

the size of the object would be reported as 12 bytes. To force the alignment on a 1
-
byte
boundary, write the following statement before the class declaration.






#pragma pack ( 1 )

38. Write a program that will convert an integer pointer to an integer a
nd vice
-
versa.

Ans: The following program demonstrates this.







#include







void main( )







{







int i = 65000 ;







int *iptr = reinterpret_cast ( i ) ;







cout << endl << iptr ;







iptr++ ;







cout << endl << iptr ;







i = rein
terpret_cast ( iptr ) ;







cout << endl << i ;







i++ ;







cout << endl << i ;







}

39. What is a const_cast?

Ans. The const_cast is used to convert a const to a non
-
const. This is shown in the following







program:







#include







void

main( )







{







const int a = 0 ;







int *ptr = ( int * ) &a ; //one way







ptr = const_cast_ ( &a ) ; //better way







}

Here, the address of the const variable a is assigned to the pointer to a non
-
const variable. The
const_cast is also us
ed when we want to change the data members of a class inside the const member
functions. The following code snippet shows this:







class sample







{







private:







int data;







public:







void func( ) const







{







(const_cast (this
))
-
>data = 70 ;







}







} ;

40. What is forward referencing and when should it be used?

Ans: Forward referencing is generally required when we make a class or a function as a friend.

Consider following program:







class test







{







public:







friend void fun ( sample, test ) ;







} ;







class sample







{







public:







friend void fun ( sample, test ) ;







} ;







void fun ( sample s, test t )







{







// code







}







void main( )







{







sample s ;







test t ;







fun ( s, t ) ;







}

On compiling this program it gives error on the following statement of test class. It gives an error that
sample is undeclared identifier. friend void fun ( sample, test );

This is so because the class sample is def
ined below the class test and we are using it before its
definition. To overcome this error we need to give forward reference of the class sample before the
definition of class test. The following statement is the forward reference of class sample.







c
lass sample ;

41. How would you give an alternate name to a namespace?

Ans: An alternate name given to namespace is called a namespace
-
alias. namespace
-
alias is generally
used to save the typing effort when the names of namespaces are very long or complex.

The following
syntax is used to give an alias to a namespace.







namespace myname = my_old_very_long_name ;

42. Using a smart pointer can we iterate through a container?

Ans: Yes. A container is a collection of elements or objects. It helps to properly

organize and store the
data. Stacks, linked lists, arrays are examples of containers. Following program shows how to iterate
through a container using a smart pointer.







#include







class smartpointer







{







private :







int *p ; // ordin
ary pointer







public :







smartpointer ( int n )







{







p = new int [ n ] ;







int *t = p ;







for ( int i = 0 ; i <= 9 ; i++ )







*t++ = i * i ;







}







int* operator ++ ( int )







{







return p++ ;







}







int ope
rator * ( )







{







return *p ;







}







} ;







void main( )







{







smartpointer sp ( 10 ) ;







for ( int i = 0 ; i <= 9 ; i++ )







cout << *sp++ << endl ;







}

Here, sp is a smart pointer. When we say *sp, the operator * ( )
function gets called. It returns the
integer being pointed to by p. When we say sp++ the operator ++ ( ) function gets called. It
increments p to point to The next element in the array and then returns the address of this new
location.

43. Can objects read

and write themselves?

Ans: Yes! This can be explained with the help of following example:







#include







#include







class employee







{







private :







char name [ 20 ] ;







int age ;







float salary ;







public :







void ge
tdata( )







{







cout << "Enter name, age and salary of employee : " ;







cin >> name >> age >> salary ;







}







void store( )







{







ofstream file ;







file.open ( "EMPLOYEE.DAT", ios::app | ios::binary ) ;







file.write ( ( ch
ar * ) this, sizeof ( *this ) ) ;







file.close( ) ;







}







void retrieve ( int n )







{







ifstream file ;







file.open ( "EMPLOYEE.DAT", ios:

CITICORP


1]. The following variable is available in file1.c

static int average_float;

all

the functions in the file1.c can access the variable


[2]. extern int x;

Check the answer


[3]. Another Problem with



# define TRUE 0

some code

while(TRUE)

{

some code



}

This won't go into the loop as TRUE is defined as 0

[4]. A question in struc
tures where the memebers are dd,mm,yy.

mm:dd:yy

09:07:97


[5]. Another structure question



1 Rajiv System Analyst


[6]. INFILE.DAT is copied to OUTFILE.DAT


[7]. A question with argc and argv .



Input will be



main()

{

int x=10,y=15;

x=x++;

y=++y;

pri
ntf("%d %d
\
n",x,y);

}

----------------------------------------------------------------------


int x;

main()

{

int x=0;

{

int x=10;

x++;

change_value(x);

x++;

Modify_value();

printf("First output: %d
\
n",x);

}

x++;

change_value(x);

printf("Second Output : %
d
\
n",x);

Modify_value();

printf("Third Output : %d
\
n",x);

}


Modify_value()

{

return (x+=10);

}


change_value()

{

return(x+=1);

}


----------------------------------------------------------------------------


main()

{

int x=20,y=35;

x = y++ + x++;

y = ++y
+ ++x;

printf("%d %d
\
n",x,y);

}


-----------------------------------------------------------------------



main()

{

char *p1="Name";

char *p2;

p2=(char *)malloc(20);

while(*p2++=*p1++);

printf("%s
\
n",p2);

}

-------------------------------------------------
---------------------


main()

{

int x=5;

printf("%d %d %d
\
n",x,x<<2,x>>2);

}


--------------------------------------------------------------------


#define swap1(a,b) a=a+b;b=a
-
b;a=a
-
b;

main()

{

int x=5,y=10;

swap1(x,y);

printf("%d %d
\
n",x,y);

swap2(x,y);

printf("%d %d
\
n",x,y);

}


int swap2(int a,int b)

{

int temp;

temp=a;

b=a;

a=temp;

return;

}

----------------------------------------------------------------------



main()

{

char *ptr = "Ramco
Systems
";

(*ptr)++;

printf("%s
\
n",ptr);

ptr++;

printf("%s
\
n",ptr);

}


---------------------------------------------------------------------


#include<stdio