Data Structures Aptitude
1. What is data structure?
A data structure is a way of organizing data that considers not only the items stored, but also their relationship to each other. Advance knowledge about the relationship between data items allows designing of efficient algorithms for the manipulation of data.
2. List out the areas in which data structures are applied extensively?
Compiler Design,
Operating System,
Database Management System,
Statistical analysis package,
Numerical Analysis,
Graphics,
Artificial Intelligence,
Simulation
3. What are the major data structures used in the following areas : RDBMS, Network data model & Hierarchical data model.
RDBMS – Array (i.e. Array of structures)
Network data model – Graph
Hierarchical data model – Trees
4. If you are using C language to implement the heterogeneous linked list, what pointer type will you use?
The heterogeneous linked list contains different data types in its nodes and we need a link, pointer to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer is capable of storing pointer to any type as it is a generic pointer type.
5. Minimum number of queues needed to implement the priority queue?
Two. One queue is used for actual storing of data and another for storing priorities.
6. What is the data structures used to perform recursion?
Stack. Because of its LIFO (Last In First Out) property it remembers its ‘caller’ so knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent iterative procedures are written, explicit stack is to be used.
7. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix forms?
Polish and Reverse Polish notations.
8. Convert the expression ((A + B) * C – (D – E) ^ (F + G)) to equivalent Prefix and Postfix notations.
Prefix Notation:
^ - * +ABC - DE + FG Postfix Notation:
AB + C * DE - - FG + ^
9. Sorting is not possible by using which of the following methods?
(a) Insertion
(b) Selection
(c) Exchange
(d) Deletion
(d) Deletion.
Using insertion we can perform insertion sort, using selection we can perform selection sort, using exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can be done just using deletion.
10. A binary tree with 20 nodes has null branches?
21
Let us take a tree with 5 nodes (n=5)
It will have only 6 (ie,5+1) null branches. In general,
A binary tree with n nodes has exactly n+1 null nodes.
11. What are the methods available in storing sequential files ?
Straight merging,
Natural merging,
Polyphase sort,
Distribution of Initial runs.
12. How many different trees are possible with 10 nodes ?
1014
For example, consider a tree with 3 nodes(n=3), it will have the maximum combination of 5 different (ie, 23 - 3 = 5) trees.
i ii iii iv v
In general:
If there are n nodes, there exist 2n-n different trees.
13. List out few of the Application of tree data-structure?
The manipulation of Arithmetic expression,
Symbol Table construction,
Syntax analysis.
14. List out few of the applications that make use of Multilinked Structures?
Sparse matrix,
Index generation.
15. In tree construction which is the suitable efficient data structure?
(a) Array (b) Linked list (c) Stack (d) Queue (e) none
(b) Linked list
16. What is the type of the algorithm used in solving the 8 Queens problem?
Backtracking
17. In an AVL tree, at what condition the balancing is to be done?
If the ‘pivotal value’ (or the ‘Height factor’) is greater than 1 or less than –1.
18. What is the bucket size, when the overlapping and collision occur at same time?
One. If there is only one entry possible in the bucket, when the collision occurs, there is no way to accommodate the colliding value. This results in the overlapping of values.
19. Traverse the given tree using Inorder, Preorder and Postorder traversals.
Inorder : D H B E A F C I G J
Preorder: A B D H E C F G I J
Postorder: H D E B F I J G C A
20. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have formed a full binary tree?
15.
In general:
There are 2n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14 nodes, so rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correct answer is 15.
Note:
Full and Complete binary trees are different. All full binary trees are complete binary trees but not vice versa.
21. In the given binary tree, using array you can store the node 4 at which location?
At location 6
1 2 3 - - 4 - - 5
Root LC1 RC1 LC2 RC2 LC3 RC3 LC4 RC4
where LCn means Left Child of node n and RCn means Right Child of node n
22. Sort the given values using Quick Sort?
65 70 75 80 85 60 55 50 45
Sorting takes place from the pivot value, which is the first value of the given elements, this is marked bold. The values at the left pointer and right pointer are indicated using L and R respectively.
65 70L 75 80 85 60 55 50 45R
Since pivot is not yet changed the same process is continued after interchanging the values at L and R positions
65 45 75 L 80 85 60 55 50 R 70
65 45 50 80 L 85 60 55 R 75 70
65 45 50 55 85 L 60 R 80 75 70
65 45 50 55 60 R 85 L 80 75 70
When the L and R pointers cross each other the pivot value is interchanged with the value at right pointer. If the pivot is changed it means that the pivot has occupied its original position in the sorted order (shown in bold italics) and hence two different arrays are formed, one from start of the original array to the pivot position-1 and the other from pivot position+1 to end.
60 L 45 50 55 R 65 85 L 80 75 70 R
55 L 45 50 R 60 65 70 R 80 L 75 85
50 L 45 R 55 60 65 70 80 L 75 R 85
In the next pass we get the sorted form of the array.
45 50 55 60 65 70 75 80 85
23. For the given graph, draw the DFS and BFS?
BFS: A X G H P E M Y J
DFS: A X H P E Y M J G
24. Classify the Hashing Functions based on the various methods by which the key value is found.
Direct method,
Subtraction method,
Modulo-Division method,
Digit-Extraction method,
Mid-Square method,
Folding method,
Pseudo-random method.
25. What are the types of Collision Resolution Techniques and the methods used in each of the type?
Open addressing (closed hashing),
The methods used include:
Overflow block,
Closed addressing (open hashing)
The methods used include:
Linked list,
Binary tree…
26. In RDBMS, what is the efficient data structure used in the internal storage representation?
B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier. This corresponds to the records that shall be stored in leaf nodes.
27. Draw the B-tree of order 3 created by inserting the following data arriving in sequence – 92 24 6 7 11 8 22 4 5 16 19 20 78
28. Of the following tree structure, which is, efficient considering space and time complexities?
(a) Incomplete Binary Tree
(b) Complete Binary Tree
(c) Full Binary Tree
(b) Complete Binary Tree.
By the method of elimination:
Full binary tree loses its nature when operations of insertions and deletions are done. For incomplete binary trees, extra storage is required and overhead of NULL node checking takes place. So complete binary tree is the better one since the property of complete binary tree is maintained even after operations like additions and deletions are done on it.
29. What is a spanning Tree?
A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized.
30. Does the minimum spanning tree of a graph give the shortest distance between any 2 specified nodes?
No.
Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesn’t mean that the distance between any two nodes involved in the minimum-spanning tree is minimum.
31. Convert the given graph with weighted edges to minimal spanning tree.
the equivalent minimal spanning tree is:
32. Which is the simplest file structure?
(a) Sequential
(b) Indexed
(c) Random
(a) Sequential
33. Whether Linked List is linear or Non-linear data structure?
According to Access strategies Linked list is a linear one.
According to Storage Linked List is a Non-linear one.
34. Draw a binary Tree for the expression :
A * B - (C + D) * (P / Q)
35. For the following COBOL code, draw the Binary tree?
01 STUDENT_REC.
02 NAME.
03 FIRST_NAME PIC X(10).
03 LAST_NAME PIC X(10).
02 YEAR_OF_STUDY.
03 FIRST_SEM PIC XX.
03 SECOND_SEM PIC XX.
C Aptitude
Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment,
The underlying machine is an x86 system,
Program is compiled using Turbo C/C++ compiler.
The program output may depend
C Questions
Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
Programs run under DOS environment,
The underlying machine is an x86 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).
Predict the output or error(s) for the following:
1. void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".
2. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].
3. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer:
I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb:
Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .
4. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer:
5 4 3 2 1
Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.
5. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++) {
printf(" %d ",*c);
++q; }
for(j=0;j<5;j++){
printf(" %d ",*p);
++p; }
}
Answer:
2 2 2 2 2 2 3 4 6 5
Explanation:
Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.
6. main()
{
extern int i;
i=20;
printf("%d",i);
}
Answer:
Linker Error : Undefined symbol '_i'
Explanation:
extern storage class in the following declaration,
extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .
7. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer:
0 0 1 3 1
Explanation :
Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression ‘i++ && j++ && k++’ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.
8. main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}
Answer:
1 2
Explanation:
The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.
9. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer :
three
Explanation :
The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.
10. main()
{
printf("%x",-1<<4);
}
Answer:
fff0
Explanation :
-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.
11. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Answer:
Compiler Error : Type mismatch in redeclaration of function display
Explanation :
In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.
12. main()
{
int c=- -2;
printf("c=%d",c);
}
Answer:
c=2;
Explanation:
Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
Note:
However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.
13. #define int char
main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
Answer:
sizeof(i)=1
Explanation:
Since the #define replaces the string int by the macro char
14. main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer:
i=0
Explanation:
In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).
15. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
77
Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77("M");
So we get the output 77 :: "M" (Ascii is 77).
16. #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.
17. #include
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer:
Compiler Error
Explanation:
You should not initialize variables in declaration
18. #include
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.
19. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed
20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.
21. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64
22. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
Explanation:
++*p++ will be parse in the given order
*p that is value at the location currently pointed by p will be taken
++*p the retrieved value will be incremented
when ; is encountered the location will be incremented that is p++ will be executed
Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot print anything.
23. #include
#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.
24. #define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
main()
{
100;
printf("%d\n",100);
}
Note:
100; is an executable statement but with no action. So it doesn't give any problem
25. main()
{
printf("%p",main);
}
Answer:
Some address will be printed.
Explanation:
Function names are just addresses (just like array names are addresses).
main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.
27) main()
{
clrscr();
}
clrscr();
Answer:
No output/error
Explanation:
The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).
28) enum colors {BLACK,BLUE,GREEN}
main()
{
printf("%d..%d..%d",BLACK,BLUE,GREEN);
return(1);
}
Answer:
0..1..2
Explanation:
enum assigns numbers starting from 0, if not explicitly defined.
29) void main()
{
char far *farther,*farthest;
printf("%d..%d",sizeof(farther),sizeof(farthest));
}
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer
30) main()
{
int i=400,j=300;
printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.
31) main()
{
char *p;
p="Hello";
printf("%c\n",*&*p);
}
Answer:
H
Explanation:
* is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H.
32) main()
{
int i=1;
while (i<=5)
{
printf("%d",i);
if (i>2)
goto here;
i++;
}
}
fun()
{
here:
printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.
33) main()
{
static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
int i;
char *t;
t=names[3];
names[3]=names[4];
names[4]=t;
for (i=0;i<=4;i++)
printf("%s",names[i]);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants. So it cannot be modified.
34) void main()
{
int i=5;
printf("%d",i++ + ++i);
}
Answer:
Output Cannot be predicted exactly.
Explanation:
Side effects are involved in the evaluation of i
35) void main()
{
int i=5;
printf("%d",i+++++i);
}
Answer:
Compiler Error
Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.
36) #include
main()
{
int i=1,j=2;
switch(i)
{
case 1: printf("GOOD");
break;
case j: printf("BAD");
break;
}
}
Answer:
Compiler Error: Constant expression required in function main.
Explanation:
The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error).
Note:
Enumerated types can be used in case statements.
37) main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1.
38) #define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
}
Answer:
100
39) main()
{
int i=0;
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer:
1
Explanation:
before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop).
40) #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
M
Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32.
i.e. (11+98-32)=77("M");
41) #include
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}
Answer:
Compiler Error
Explanation:
Initialization should not be done for structure members inside the structure declaration
42) #include
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
in the end of nested structure yy a member have to be declared.
43) main()
{
extern int i;
i=20;
printf("%d",sizeof(i));
}
Answer:
Linker error: undefined symbol '_i'.
Explanation:
extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error.
44) main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
Explanation:
The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.
45) main()
{
extern out;
printf("%d", out);
}
int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program.
46) main()
{
show();
}
void show()
{
printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().
47) main( )
{
int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
printf(“%u %u %u %d \n”,a,*a,**a,***a);
printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
}
Answer:
100, 100, 100, 2
114, 104, 102, 3
Explanation:
The given array is a 3-D one. It can also be viewed as a 1-D array.
2 4 7 8 3 4 2 2 2 3 3 4
100 102 104 106 108 110 112 114 116 118 120 122
thus, for the first printf statement a, *a, **a give address of first element . since the indirection ***a gives the value. Hence, the first line of the output.
for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increments the first dimension thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1. Hence, the output.
48) main( )
{
int a[ ] = {10,20,30,40,50},j,*p;
for(j=0; j<5; j++)
{
printf(“%d” ,*a);
a++;
}
p = a;
for(j=0; j<5; j++)
{
printf(“%d ” ,*p);
p++;
}
}
Answer:
Compiler error: lvalue required.
Explanation:
Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue.
49) main( )
{
static int a[ ] = {0,1,2,3,4};
int *p[ ] = {a,a+1,a+2,a+3,a+4};
int **ptr = p;
ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*ptr++;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
*++ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
++*ptr;
printf(“\n %d %d %d”, ptr-p, *ptr-a, **ptr);
}
Answer:
111
222
333
344
Explanation:
Let us consider the array and the two pointers with some address
a
0 1 2 3 4
100 102 104 106 108
p
100 102 104 106 108
1000 1002 1004 1006 1008
ptr
1000
2000
After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for integer is 2 bytes. Now ptr – p is value in ptr – starting location of array p, (1002 – 1000) / (scaling factor) = 1, *ptr – a = value at address pointed by ptr – starting value of array a, 1002 has a value 102 so the value is (102 – 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1, 1.
After execution of *ptr++ increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the second printf are ptr – p = 2, *ptr – a = 2, **ptr = 2.
After execution of *++ptr increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the third printf are ptr – p = 3, *ptr – a = 3, **ptr = 3.
After execution of ++*ptr value in ptr remains the same, the value pointed by the value is incremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108,. Hence, the outputs for the fourth printf are ptr – p = 1006 – 1000 = 3, *ptr – a = 108 – 100 = 4, **ptr = 4.
50) main( )
{
char *q;
int j;
for (j=0; j<3; j++) scanf(“%s” ,(q+j));
for (j=0; j<3; j++) printf(“%c” ,*(q+j));
for (j=0; j<3; j++) printf(“%s” ,(q+j));
}
Explanation:
Here we have only one pointer to type char and since we take input in the same pointer thus we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as
M O U S E \0
When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101.
M T R A C K \0
The third input starts filling from the location 102
M T V I R T U A L \0
This is the final value stored .
The first printf prints the values at the position q, q+1 and q+2 = M T V
The second printf prints three strings starting from locations q, q+1, q+2
i.e MTVIRTUAL, TVIRTUAL and VIRTUAL.
51) main( )
{
void *vp;
char ch = ‘g’, *cp = “goofy”;
int j = 20;
vp = &ch;
printf(“%c”, *(char *)vp);
vp = &j;
printf(“%d”,*(int *)vp);
vp = cp;
printf(“%s”,(char *)vp + 3);
}
Answer:
g20fy
Explanation:
Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is ‘g’. Similarly the output from second printf is ‘20’. The third printf statement type casts it to print the string from the 4th value hence the output is ‘fy’.
52) main ( )
{
static char *s[ ] = {“black”, “white”, “yellow”, “violet”};
char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
p = ptr;
**++p;
printf(“%s”,*--*++p + 3);
}
Answer:
ck
Explanation:
In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1 – 1 = s . the indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is ‘ck’.
53) main()
{
int i, n;
char *x = “girl”;
n = strlen(x);
*x = x[n];
for(i=0; i
printf(“%s\n”,x);
x++;
}
}
Answer:
(blank space)
irl
rl
l
Explanation:
Here a string (a pointer to char) is initialized with a value “girl”. The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location (‘\0’) to the first location. Now the string becomes “\0irl” . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = ‘\0’ hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e “irl” and the third time it prints “rl” and the last time it prints “l” and the loop terminates.
54) int i,j;
for(i=0;i<=10;i++)
{
j+=5;
assert(i<5);
}
Answer:
Runtime error: Abnormal program termination.
assert failed (i<5),
Explanation:
asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use,
#undef NDEBUG
and this will disable all the assertions from the source code. Assertion
is a good debugging tool to make use of.
55) main()
{
int i=-1;
+i;
printf("i = %d, +i = %d \n",i,+i);
}
Answer:
i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).
56) What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).
57) what will be the position of the file marker?
a: fseek(ptr,0,SEEK_SET);
b: fseek(ptr,0,SEEK_CUR);
Answer :
a: The SEEK_SET sets the file position marker to the starting of the file.
b: The SEEK_CUR sets the file position marker to the current position
of the file.
58) main()
{
char name[10],s[12];
scanf(" \"%[^\"]\"",s);
}
How scanf will execute?
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.
59) What is the problem with the following code segment?
while ((fgets(receiving array,50,file_ptr)) != EOF)
;
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.
60) main()
{
main();
}
Answer:
Runtime error : Stack overflow.
Explanation:
main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error.
61) main()
{
char *cptr,c;
void *vptr,v;
c=10; v=0;
cptr=&c; vptr=&v;
printf("%c%v",c,v);
}
Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.
62) main()
{
char *str1="abcd";
char str2[]="abcd";
printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
}
Answer:
2 5 5
Explanation:
In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the '\0' termination character). The third sizeof is similar to the second one.
63) main()
{
char not;
not=!2;
printf("%d",not);
}
Answer:
0
Explanation:
! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0.
64) #define FALSE -1
#define TRUE 1
#define NULL 0
main() {
if(NULL)
puts("NULL");
else if(FALSE)
puts("TRUE");
else
puts("FALSE");
}
Answer:
TRUE
Explanation:
The input program to the compiler after processing by the preprocessor is,
main(){
if(0)
puts("NULL");
else if(-1)
puts("TRUE");
else
puts("FALSE");
}
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.
65) main()
{
int k=1;
printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
}
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".
66) main()
{
int y;
scanf("%d",&y); // input given is 2000
if( (y%4==0 && y%100 != 0) || y%100 == 0 )
printf("%d is a leap year");
else
printf("%d is not a leap year");
}
Answer:
2000 is a leap year
Explanation:
An ordinary program to check if leap year or not.
67) #define max 5
#define int arr1[max]
main()
{
typedef char arr2[max];
arr1 list={0,1,2,3,4};
arr2 name="name";
printf("%d %s",list[0],name);
}
Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})
Explanation:
arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error.
Rule of Thumb:
#defines are used for textual replacement whereas typedefs are used for declaring new types.
68) int i=10;
main()
{
extern int i;
{
int i=20;
{
const volatile unsigned i=30;
printf("%d",i);
}
printf("%d",i);
}
printf("%d",i);
}
Answer:
30,20,10
Explanation:
'{' introduces new block and thus new scope. In the innermost block i is declared as,
const volatile unsigned
which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10.
69) main()
{
int *j;
{
int i=10;
j=&i;
}
printf("%d",*j);
}
Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.
70) main()
{
int i=-1;
-i;
printf("i = %d, -i = %d \n",i,-i);
}
Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.
71) #include
main()
{
const int i=4;
float j;
j = ++i;
printf("%d %f", i,++j);
}
Answer:
Compiler error
Explanation:
i is a constant. you cannot change the value of constant
72) #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d..%d",*p,*q);
}
Answer:
garbagevalue..1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array.
73) #include
main()
{
register i=5;
char j[]= "hello";
printf("%s %d",j,i);
}
Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.
74) main()
{
int i=5,j=6,z;
printf("%d",i+++j);
}
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)
76) struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
struct aaa abc,def,ghi,jkl;
int x=100;
abc.i=0;abc.prev=&jkl;
abc.next=&def;
def.i=1;def.prev=&abc;def.next=&ghi;
ghi.i=2;ghi.prev=&def;
ghi.next=&jkl;
jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
x=abc.next->next->prev->next->i;
printf("%d",x);
}
Answer:
2
Explanation:
above all statements form a double circular linked list;
abc.next->next->prev->next->i
this one points to "ghi" node the value of at particular node is 2.
77) struct point
{
int x;
int y;
};
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);
}
Answer:
origin is(0,0)
origin is(0,0)
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator.
Note:
Since structure point is globally declared x & y are initialized as zeroes
78) main()
{
int i=_l_abc(10);
printf("%d\n",--i);
}
int _l_abc(int i)
{
return(i++);
}
Answer:
9
Explanation:
return(i++) it will first return i and then increments. i.e. 10 will be returned.
79) main()
{
char *p;
int *q;
long *r;
p=q=r=0;
p++;
q++;
r++;
printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.
80) main()
{
char c=' ',x,convert(z);
getc(c);
if((c>='a') && (c<='z'))
x=convert(c);
printf("%c",x);
}
convert(z)
{
return z-32;
}
Answer:
Compiler error
Explanation:
declaration of convert and format of getc() are wrong.
81) main(int argc, char **argv)
{
printf("enter the character");
getchar();
sum(argv[1],argv[2]);
}
sum(num1,num2)
int num1,num2;
{
return num1+num2;
}
Answer:
Compiler error.
Explanation:
argv[1] & argv[2] are strings. They are passed to the function sum without converting it to integer values.
82) # include
int one_d[]={1,2,3};
main()
{
int *ptr;
ptr=one_d;
ptr+=3;
printf("%d",*ptr);
}
Answer:
garbage value
Explanation:
ptr pointer is pointing to out of the array range of one_d.
83) # include
aaa() {
printf("hi");
}
bbb(){
printf("hello");
}
ccc(){
printf("bye");
}
main()
{
int (*ptr[3])();
ptr[0]=aaa;
ptr[1]=bbb;
ptr[2]=ccc;
ptr[2]();
}
Answer:
bye
Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.
85) #include
main()
{
FILE *ptr;
char i;
ptr=fopen("zzz.c","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
}
Answer:
contents of zzz.c followed by an infinite loop
Explanation:
The condition is checked against EOF, it should be checked against NULL.
86) main()
{
int i =0;j=0;
if(i && j++)
printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0
Explanation:
The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed.
87) main()
{
int i;
i = abc();
printf("%d",i);
}
abc()
{
_AX = 1000;
}
Answer:
1000
Explanation:
Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000.
88) int i;
main(){
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
printf("%d--",t--);
}
// If the inputs are 0,1,2,3 find the o/p
Answer:
4--0
3--1
2--2
Explanation:
Let us assume some x= scanf("%d",&i)-t the values during execution
will be,
t i x
4 0 -4
3 1 -2
2 2 0
89) main(){
int a= 0;int b = 20;char x =1;char y =10;
if(a,b,x,y)
printf("hello");
}
Answer:
hello
Explanation:
The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed.
90) main(){
unsigned int i;
for(i=1;i>-2;i--)
printf("c aptitude");
}
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop.
91) In the following pgm add a stmt in the function fun such that the address of
'a' gets stored in 'j'.
main(){
int * j;
void fun(int **);
fun(&j);
}
void fun(int **k) {
int a =0;
/* add a stmt here*/
}
Answer:
*k = &a
Explanation:
The argument of the function is a pointer to a pointer.
92) What are the following notations of defining functions known as?
i. int abc(int a,float b)
{
/* some code */
}
ii. int abc(a,b)
int a; float b;
{
/* some code*/
}
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation
93) main()
{
char *p;
p="%d\n";
p++;
p++;
printf(p-2,300);
}
Answer:
300
Explanation:
The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.
94) main(){
char a[100];
a[0]='a';a[1]]='b';a[2]='c';a[4]='d';
abc(a);
}
abc(char a[]){
a++;
printf("%c",*a);
a++;
printf("%c",*a);
}
Explanation:
The base address is modified only in function and as a result a points to 'b' then after incrementing to 'c' so bc will be printed.
95) func(a,b)
int a,b;
{
return( a= (a==b) );
}
main()
{
int process(),func();
printf("The value of process is %d !\n ",process(func,3,6));
}
process(pf,val1,val2)
int (*pf) ();
int val1,val2;
{
return((*pf) (val1,val2));
}
Answer:
The value if process is 0 !
Explanation:
The function 'process' has 3 parameters - 1, a pointer to another function 2 and 3, integers. When this function is invoked from main, the following substitutions for formal parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the result of the operation performed by the function 'func'. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a==b returns 0. therefore the function returns 0 which in turn is returned by the function 'process'.
96) void main()
{
static int i=5;
if(--i){
main();
printf("%d ",i);
}
}
Answer:
0 0 0 0
Explanation:
The variable "I" is declared as static, hence memory for I will be allocated for only once, as it encounters the statement. The function main() will be called recursively unless I becomes equal to 0, and since main() is recursively called, so the value of static I ie., 0 will be printed every time the control is returned.
97) void main()
{
int k=ret(sizeof(float));
printf("\n here value is %d",++k);
}
int ret(int ret)
{
ret += 2.5;
return(ret);
}
Answer:
Here value is 7
Explanation:
The int ret(int ret), ie., the function name and the argument name can be the same.
Firstly, the function ret() is called in which the sizeof(float) ie., 4 is passed, after the first expression the value in ret will be 6, as ret is integer hence the value stored in ret will have implicit type conversion from float to int. The ret is returned in main() it is printed after and preincrement.
98) void main()
{
char a[]="12345\0";
int i=strlen(a);
printf("here in 3 %d\n",++i);
}
Answer:
here in 3 6
Explanation:
The char array 'a' will hold the initialized string, whose length will be counted from 0 till the null character. Hence the 'I' will hold the value equal to 5, after the pre-increment in the printf statement, the 6 will be printed.
99) void main()
{
unsigned giveit=-1;
int gotit;
printf("%u ",++giveit);
printf("%u \n",gotit=--giveit);
}
Answer:
0 65535
Explanation:
100) void main()
{
int i;
char a[]="\0";
if(printf("%s\n",a))
printf("Ok here \n");
else
printf("Forget it\n");
}
Answer:
Ok here
Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.
101) void main()
{
void *v;
int integer=2;
int *i=&integer;
v=i;
printf("%d",(int*)*v);
}
Answer:
Compiler Error. We cannot apply indirection on type void*.
Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for,
1. Passing generic pointers to functions and returning such pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later point of time.
102) void main()
{
int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}
Answer:
Garbage values.
Explanation:
An identifier is available to use in program code from the point of its declaration.
So expressions such as i = i++ are valid statements. The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO).
103) void main()
{
static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
Answer:
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.
104) void main()
{
while(1){
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
Answer:
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.
104) main()
{
unsigned int i=10;
while(i-->=0)
printf("%u ",i);
}
Answer:
10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop.
105) #include
main()
{
int x,y=2,z,a;
if(x=y%2) z=2;
a=2;
printf("%d %d ",z,x);
}
Answer:
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.
Thumb Rule: Check all control paths to write bug free code.
106) main()
{
int a[10];
printf("%d",*a+1-*a+3);
}
Answer:
4
Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !
107) #define prod(a,b) a*b
main()
{
int x=3,y=4;
printf("%d",prod(x+2,y-1));
}
Answer:
10
Explanation:
The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10
108) main()
{
unsigned int i=65000;
while(i++!=0);
printf("%d",i);
}
Answer:
1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1.
109) main()
{
int i=0;
while(+(+i--)!=0)
i-=i++;
printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the expression and now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The value –1 is printed due to the post-decrement operator.
113) main()
{
float f=5,g=10;
enum{i=10,j=20,k=50};
printf("%d\n",++k);
printf("%f\n",f<<2);
printf("%lf\n",f%g);
printf("%lf\n",fmod(f,g));
}
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++.
Bit-wise operators and % operators cannot be applied on float values.
fmod() is to find the modulus values for floats as % operator is for ints.
110) main()
{
int i=10;
void pascal f(int,int,int);
f(i++,i++,i++);
printf(" %d",i);
}
void pascal f(integer :i,integer:j,integer :k)
{
write(i,j,k);
}
Answer:
Compiler error: unknown type integer
Compiler error: undeclared function write
Explanation:
Pascal keyword doesn’t mean that pascal code can be used. It means that the function follows Pascal argument passing mechanism in calling the functions.
111) void pascal f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
void cdecl f(int i,int j,int k)
{
printf(“%d %d %d”,i, j, k);
}
main()
{
int i=10;
f(i++,i++,i++);
printf(" %d\n",i);
i=10;
f(i++,i++,i++);
printf(" %d",i);
}
Answer:
10 11 12 13
12 11 10 13
Explanation:
Pascal argument passing mechanism forces the arguments to be called from left to right. cdecl is the normal C argument passing mechanism where the arguments are passed from right to left.
112). What is the output of the program given below
main()
{
signed char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
-128
Explanation
Notice the semicolon at the end of the for loop. THe initial value of the i is set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition in the for loop fails and so comes out of the for loop. It prints the current value of i that is -128.
113) main()
{
unsigned char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer
infinite loop
Explanation
The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.
114) main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
Answer:
Behavior is implementation dependent.
Explanation:
The detail if the char is signed/unsigned by default is implementation dependent. If the implementation treats the char to be signed by default the program will print –128 and terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent behavior. But dont write programs that depend on such behavior.
115) Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
Definition.
x is a pointer to array of(size 10) integers.
Apply clock-wise rule to find the meaning of this definition.
116). What is the output for the program given below
typedef enum errorType{warning, error, exception,}error;
main()
{
error g1;
g1=1;
printf("%d",g1);
}
Answer
Compiler error: Multiple declaration for error
Explanation
The name error is used in the two meanings. One means that it is a enumerator constant with value 1. The another use is that it is a type name (due to typedef) for enum errorType. Given a situation the compiler cannot distinguish the meaning of error to know in what sense the error is used:
error g1;
g1=error;
// which error it refers in each case?
When the compiler can distinguish between usages then it will not issue error (in pure technical terms, names can only be overloaded in different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for programmer’s convenience.
117) typedef struct error{int warning, error, exception;}error;
main()
{
error g1;
g1.error =1;
printf("%d",g1.error);
}
Answer
1
Explanation
The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable name as in :
g1.error =1;
printf("%d",g1.error);
typedef struct error{int warning, error, exception;}error;
This can be used to define variables without using the preceding struct keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid.
Note
This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn’t mean that we should use it!
118) #ifdef something
int some=0;
#endif
main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}
Answer:
Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration
int some = 0;
effectively removed from the source code.
119) #if something == 0
int some=0;
#endif
main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}
Answer
0 0
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero.
120). What is the output for the following program
main()
{
int arr2D[3][3];
printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
}
Answer
1
Explanation
This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays.
arr2D is made up of a 3 single arrays that contains 3 integers each .
The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1).
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1).
Since both parts of the expression evaluates to true the result is true(1) and the same is printed.
121) void main()
{
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented in memory”);
}
Answer
You can answer this if you know how values are represented in memory
Explanation
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. –1 is represented in unsigned value as all 1’s and so both are equal.
122) int swap(int *a,int *b)
{
*a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
int x=10,y=20;
swap(&x,&y);
printf("x= %d y = %d\n",x,y);
}
Answer
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.
123) main()
{
char *p = “ayqm”;
printf(“%c”,++*(p++));
}
Answer:
b
124) main()
{
int i=5;
printf("%d",++i++);
}
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.
125) main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated.
126)
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);}
main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Answer:
bye
Explanation:
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments and returns the type int. By the assignment ptr[0] = aaa; it means that the first function pointer in the array is initialized with the address of the function aaa. Similarly, the other two array elements also get initialized with the addresses of the functions bbb and ccc. Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is same as calling ccc(). So it results in printing "bye".
127)
main()
{
int i=5;
printf(“%d”,i=++i ==6);
}
Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.
128) main()
{
char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}
Answer:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
129) void ( * abc( int, void ( *def) () ) ) ();
Answer::
abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptrto a funtion which returns void. the return type of the function is void.
Explanation:
Apply the clock-wise rule to find the result.
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
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
least = (*ptr
}
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++
*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
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
cout<
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"<
class deri:public base
{
public:
void baseFun(){ cout<< "from derived"<
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"<
class deri:public base
{
public:
void baseFun(){ cout<< "from derived"<
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="<}
/*
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<
void print(int ptr[size])
{
cout<
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"<
};
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
class fig2d
{
int dim1;
int dim2;
public:
fig2d() { dim1=5; dim2=6;}
virtual void operator<<(ostream & rhs);
};
void fig2d::operator<<(ostream &rhs)
{
rhs <
}
/*class fig3d : public fig2d
{
int dim3;
public:
fig3d() { dim3=7;}
virtual void operator<<(ostream &rhs);
};
void fig3d::operator<<(ostream &rhs)
{
fig2d::operator <<(rhs);
rhs<
}
*/
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<
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="<}
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 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
........
cout<
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 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
const smart_pointer
~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
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
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.
More Best Practical Question on C
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
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 part of this question can be answered in at least
three ways:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */
3. 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 of 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-function 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.)
7. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers.
Write the way to initialize the 2nd element to 10.
8. In the above question an array of pointers is declared.
Write the statement to initialize the 3rd element of the 2 element to 10;
9.
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.
10.
void main()
{
int i=7;
printf("%d",i++*i++);
}
Ans: 56
11.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
12.
void main()
{
intcount=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20
13. There was question in c working only on unix machine with pattern matching.
14. what is alloca()
Ans : It allocates and frees memory after use/after getting out of scope
15.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
Ans: 321
16.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}
Ans: anything is good.
17.
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"
Find the output for the following C program
int array[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
for (i=2;i<0;i--)
for(j=2;j<=0;j--)
printf("%d", arr[i][j]);
10. Find the output for the following C program
#include
void main()
{int i,x,sum=0;
int arr[6]=[1,2,3,4,5,6]
for (i=0;i<4;i++)
sum+ = func(arr[i]);
printf("%d", sum);
}
func(int x)
{ int val,x;
val = 2;
return(x+ val++);
}
1. Convert 251 in base 10 to octal(base 8)?
2. How much information can be stored in 1 byte of a IBM pc compatible?
3.What is the language used for Artificial Intelligence
Ans: lisp
4. Swap two variables without using temporary variable
Ans: a= a+b; b= a-b; a= a-b:
5.Which is not the operating system ?
Ans: BIOS
6. What is the optimum number of operations for 2x3 + 3x2 + 5x + 5?
7. In the fortran language which of the following is true.
(i) fortran uses call by value
(ii) fortran is object oriented
(iii) fortran allows use of function overloading
Ans. (i)
8. When a program is compiled what does it produce?
Ans: Source code is converted to object code
9. What is the difference between function overloading and function overriding?
10. What is the character set used in JAVA 2.0 ?
Ans: Unicode
SECTION 3 - C TEST
1. What is the mistake in the following program segment ?
f()
{
int a;
void c;
f2(&c,&a);}
2. a=0;
b=(a=0)?2:3;
a) What will be the value of b and why ?
b) If in first statement a= 0 is replaced by a= -1, b = ?
c) If in second statement a=0 is replaced by a = -1, b=?
3. char *a[2];
int const *p;
int *const p;
struct new { int a;int b; *var[5] (struct new)}
Describe the statements in the above given construct ?
4. f()
{
int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
}
What is the value of c ?
5. f1()
{
f(3);
}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
What is the value of c?
6. What is the fallacy in the following program segment ?
int *f1()
{
int a=5;
return &a;
}
f()
int *b=f1()
int c=*b;
}
7. Give the C language equivalents of the following
a)Function returning an int pointer
b)Function pointer returning an int pointer
c)Function pointer returning an array of integers
d)Array of function pointer returning an array of integers
8. Find the fallacy in the following program segment?
int a;
short b;
b=a;
9. Define function ? Explain arguments in functions ?
10. How does C pass variables to a function ?
11. Explain the following program segment.
f(){
int *b;
*b=2;
}
12. Explain binary trees and their use ?
13. Draw the diagram showing the function stack, illustrating the variables that were pushed on the stack at the point when function f2 has been introduced .
type def struct
{ double x,double y} point; }
main( int argc, char *arg[3])
{ double a;
int b,c;
f1(a,b); }
f1(double x, int y)
{point p;
stack int n;
f2(p,x,y)
}
f2(point p, double angle)
{ int i,j,k,int max;
}
Section B
1. Given the following statement
enum day = { jan = 1 ,feb=4, april, may}
What is the value of may?
(a) 4
(b) 5
(c) 6
(d) 11
(e) None of the above
2. Find the output for the following C program
main
{int x,j,k;
j=k=6;x=2;
x=j*k;
printf("%d", x);
3. Find the output for the following C program
fn f(x)
{ if(x<=0)
return;
else f(x-1)+x;
}
4. Find the output for the following C program
i=20,k=0;
for(j=1;j{k+=j<10?4:3;
}
printf("%d", k);
Ans. k=4
5. Find the output for the following C program
int i =10
main()
{int i =20,n;
for(n=0;n<=i;)
{int i=10;
i++;
}
printf("%d", i);
Ans. i=20
6. Find the output for the following C program
int x=5;
y= x&y
7.Find the output for the following C program
Y=10;
if( Y++>9 && Y++!=10 && Y++>10)
{printf("%d", Y);
else
printf("%d", Y);
}
Ans. 13
8. Find the output for the following C program
f=(x>y)?x:y
a) f points to max of x and y
b) f points to min of x and y
c)error
Ans. (a)
9. What is the sizeof(long int)
(a) 4 bytes
(b) 2 bytes
(c) compiler dependent
(d) 8 bytes
10. Which of the function operator cannot be over loaded
(a) <=
(b) ?:
(c) ==
(d) *
11. Find the output for the following C program
main()
{intx=2,y=6,z=6;
x=y==z;
printf(%d",x)
}
Section C (Programming Skills)
Answer the questions based on the following program
STRUCT DOUBLELIST
{ DOUBLE CLINKED
INT DET; LIST VOID
STRUCT PREVIOUS; (BE GIVEN AND A PROCEDURE TO DELETE)
STRUCT NEW; (AN ELEMENT WILL BE GIVEN)
}
DELETE(STRUCT NODE)
{NODE-PREV-NEXT NODE-NEXT;
NODE-NEXT-PREV NODE-PREV;
IF(NODE==HEAD)
NODE
}
Q. In what case the prev was
(a) All cases
(b) It does not work for the last element
(c) It does not for the first element
(d) None of these
Answer the questions based on the following program
VOID FUNCTION(INT KK)
{KK+=20;
}
VOID FUNCTION (INT K)
INT MM,N=&M
KN = K
KN+-=10;
}
Q. What is the output of the following program
main()
{ int var=25,varp;
varp=&var;
varp p = 10;
fnc(varp)
printf("%d%d,var,varp);
}
(a) 20,55
(b) 35,35
(c) 25,25
(d)55,55
**************8
Q1. typedef struct{
char *;
nodeptr next;
} * nodeptr ;
What does nodeptr stand for?
Q2. What does. int *x[](); means ?
Q3. struct list{
int x;
struct list *next;
}*head;
the struct head.x =100
Is the above assignment to pointer is correct or wrong ?
Ans. Wrong
Q4.What is the output of the following ?
int i;
i=1;
i=i+2*i++;
printf(%d,i);
Ans. 4
Q5. FILE *fp1,*fp2;
fp1=fopen("one","w")
fp2=fopen("one","w")
fputc('A',fp1)
fputc('B',fp2)
fclose(fp1)
fclose(fp2)}
a.error b. c. d.
Ans. no error. But It will over writes on same file.
What are the output(s) for the following ?
Q6. #include
char *f()
{char *s=malloc(8);
strcpy(s,"goodbye")}
main()
{
char *f();
printf("%c",*f()='A');
}
Q7. #define MAN(x,y) (x)>(y)?(x):(y)
{
inti=10;j=5;k=0;
k= MAX(i++,++j)
printf(%d %d %d %d,i,j,k)
}
Ans. 10 5 0
Q8. a=10;b= 5;c=3;d=3;
if(a printf(%d %d %d %d a,b,c,d)
else printf("%d %d %d %d a,b,c,d);
Q9. #include
show(int t,va_list ptr1)
{
int a,x,i;
a=va_arg(ptr1,int)
printf("\n %d",a)
}
display(char)
{
int x;
listptr;
va_star(otr,s);
n=va_arg(ptr,int);
show(x,ptr);
}
main()
{
display("hello",4,12,13,14,44);
}
Q10. main()
{
printf("hello");
fork();
}
Q11. main()
{
int i = 10;
printf(" %d %d %d \n", ++i, i++, ++i);
}
Q12. #include
main()
{
int *p, *c, i;
i = 5;
p = (int*) (malloc(sizeof(i)));
printf("\n%d",*p);
*p = 10;
printf("\n%d %d",i,*p);
c = (int*) calloc(2);
printf("\n%d\n",*c);
}
Q13. #define MAX(x,y) (x) >(y)?(x):(y)
main()
{
inti=10,j=5,k=0;
k= MAX(i++,++j);
printf("%d..%d..%d",i,j,k);
}
Q14. #include
main()
{
enum _tag{ left=10, right, front=100, back};
printf("left is %d, right is %d, front is %d, back is %d",left,right,front,back);
}
Q15. main()
{
inta=10,b=20;
a>=5?b=100:b=200;
printf("%d\n",b);
}
Q16. #define PRINT(int) printf("int = %d ",int)
main()
{< BR> intx,y,z;
x=03;y=02;z=01;
PRINT(x^x);
z<<=3;PRINT(x);
y>>=3;PRINT(y);
}
Q17. #include
main()
{
char s[] = "Bouquets and Brickbats";
printf("\n%c, ",*(&s[2]));
printf("%s, ",s+5);
printf("\n%s",s);
printf("\n%c",*(s+2));
}
Q18. main()
{
struct s1
{
char *str;
struct s1 *ptr;
};
static struct s1 arr[] = { {"
};
struct s1 *p[3];
int i; < BR> for(i=0;i<=2;i++)
p[i] = arr[i].ptr;
printf("%s\n",(*p)->str);
printf("%s\n",(++*p)->str);
printf("%s\n",((*p)++)->str);
}
Q19. .main()
{
char *p = "hello world!";
p[0] = 'H';
printf("%s",p);
}
24. What will the following program do?
void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
25. In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}
a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT
Ans. (a)
27. What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
a) The string is : string
b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Ans. (b)
28. What will be result of the following program?
void myalloc(char *x, int n)
{x= (char *)malloc(n*sizeof(char));
memset(x,\0,n*sizeof(char));
}
main()
{char *g="String";
myalloc(g,20);
strcpy(g,"Oldstring");
printf("The string is %s",g);
}
a) The string is : String
b) Run time error/Core dump
c) The string is : Oldstring
d) Syntax error during compilation
e) None of these
31. The standard source for standard input, standard output and standard error is
a) the terminal
b) /dev/null
c) /usr/you/input, /usr/you/output/, /usr/you/error respectively
d) None
Ans. (a)
32. What will be the result of the following program?
main()
{char p[]="String";
int x=0;
if(p=="String")
{printf("Pass 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
else
{
printf("Fail 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
}
a) Pass 1, Pass 2
b) Fail 1, Fail 2
c) Pass 1, Fail 2
d) Fail 1, Pass 2
e) syntax error during compilation
33. Which of the choices is true for the mentioned declaration ?
const char *p;
and
char * const p;
a) You can't change the character in both
b) First : You can't change the characterr & Second : You can;t change the pointer
c) You can't change the pointer in both
d) First : You can't change the pointer & Second : You can't chanage the character
e) None
34. The redirection operators > and >>
a) do the same function
b) differ : > overwrites, while >> appends
c) differ : > is used for input while >> is used for output
d) differ : > write to any file while >> write only to standard output
e) None of these
Ans. (b)
35. The command grep first second third /usr/you/myfile
a) prints lines containing the words first, second or third from the file /usr/you/myfile
b) searches for lines containing the pattern first in the files
second, third, and /usr/you/myfile and prints them
c) searches the files /usr/you/myfiel and third for lines containing the words first or second and prints them
d) replaces the word first with the word second in the files third and /usr/you/myfile
e) None of the above
Ans. (b)
SECTION 3 - C TEST
1. What is the mistake in the following program segment ?
f()
{
int a;
void c;
f2(&c,&a);}
2. a=0;
b=(a=0)?2:3;
a) What will be the value of b and why ?
b) If in first statement a= 0 is replaced by a= -1, b = ?
c) If in second statement a=0 is replaced by a = -1, b=?
3. char *a[2];
int const *p;
int *const p;
struct new { int a;int b; *var[5] (struct new)}
Describe the statements in the above given construct ?
4. f()
{
int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
}
What is the value of c ?
5. f1()
{
f(3);
}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
What is the value of c?
6. What is the fallacy in the following program segment ?
int *f1()
{
int a=5;
return &a;
}
f()
int *b=f1()
int c=*b;
}
7. Give the C language equivalents of the following
a)Function returning an int pointer
b)Function pointer returning an int pointer
c)Function pointer returning an array of integers
d)Array of function pointer returning an array of integers
8. Find the fallacy in the following program segment?
int a;
short b;
b=a;
9. Define function ? Explain arguments in functions ?
10. How does C pass variables to a function ?
11. Explain the following program segment.
f(){
int *b;
*b=2;
}
12. Explain binary trees and their use ?
13. Draw the diagram showing the function stack, illustrating the variables that were pushed on the stack at the point when function f2 has been introduced .
type def struct
{ double x,double y} point; }
main( int argc, char *arg[3])
{ double a;
int b,c;
f1(a,b); }
f1(double x, int y)
{point p;
stack int n;
f2(p,x,y)
}
f2(point p, double angle)
{ int i,j,k,int max;
}
C/C++ Questions
1. What is the output of printf("%d")
2. What will happen if I say delete this
3. Difference between "C structure" and "C++ structure".
4. Diffrence between a "assignment operator" and a "copy constructor"
5. What is the difference between "overloading" and "overridding"?
6. Explain the need for "Virtual Destructor".
7. Can we have "Virtual Constructors"?
8. What are the different types of polymorphism?
9. What are Virtual Functions? How to implement virtual functions in "C"
10. What are the different types of Storage classes?
11. What is Namespace?
12. What are the types of STL containers?.
13. Difference between "vector" and "array"?
14. How to write a program such that it will delete itself after exectution?
15. Can we generate a C++ source code from the binary file?
16. What are inline functions?
17. Talk sometiming about profiling?
18. How many lines of code you have written for a single program?
19. What is "strstream" ?
20. How to write Multithreaded applications using C++?
21. Explain "passing by value", "passing by pointer" and "passing by reference"
22. Write any small program that will compile in "C" but not in "C++"
23. Have you heard of "mutable" keyword?
24. What is a "RTTI"?
25. Is there something that I can do in C and not in C++?
26. Why preincrement operator is faster than postincrement?
27. What is the difference between "calloc" and "malloc"?
28. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?
29. What is Memory Alignment?
30. Explain working of printf.
31. Difference between "printf" and "sprintf".
32. What is "map" in STL?
33. When shall I use Multiple Inheritance?
34. What are the techniques you use for debugging?
35. How to reduce a final size of executable?
36. Give 2 examples of a code optimization.
Some companies certainly ask for these puzzles.
1. Write a "Hello World" program in 'C' without using a semicolon.
2. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
3. C/C++ : Exchange two numbers without using a temporary variable.
4. C/C++ : Find if the given number is a power of 2.
5. C/C++ : Multiply x by 7 without using multiplication (*) operator.
6. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
7. Remove duplicates in array
8. Finding if there is any loop inside linked list.
9. Remove duplicates in an no key access database without using an array
10. Convert (integer) number in binary without loops.
11. Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
12. From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
13. Given an array (group) of numbers write all the possible sub groups of this group.
Frequently Asked Questions - C/C++ Questions
1. What does static variable mean?
2. What is a pointer?
3. What is a structure?
4. What are the differences between structures and arrays?
5. In header files whether functions are declared or defined?
6. What are the differences between malloc() and calloc()?
7. What are macros? what are its advantages and disadvantages?
8. Difference between pass by reference and pass by value?
9. What is static identifier?
10. Where are the auto variables stored?
11. Where does global, static, local, register variables, free memory and C Program instructions get stored?
12. Difference between arrays and linked list?
13. What are enumerations?
14. Describe about storage allocation and scope of global, extern, static, local and register variables?
15. What are register variables? What are the advantage of using register variables?
16. What is the use of typedef?
17. Can we specify variable field width in a scanf() format string? If possible how?
18. Out of fgets() and gets() which function is safe to use and why?
19. Difference between strdup and strcpy?
20. What is recursion?
21. Differentiate between a for loop and a while loop? What are it uses?
22. What are the different storage classes in C?
23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
24. What is difference between Structure and Unions?
25. What the advantages of using Unions?
26. What are the advantages of using pointers in a program?
27. What is the difference between Strings and Arrays?
28. In a header file whether functions are declared or defined?
29. What is a far pointer? where we use it?
30. How will you declare an array of three function pointers where each function receives two ints and returns a float?
31. what is a NULL Pointer? Whether it is same as an uninitialized pointer?
32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?
33. What does the error 'Null Pointer Assignment' mean and what causes this error?
34. What is near, far and huge pointers? How many bytes are occupied by them?
35. How would you obtain segment and offset addresses from a far address of a memory location?
36. Are the expressions arr and &arr same for an array of integers?
37. Does mentioning the array name gives the base address in all the contexts?
38. Explain one method to process an entire string as one unit?
39. What is the similarity between a Structure, Union and enumeration?
40. Can a Structure contain a Pointer to itself?
41. How can we check whether the contents of two structure variables are same or not?
42. How are Structure passing and returning implemented by the complier?
43. How can we read/write Structures from/to data files?
44. What is the difference between an enumeration and a set of pre-processor # defines?
45. what do the 'c' and 'v' in argc and argv stand for?
46. Are the variables argc and argv are local to main?
47. What is the maximum combined length of command line arguments including the space between adjacent arguments?
48. If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?
49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?
50. What are bit fields? What is the use of bit fields in a Structure declaration?
51. To which numbering system can the binary number 1101100100111100 be easily converted to?
52. Which bit wise operator is suitable for checking whether a particular bit is on or off?
53. Which bit wise operator is suitable for turning off a particular bit in a number?
54. Which bit wise operator is suitable for putting on a particular bit in a number?
55. Which bit wise operator is suitable for checking whether a particular bit is on or off?
56. which one is equivalent to multiplying by 2:Left shifting a number by 1 or Left shifting an unsigned int or char by 1?
57. Write a program to compare two strings without using the strcmp() function.
58. Write a program to concatenate two strings.
59. Write a program to interchange 2 variables without using the third one.
60. Write programs for String Reversal & Palindrome check
61. Write a program to find the Factorial of a number
62. Write a program to generate the Fibinocci Series
63. Write a program which employs Recursion
64. Write a program which uses Command Line Arguments
65. Write a program which uses functions like strcmp(), strcpy()? etc
66. What are the advantages of using typedef in a program?
67. How would you dynamically allocate a one-dimensional and two-dimensional array of integers?
68. How can you increase the size of a dynamically allocated array?
69. How can you increase the size of a statically allocated array?
70. When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically?
71. Which function should be used to free the memory allocated by calloc()?
72. How much maximum can you allocate in a single call to malloc()?
73. Can you dynamically allocate arrays in expanded memory?
74. What is object file? How can you access object file?
75. Which header file should you include if you are to develop a function which can accept variable number of arguments?
76. Can you write a function similar to printf()?
77. How can a called function determine the number of arguments that have been passed to it?
78. Can there be at least some solution to determine the number of arguments passed to a variable argument list function?
79. How do you declare the following:
o An array of three pointers to chars
o An array of three char pointers
o A pointer to array of three chars
o A pointer to function which receives an int pointer and returns a float pointer
o A pointer to a function which receives nothing and returns nothing
80. What do the functions atoi(), itoa() and gcvt() do?
81. Does there exist any other function which can be used to convert an integer or a float to a string?
82. How would you use qsort() function to sort an array of structures?
83. How would you use qsort() function to sort the name stored in an array of pointers to string?
84. How would you use bsearch() function to search a name stored in array of pointers to string?
85. How would you use the functions sin(), pow(), sqrt()?
86. How would you use the functions memcpy(), memset(), memmove()?
87. How would you use the functions fseek(), freed(), fwrite() and ftell()?
88. How would you obtain the current time and difference between two times?
89. How would you use the functions randomize() and random()?
90. How would you implement a substr() function that extracts a sub string from a given string?
91. What is the difference between the functions rand(), random(), srand() and randomize()?
92. What is the difference between the functions memmove() and memcpy()?
93. How do you print a string on the printer?
94. Can you use the function fprintf() to display the output on the screen?
C++ Questions
1. What is a class?
2. What is an object?
3. What is the difference between an object and a class?
4. What is the difference between class and structure?
5. What is public, protected, private?
6. What are virtual functions?
7. What is friend function?
8. What is a scope resolution operator?
9. What do you mean by inheritance?
10. What is abstraction?
11. What is polymorphism? Explain with an example.
12. What is encapsulation?
13. What do you mean by binding of data and functions?
14. What is function overloading and operator overloading?
15. What is virtual class and friend class?
16. What do you mean by inline function?
17. What do you mean by public, private, protected and friendly?
18. When is an object created and what is its lifetime?
19. What do you mean by multiple inheritance and multilevel inheritance? Differentiate between them.
20. Difference between realloc() and free?
21. What is a template?
22. What are the main differences between procedure oriented languages and object oriented languages?
23. What is R T T I ?
24. What are generic functions and generic classes?
25. What is namespace?
26. What is the difference between pass by reference and pass by value?
27. Why do we use virtual functions?
28. What do you mean by pure virtual functions?
29. What are virtual classes?
30. Does c++ support multilevel and multiple inheritance?
31. What are the advantages of inheritance?
32. When is a memory allocated to a class?
33. What is the difference between declaration and definition?
34. What is virtual constructors/destructors?
35. In c++ there is only virtual destructors, no constructors. Why?
36. What is late bound function call and early bound function call? Differentiate.
37. How is exception handling carried out in c++?
38. When will a constructor executed?
39. What is Dynamic Polymorphism?
40. Write a macro for swapping integers.
Some More Questions ::
1. What is the output of printf("%d")
2. What will happen if I say delete this
3. Difference between "C structure" and "C++ structure".
4. Difference between a "assignment operator" and a "copy constructor"
5. What is the difference between "overloading" and "overriding"?
6. Explain the need for "Virtual Destructor".
7. Can we have "Virtual Constructors"?
8. What are the different types of polymorphism?
9. What are Virtual Functions? How to implement virtual functions in "C"
10. What are the different types of Storage classes?
11. What is Namespace?
12. What are the types of STL containers?.
13. Difference between "vector" and "array"?
14. How to write a program such that it will delete itself after execution?
15. Can we generate a C++ source code from the binary file?
16. What are inline functions?
17. Talk something about profiling?
18. How many lines of code you have written for a single program?
19. What is "strstream" ?
20. How to write Multithreaded applications using C++?
21. Explain "passing by value", "passing by pointer" and "passing by reference"
22. Write any small program that will compile in "C" but not in "C++"
23. Have you heard of "mutable" keyword?
24. What is a "RTTI"?
25. Is there something that I can do in C and not in C++?
26. Why preincrement operator is faster than postincrement?
27. What is the difference between "calloc" and "malloc"?
28. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?
29. What is Memory Alignment?
30. Explain working of printf.
31. Difference between "printf" and "sprintf".
32. What is "map" in STL?
33. When shall I use Multiple Inheritance?
34. What are the techniques you use for debugging?
35. How to reduce a final size of executable?
36. Give 2 examples of a code optimization.
C ++ Revision QUESTIONS
Q1. What are Comments?
Ans. Comments are pieces of source code discarded from the code by the compiler. They do nothing. Their purpose is only to allow the programmer to insert notes or descriptions embedded within the source code.
C++ supports two ways to insert comments:
// Line comment
/* block comment */
Q2. What is a preprocessor directive? What is its role in C++?
Or
Why symbolic statements are used?
Ans. Preprocessor directives are orders that we include within the code of our programs that are not instructions for the program itself but for the preprocessor. The preprocessor is executed automatically by the compiler when we compile a program in C++ and is in charge of making the first verifications and digestions of the program's code
Q3. Differentiate between constants and variables.
Ans. Variables are the named memory location in computer memory and vary their value at run time. But constants remain the same and cannot change their value at run time.
Q4. Differentiate between = and = = operators.
Ans. ‘=’ operator is one of the assignment operator, used to assign the value to a variable.
‘= =’ Operator is one of the relational operator; used to check the relation between two variables.
Q5. Write a short note on type casting.
Ans. Type casting is used to convert the data type from lower data type to higher data type and converse for temporary period so that calculations can be performed with both the data types.
Example
void main()
{
int a=5;
float b;
cout<<“value of a ”<b=(float)a;
cout<<“value of b ”,b;
}
Q6. What are key words? How these are different from identifiers?
Ans. The keywords are the reserved words. The keywords are identifiers but cannot be user defined. It is mandatory that all the keywords should be in lower case letters. For example
for, while, do, if, continue, break etc.
There are 32 keywords in C and 48 in C++.
Identifier can be defined as name of variable and some other program elements using the combination of following characters.
Alphabet: a to z, A to Z
Numerals: 0 to 9
Underscore: _
Q7. Differentiate between compiler and interpreter? Also give the name of the various compilers of C and C++(imp (LY).
Ans. Compiler and interpreter both are used to convert the high-level language program into the object source code. But
Interpreter: - Interprets the program line by line. It is slow
Compiler: - Compiles the whole program at a time. It is fast.
Name of the C and C++ compilers: Borland C, ANSI C, Turbo C.
Q8. How C is different from ‘C++’?
Ans. C++ is the superset of C. C is structured programming language where as C++ is object oriented programming language. Many of the features available in C++ were not there in C.
Data protection is the most important concept included in C++.
By the means of the data hiding we can protect the data.
Redeclaration of variables is not needed in C++, where it is the overhead in C. You have to redeclare the variables every time you are using a function.
Function overloading cannot be done in C, where as it is possible in C++.
Q9. Define array. How will you declare and store values in an array?
Ans. Arrays are used to give the common name to different memory locations of same data type. In Array group of elements can share the same name.
Syntax to declare array is: -
Datatype variablename [size];
Example
int a[5];
Q10. What is Procedure oriented programming?
Ans. Using procedural programming we are able to combine returning sequence of statements into one single place. With the use of procedures, programs can be written in more structured and error free manner. A program can be viewed as sequence of procedure calls. The main program is responsible to pass data to individual calls, data is processed by the procedures and the result in presented.
Main Program
Procedure 1 Procedure 2 Procedure n
Q11. What is Nested if statement?
Ans. When we combine several if statements, it is referred to as nested if statement. The control is moved to next if statement only if the first condition is true and after performing the first statement the next if condition is checked and if this condition is also true, then the second statement is performed. In case the first condition is false, the control skips the following statement of both if conditions and moves to the else part, if specified.
Syntax
if(condition1){
statement 1
if (condition 2){
statement 2
}
}
else
{
statements
}
Q12. What do you mean by Manipulators?
Ans. These are special stream functions used to change the certain characteristics of input and output. These are used to format input and output streams. The header file used for them is
Q13. What is Pointer or Indirection operator?
Ans. The pointer is used for indirect reference of a variable. It holds address of the variable, where it has been stored in memory. For pointer * operator is used. That’s why it is also called as indirection operator. Its advantage is that it provide functions, which can modify their calling arguments i.e. function reference.
Q14. What are the desirable characteristics of a ‘C++’ program?
Ans. A C++ program must contain a class if it is according to the concept of OOPS. The data members should be declared as private or protected to ensure that there is even no accidental access to the data members of class. The methods should be declared as public.
The definition of class consists of the following steps:
i. Definition of class
ii. The internal representation of data structures and storage
iii. The internal implementation of the interface.
iv. The external operations for accessing and manipulation the instance of the class.
Q15. Why are functions created in ‘C++’? What is the difference between library functions and user-defined functions?
Ans. Function: - A function is a self-contained program segment that carries out some specific, well defined task. A function is also known as sub program that can be executed in the program. The functions are used to make the program modular.
Function basically are classified in two categories
Library function: - These are needed in every program. They are stored in the library files known as header file. Commonly used functions are printf() and scanf(). It is to include at the beginning of the program using header file.
User defined function: - These functions are defined by the users according to their requirements.
Q16. Differentiate between passing arguments by reference and by value.
Ans. Call by reference
In C++, you can declare a function parameter to be a pointer, for example "void order (int*,int*);", then use the dereferenced pointer in the function body, and pass an address as an argument when the function is called: "order(int&p, int&q);” - to change the values of "p" and "q" in the calling environment.
Call by value
Argument-passing mechanism strictly adhered to in C, variables are passed as arguments to a function copying their values to corresponding function parameters without changing them in the calling environment.
Q17. Define and explain the following:
(a) Abstraction
(b) polymorphism
Ans. Abstraction: In OOP data abstraction is defined as a collection of data and methods (functions). In a class we define the data members as well as the functions, which can access and use these data members.
Polymorphism: In OOP, polymorphism is defined as how to carry out different processing steps by a function having the same messages. Polymorphism allows you to create definitions for operators and functions and at run-time depending on the context a particular definition will be used.
Q18. What is a structure? What is the difference between a structure and a union?
Ans. Structure constitutes a super data type, which represents several different data types in a single unit. It is A collection of dissimilar data type. Structure can be initialized if it is static or global. A structure variable contains each of the named members, and its size is large enough to hold all the members.
A union contains one of the named members at a given time and is large enough to hold the largest member.
Q19. What is the precedence of Arithmetic operators?
Ans. *, /, % Highest
+, - Lowest
Precedence of Relational operators
<, < = , >,> = > Highest
= =, ! = Lowest
Logical operator
1, && , II
Assignment operator
= , + = , - = , * = , 1- , % =, & =, ^, ! =, << =, >> =
Q20. How do you declare a single and a two dimensional array?
Ans. data type array name [size] = {expression ............}
One dimensional array Two dimensional array
int a [5] = { 1,2,3,4,5}; int a [2] [2] = { {1 ,2},{3,4} } ;
Q21. What is type conversion?
Ans. Type conversion is to convert the set of declared type of some other required type. Conversion can be divided in two ways.
1 Converting by assignment
2 Using cast operator
Q22. What do you mean by preprocessor?
Ans. Preprocessor is used to include library files and also to define macro.
Built in function are the functions defined in the library files. These functions can be used in the program without need to define them in your program as they are defined in library files. E.g. get (), puts ( ), getch( ) etc.
Q23. Why special operators or characters are used in C++?
Ans. A number of special characters are used. All have different purposes.
[] is used to denote array
() is used to denote function.
{} is used for compound statements.
c=a+b;
cout<
Ans. 1. Long name describe identifier clearly.
2. Readability and understandability of identifier is increased by using long name for other programmers. .
Q25. Is cascading of input and output operators possible? If yes explain how?
Ans. The multiple use of <
cin>>a>>b>>c;
For example, Cascading of output
cout<Q26. What do you mean by atoi() function?
Ans. 1. It converts string to integer.
2 It is a utility function.
3 It is defined in stdlib.h.
Q27. How does pointer work with two-dimensional array?
Ans. In two dimensional array pointer contain address of first element i.e is address of zeroth row and zeroth column assigned to pointer. If we increment pointer, pointer will be incremented to next data in two dimensional arrays that is equal to value. i.e. value[0][1] because two dimensional array store data by row order.
Example ptr=&value[0][0];
Q28. What is meant by data hiding?
Ans. Data hiding provides facility of exposing information, as much is needed by the user. Data hiding is implemented using abstraction and encapsulation. By using three access specifiers private, public and protected this can be implemented. It is also called as information hiding.
Q29. What is encapsulation?
Ans. It is a method to implement abstraction by wrapping up data and associated functions into a single unit The single unit is called a class .The data will not be accessible to outer world. Only member functions of class can access data. These functions provide interface between object data and program.
Q30. What is object oriented programming? What is the difference between an object and a class?
Ans. Object oriented programming treat data as a critical element in program development and does not flow freely around the system. It ties data more closely to functions that operate on it in a data structure called Class. Objects are instances of Class. Class is a template from which object take its shape. A Class can have more than one object. Collection of number of entities is called as objects. Class is also defined as collection of data members and member functions.
Q31. State two rules for naming a variable.
Ans. 1. It should not begin with numeric data.
2. For breaking variable in two parts underscore is used, space is not allowed.
Q32. Can a conditional operator replace an if statement always?
Or
Define conditional operator.
Ans. Yes. By putting the conditional operator within parenthesis we can write as many conditions. Example:
(a>b &&a >c)?cout<
Ans. Operators in C++ can be classified on the following basis:
1. Arithmetic operators
2. Relational operators
3. Comparison operators
4. Bit wise operators
5. Unary operators
6. Special Operators Like Comma, New, Delete, Scope, New, Delete.
Q34. What is the difference between “b” and ‘b’?
Ans. ‘b’ is in single quotes so it is character whereas “b” is in double quotes, it is treated as string.
Q35. What is a reference variable?
Ans. It is new type of variable provided by C++. It provides facility of alias name or alternative name. For example: If we make variable sum as reference variable to total, sum then total can be interchangeably used to represent that variable.
Syntax: Datatype & reference-name=variable name
Example:
float total=100;
float sum=total;
Q36. Differentiate between a structure and an array.
Ans. Structure and array both are user defined data types. But structure is collection of dissimilar data type whereas array is collection of similar data type.
Q37. What are the various characteristics of object oriented languages?
Ans. Characteristics of object oriented languages
# Early binding # Inheritance # Persistence
# Late binding #Polymorphism #Genericity
#Concurrency # Garbage collection # Object Libraries
C++ supports: - Early and late binding, polymorphism, Concurrency at poor level, Inheritance and Garbage collection.
Q38. What is pointer to a constant?
Ans. int const *ptr2=&m; here ptr2 is declared as pointer to constant. It can point to any variable of correct type, but the contents of what it points to cannot be changed.
Q39. What are the various output statements used in C++? Explain with examples.
Ans. COUT: It can display data of any type. It can print integer, float, character, double type.
Example: cout<PUT: It is used to display output which is a single character.
Example: cout.put(ch);
WRITE: It can display collection of characters or text line as output.
Example: cout.write(line,size);
Q40. How array of things can be allocated and deallocated?
Ans. Array of things can be allocated using new operator and can be deallocated using delete operator.
Int *ptr=new int[20]; will allocate memory for 20 integers.
Delete[] ptr; will deallocate memory .
Q41. How does C++ help to produce flexible and extensible software?
Ans. Using C++ we can create software that can represent real life entities. The systems design using C++ has open interfaces. It provides facility of inheritance using which class can be extended by keeping its previous form as it is and adding new features to it. C++ is flexible because it industrializes software development.
Q42. Can we pass entire structure as argument to function?
Ans. Yes entire structure can be passed as argument to a functional and can also be returned.
For example
struct student
{
char name [20] ;
int age, fee;
};
struct student fi (struct student s)
{
----------
----------
}
Q1. What is a constructor? Can there be more than one constructor?
Ans. A constructor is a special member function for automatic initialization of an object. Whenever an object is created, the constructor will be executed automatically. It has the same name as that of class. It is declared with no return type. A class may have a number of constructors. They can be defined by varying the number of parameters passed in the constructor.
Q2. What are destructors?
Ans. A destructor is a function that automatically executes when an object is destroyed. It is executed when an instance of the class to which it belongs goes out of class or goes out of existence. Some rules for writing a destructor function are:
1) The name of destructor is the same as that of class.
2) The first character of name must be tilde (~)
3) It cannot be overloaded.
4) It has no return type.
5) It cannot accept any parameters.
Q3. What is copy constructor?
Ans. It is used when compiler has to create a temporary copy of a class object. The copy constructors are used in following situations
1) The initialization of an object by another object of same class.
2) Return of objects as function value.
3) Stating the object as by value parameters of a function.
Q4. What are classes? How classes are different from structures?
Ans. A class is a user defined data type, which holds both the data and functions. The internal data of a class is called member data and the functions are called member functions. The member functions mostly manipulate the internal data of a class. The member data of a class should not normally be addressed outside a member function. The variables of a class are called objects or instances of a class.
Structure contains one or more data item, which are grouped together as a single unit. On the other hand class not only contain the data members but also the functions to manipulate that data. Secondly, in a structure, all elements are public by default, while in a class they are private.
Q5. Define Enumerated data types.
Ans. An enumerated data type is user-defined data type, which provides a way for attaching names, thereby increasing comprehensibility of the code. The enum keyword automatically enumerates a list of words by assigning them values 0,1,2 and so on.
enum colour{red, green, blue, pink};
Q6. A friend function cannot be used to overload the assignment operator =. Explain why?
Ans. Although the friend function cannot directly access the members that are declared as private, still the friend function has the right to access these members. In other words, there is nothing a class can hide from its friend.
But the friend function is not within the scope of any class. And it is defined out of class. Also when the function is called, it is called without any object reference. The only need is to pass the object of class as parameters in to the function. So it can not be used to overload=operator
Q7. What is multiple inheritance?
Ans. Multiple inheritance: multiple inheritance is the process of creating a new class from more than one base classes.
Syntax:
Class A {
-
-
-
}; Class B {
-
-
-
};
Class C : public A, public B
{
-
-
};
The class C is derived from both classes A and B. In multiple inheritance a class is derived to inherit the properties of two or more parent classes. Multiple inheritance can combine the behavior of multiple base classes in a single derived class. It has advantages over single inheritance .It can combine the behavior of multiple base classes in a single derived class. It has advantages over single inheritance such as rich semantics and ability to directly express complex structures.
Q8. Write a Short Note on Operator overloading.
Ans. The working of an operator can be redefined by using operator overloading .The operators, which already exist in a language, can only be used to make language more natural to read and write. Even debugging of such codes are much easier.
Operator overloading: It is accomplished by means of special function. The function we want to declare as operator overloading function must be of a class. The syntax is
return –type operator operator to be overloaded (parameters ..);
The keyword operator must be preceded by the return type of the functions which gives the compiler, the information that operator is being overloaded.
Q9. How File Handling is done in C++?
Ans. File is a collection of data or a set of characters. There are two types of files in C++. Sequential and Random access. In sequential files the data or text will be stored or read back sequentially. In random access files, data can be accessed and processed randomly.
The following methods are used in C++ to read and write files:
ifstream – To read a stream of object from a specified file.
ofstream – To write a stream of object on a specified file.
The following attributes are used for various file operations:
ios :: in open a file for reading.
ios :: out open a file for writing
ios :: app append at end
ios :: binary open in binary mode.
Q10. What are the various access labels used in the declaration of classes?
Ans. Three types of labels are used:
1. public
2. private
3. protected
Q11. What are pitfalls of operator overloading and data conversion?
Ans. Operator overloading
1. It is not possible to overload all operators.
2. Some programmers try to define everything as an operator so it is over utilized.
3. Operator overloading facility is not available in all type of languages like java.
Data conversion
By converting data from one type to another accuracy is reduced .If we convert float data into an integer then rounding of all digits after decimal reduces accuracy.
Q12. What is nesting of classes?
Ans. Class within class is called nested class
Here class is declared as member of another class.
The name of nested class is local to enclosing class.
Class student {
private
char name [20]
int roll no ;
public :
class date {
private :
int day, month, year;
public:
}; // end of date class
}; //end of student class
Q13. What do you mean by object reference?
Ans. C++ allows the use of a reference, which is simply another name of object that is being initialized.
Class o;
Class &o1=o;
Here o1 is alternative name of o.
Q14. What is late binding? What is early binding? How these bindings are implemented?
OR
What is static polymorphism? What is dynamic polymorphism?
Ans. Early binding: Choosing a function in normal way, during compilation time is called as early binding or static binding or static linkage or static Polymorphism. During compilation time, C++ compiler determines which function is used based on parameters passed to the function or function return type. The compiler then substitutes the correct function for each invocation.
By default, c++ follows early binding. C++ supports late binding also. Late binding is called as run time binding or execution time binding or dynamic polymorphism. Late binding is implemented using virtual function.
Q15. What is hybrid inheritance?
Ans. It is combination of more than one inheritance. In following figure class1, class 2, class3 are related to each other using the concept of multilevel inheritance. Whereas class2, class 3, class 4 are related using the concept of multiple inheritance. So overall concept is of hybrid inheritance. By combining all four classes we get hybrid inheritance
Class1
class2 class3
Class4
Q16. How pointer to a class is declared?
Ans. The pointer will hold address of object of class .The pointer to object of class can be accessed using following syntax:
Objectname -> membername=variable;
Or
(*Objectname).membername=variable;
Q17. How inheritance works in different labels? Explain with suitable example.
Ans. In public inheritance:
1 Each public member in the base class is public in the derived class.
2 Each protected member in the base class is protected in the derived class.
3 Each private member in the base class is private in the derived class.
In private inheritance:
1 Each public member in the base class is private in the derived class.
2 Each protected member in the base class is private in the derived class.
3 Each private member in the base class is private in the derived class.
In protected inheritance:
3 Each public member in the base class is public in the derived class.
4 Each protected member in the base class is protected in the derived class.
5 Each private member in the base class is private in the derived class.
Q18. What is this pointer?
Ans. C++ uses a unique keyword called ‘this’ to represent an object that invokes a member function. this is a pointer that points to object for which this function was called. For example the function call A. max() will set the pointer to the address of the object A. The starting address is the same as the address of the variable in the class structure.
Q19. What is default constructor?
Ans. The constructor without arguments is called as default constructor. It has no return type. It has same name as that of class. It is automatically called when object of classes is created.
Class abc
{
private:
---------
---------
public:
abc();
----------
---------
};
void main()
{
abc();
-------
}
Q1. What are the different file modes?
Ans. There are three file opening modes
These are:
Read mode
Write mode
Append mode
Various streams are used to open the files in such modes, these are:
ios :: in:- For read mode
ios :: out:- For writing in a file
ios :: app:- Append at end of file
ios::ate:- Goto end of file on opening.
The file can also be set to be a binary file by using binary keyword as - ios :: binary
Q2. What is use of redirection operator?
Ans. The << and >> are used as redirection operators. These operators accept output from one stream that output will act as input to other stream.
Q3. What is a stream?
Ans. Stream: It is defined as collection of bytes. It acts either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to program is called as input stream and destination stream that receives output from program is called as output stream.
Q4. What is Buffer?
Ans. It is a temporary memory used to store data. Fstream class inherits two buffers one for input and another for output, and synchronizes the movement of the file pointers on these buffers.
Q5. What are the functions available in C++ to manipulate the file pointers? Explain.
Ans.
Open (): This is the function used to open a file. A string parameter, which is actually the name of the file to be opened, is passed to the function.
Close (): This is the function used to close the already opened file.
Eof (): this function is used to check whether a file pointer has reached at end of the file.
Fail (): The function return true if it failed to open the file requested.
Q6. What is a priority queue?
Ans. Priority queues are essentially a list of items in which each item has a priority associated with it. The priorities are associated depending on preference rules. Different items have different priorities to them. An item having higher priority is given preference over lower priority. Priority queues are generally used by the operating system to manage various resources such as printer and processor.
Q7. How is the mid point in a binary tree calculated?
Ans. Root of the binary tree is considered to be the mid point of the tree.
Q8. What is an array? How array is stored in memory?
Ans. Array is collection of homogeneous data elements. They are stored in continuous memory locations. They are accessed by using index value.
Int a[5];
12 4 45 67 68
1000 1002 1004 1006 1008
1000 is the location of the first element of the array. As the int data type takes two bytes of the memory so the next element is stored at 1002 and so on.
Q9. Define multidimensional array.
Ans. Multidimensional arrays can be defined as two or more arrays clubbed together. The array that is grouped together can be two dimensional in nature or more. An example of the two dimensional array is the matrix
Q10. Differentiate between structured and modular programming.
Ans. When a monolith software is divided into modules is called modular programming. It is easy to solve a smaller problem than a bigger problem. All the modules are combined to solve a bigger problem.
A structured approach follows the concept of coupling, cohesion, information hiding, DFD’s etc.
Q11. What is garbage collection?
Ans. The operating system of a computer may periodically collect all the deleted spaces onto the free storage list. Any technique, which does this collection, is called Garbage Collection. This collection can be done in two passes:
Marking phase: In this phase all the allocated block are tagged.
Collection Phase: In this phase all the untagged blocks are stored into free list.
Q12. Give two applications of binary tree.
Ans. User interface: The best example for this is file system organization and windows graphical interface.
Database System: Balanced search trees are good in situations that require both sequential efficiency and random access while performing insertion and deletion.
Q13. What do you mean by circular queue?
Ans. A circular queue is the same as a queue but the front and rear ends of a queue are joined together to form a circular ring.
Q14. What is value of following postfix expression?
5, 4, 6, +, *, 4, 9, 3, /, +, *
Ans. 350.
Q15. Define AVL tree.
Ans. A binary search tree in which the difference of heights of the right and left sub-trees of any node is less than or equal to one is known as AVL tree. The name is derived from the names of inventors who are Adelson-Velskii and Landi.
Q16. What do you mean by sparse matrix?
Ans. An m x n matrix is said to be sparse if many of its elements are 0. A matrix that is not sparse is called dense matrix.
Q17. What is a stack?
Ans. A stack is a list of elements in which an element may be inserted or deleted only at one end, called the top of the stock.
Q18. Define queue.
Ans. A queue is a linear list of elements in which deletions can take place only at one end, called the ‘front’ & insertions can take place only at the other end called the ‘rear’.
Q19. What is a linked list?
Ans. A linked list or one-way list is a linear collection of data elements, called nodes, where the linear order is given by means of pointers. Each node is divided into 2 parts. The first part contains the information of the element & the second part called the link field, contains the address of the next node in the list.
Q20. What is binary search tree?
Ans. A binary tree in which all elements in the left subtree of a node are less than the contents of root & all elements in the right subtree are greater than or equal to the contents of the root. Such a tree is called a binary search tree.
Q21. What are the applications of binary trees?
Ans. A binary tree is a useful data structure when two- way decisions must be made at each point in a process. E.g. Suppose that we want to find all duplicates in a list of numbers. The no. of comparisons may be reduced by placing the first number in the root. Each successive node is compared to the root, if it matches, we have a duplicate of a number is lesser, we examine the left subtree, else if it is larger, we examine the right subtree.
Q22. What is the level & height of a binary tree?
Ans. Level: The level of any mode is equal to length of its path from root to the mode: The root of any tree has level equal to zero.
Height: It is equal to one + maximum level in a tree.
Q23. What is a data structure?
Ans. The logical or mathematical model of a particular organization of data is called a data structure.
Q24. Differentiate between linear & non-linear data structure.
Ans. 1. Linear Data Structure:
A data structure is said be linear if its elements are stored sequentially in the form of a linear list e.g. stacks, linked lists.
2. Non-linear Data structure:
A data structure is said to be non-linear if its elements are not stored sequentially in the form of linear list e.g. trees & graphs.
Q25. What are the applications of stacks?
Ans. Using stacks, we can perform the process of recursion. Stacks are used in recursion to fetch an element from top one by one. The other application of stack is calculation of postfix expression where each operator is fetched one by one.
Q26. What are the applications of queues?
Ans. One of the important areas to which queues can be applied is that of simulation. It is the process of forming an abstract model from a real situation in order to understand the impact of modifications & the effect of introducing various strategies on the situation. The major advantage of simulation is that it allows experimentation without modifying the real situation. Areas such as military operations are safer to simulate.
Q27. What is dequeue?
Ans. A dequeue also known as double ended queue is a link of queues in which elements can be added or removed from at either end but not in the middle.
Q28. What is time & space complexity?
Ans. Time complexity is related to the performance requirements of an algorithm.
Space complexity is the amount of memory it needs to run to completion.
Q29. What are primitive data structures?
Ans. These are the data structures that are directly operated upon by machine level instructions. Examples are integers, real numbers, characters, logical data item etc.
Q30. What is a doubly linked list?
Ans. A singly linked list can move only in one direction in certain applications, it is sometimes required that the list be traversed in either a forward or reverse direction. This property of a linked list implies that each mode must contain two link fields instead of one. The links are used to denote the predecessor & successor of a mode. The link denoting the predecessor & of a node is called the left link & that devoting its successor is called the right link. A list containing this type of mode is called a doubly linked list.
LONG QUESTIONS
Q1. What are the different data types available in ‘C++’?
OR
In how many ways we can represent an integer?
Ans. When programming, we store the variables in our computer's memory, but the computer must know what we want to store in them since storing a simple number, a letter or a large number is not going to occupy the same space in memory.
Various data types are:
1. Character data type: any character belonging to the ASCII character set is considered as a character data type whose maximum size is 8 bits long. The ‘char’ keyword is used to represent character data type in C++. Character constants are always represented within single quotes.
2. Integer data: the keyword ‘int’ stands for the integer data type in C++ and its size is either 16 or 32 bits. A 16-bit integer may fall in the range of -215 to 215 -1, while 32 bit integers may fall in the range of -231 to 231 - 1.
Various integer data types are:
a) Short integer data type: Normally the ‘short int’ is used to declare the short integer data type in C++. Its maximum size is 16 bits long. It may fall in the range between
-32768 to 32767.
b) Long integer data type: The ‘long int’ stands for the long integer data type used in C++. Its size is 32 bits. It may fall in the range of -2147483648 to 2147483647.
3. Floating point data type: The numbers which are stored in the form of floating point representation are known as floating point numbers. They can be declared as ‘float’ in C++ whose maximum size is a rational number approximately between -0.17e38 and 0.17e38. The smallest value other than 0 that can be represented is 0.29e-38 in C++.
4. Double data type: ‘double’ is a keyword that is used to represent double precision floating point numbers in C++. The size of double is a rational number in the same range as float and is stored in the form of floating point representation with binary mantissa and exponent.
5. Void: It means nothing.
Q2. What are pre processors? Write a program to define a macro with parameters using #define pre-processor.
Ans. Preprocessor is a program that modifies the C++ source program according to directives supplied in the program. The preprocessor does not modify the actual program, but creates a new file that contains the processed version of the program. This new file is then submitted to the compiler.
The preprocessor carries out the following actions:
1 Replacement of defined identifiers by piece of text.
2 Conditional selection of parts of the source file.
3 Inclusion of other file.
4 Renumbering of source file and renaming of the source file itself.
Program with definition of macro with parameter:
#define SQUARE (x) x*x
#include
void main( )
{
int a=SQUARE (5);
int b=SQUARE(6);
cout<< a<}
Q3. What do you mean by manipulators? Explain some inbuilt I/O manipulators.
Ans. Manipulator functions are special stream functions that change certain characteristics of the input and output. They change the format flags and values for a stream. They facilitate formatting the input and output streams. The input and output manipulators can be used in the program by including the file
Endl. The endl is an output manipulator. It generate carriage return or line feed.
Setbase( ). It is used to convert the base of numeric value into another base.
Dec – decimal base (base=10)
Hex - hexadecimal base (base=16)
Oct – octal base (base =8)
Setw ( ) The setw( ) stands for set width. It is used to specify the minimum number of character positions on the output field a variable will consume.
Setfill( ) The setfill( ) manipulator function is used to specify a different character to fill the unused field width of the value.
Q4. What are the different control structure available in ‘C++’? Explain with example.
Ans. Control statements are used to make decision. These statements are required to take an action according to the condition. The various control statements are as under: -
1. if statement 2. if – else statement 3. nested if
1. if statement :- Executes the statements if condition is true.
Syntax: -
if (condition)
{
statements;
}
2. if–else statement: - Executes the block of statements if condition is true. Otherwise execute else block.
if (condition)
{
statements;
}
else
{
statements;
}
3. Nested if :- Executes one block out of number of blocks of statements which specify the condition other wise executes else block statements.
if (condition)
{
statements;
}
else if(condition)
{
statement;
}
else
{
statements;
}
Case statements :- These statements are used to make decision from the number of choices. In “C++” case control instruction is the switch statement.
Switch statement :- switch statement provide better alternative for series of if –else statements, because any part of the code can be executed on the value of an expression.
Syntax: -
switch(expression)
{
case value:
statement1;
case value:
statement2:
default:
statements
}
Default statement is used as optional.
Branching statements: These statements transfer the control to another part of the program. There are three types of branching statement.
(a) Continue statement
(b) Break statement
(c) Goto statement
i. continue :- The continue statement takes the control at the beginning of the loop and remaining statements skipped and control move to the last stub.
ii. break :- The break statement is used to terminate the loop or a sequence of statement in a switch statement. A break statement enforces immediate termination of program.
iii. goto :- The goto statement is used to alter the normal sequence of program execution by transferring the control to some of the defined level in the program.
Syntax
goto label;
label :
statements;
Iterations statements/Loop statements: - Loops are used execute a set of statements repeatedly until desired condition is meet. There are different types of loops in C++
1. while
2. do while
3. for
While loop: -
This statement is used to execute the loop till the condition true.
while (expression or condition)
{
statements
}
Do while: -
Statements will execute when the condition is true but in this loop the statements will execute first then condition checked.
do
{
statements
}while (expression);
For loop: -
In the for loop the initialization , condition and increment or decrement can be done at one place.
for (initial value; expression; increment/decrement)
{
statements ;
}
Q5. Write a program to calculate the sum of all odd numbers between 1 and 1000.
Ans.
#include
#include
void main( )
{
int i;
long int sum=0;
for(i=1;i<=1000;i+=2)
sum+=i;
cout<<”Sum of odd numbers between 1 and 1000 is : “<
}
Q6. Write a program to input a word. Display on screen “Hello” as many times as, the number of a’s present in the word.
Ans.
#include
void main( )
{
char str[20];
int k;
cout<<”Enter a string”;
cin>>str;
k=0;
while(str[k] !=’\0’)
{
if(str[k]==’a’)
cout<
}
}
Q7. Why do we use functions and what are its advantages?
Ans. Functions are used to divide a program in sub parts. There are different advantages of using functions:
1. Efficiency of maintenance of code
The code written as the body of functions that makes the task simpler. Separating the code into modular functions makes the program easier to design.
2. Ease of understanding
The use of functions makes the program understand easily as each operation is placed in different function. And it can be written or checked immediately.
3. Elimination of redundancy of code
Using this we don’t have any need to rewrite the code again and again to perform the same type of task.
4. Reusability of code
Functions once defined can be used any number of times just by calling them by their name.
Q8. How parameters can be passed to a function. Explain?
Ans. To make the communication between the calling and called functions, parameters can be passed to the functions. Formal parameters are passed to the user-defined function. The communication can be one way or two way. If the function defined does not return any thing then it is one way communication. If the function returns some thing then it is two-way communication.
Example:
int square ( int a) {
statements;
---------
return ; }
Here square is the user defined function getting one parameter of type int. The function is also returning a value of type int.
Q9. What are storage classes? Explain their types.
Ans. The storage class specifier refers to how widely it is known among a set of functions in a program. Storage class provides information about its visibility, lifetime and location. Normally a variable can be declared as belonging to any one of the following groups:
1. Automatic variable
2. Register variable
3. Static variable
4. External variable
Automatic variable: These are also called local or internal variables. They are declared inside a function. They are referred to as automatic because their memory space is automatically allocated as the function is entered and released as soon as it leaves. In other words, automatic variables are given only temporary memory space. Their scope is within the function in which they are declared.
Register variable: The only difference between automatic and register variables is that of their memory location. The register variables are stored in the CPU registers. Thus the time taken to access the register variables is much less than the memory variables. But only limited variables can be declared with register storage class. If there are not sufficient registers to hold these variables then they will be stored in memory, hence will be treated as automatic variables.
Static variables: Static variables are defined within a function and they have the same scope rules as that of automatic variables but in the case of static variables, the contents of the variables will be retained throughout the program.
External variable: Variables, which are declared outside the main, are called external variables. These variables will have the same data type in main and other functions. The life of these variables is in whole program. It can be accessed in each and every function of the program.
Q10. What is recursion? Why recursion is used? Write a program to calculate sum of first five numbers using recursion.
Ans. A function, which calls itself directly or indirectly again and again, is known as the recursive function. Recursive functions are very useful while constructing the data structures like trees. The recursive function will be invoked by itself as long as the given condition is satisfied.
Program to calculate the sum of first five numbers:
int sum(int x)
{
if (x==1)
return 1;
else
return ( x+ sum(x-1));
}
void main( )
{
cout<< sum(5);
getch( );
}
Q11. Create a function to find whether the character is in uppercase or lowercase.
Ans.
#include
#include
void letter(char);
void main()
{
char c;
clrscr();
cout<<”enter any letter”;
cin>>c;
letter(c);
getch();
}
void letter(char c)
{
if((c>'a')&&(c<'z'))
cout<<"letter is in lower case";
else
cout<<"letter is in upper case";
}
Q12. WAP to pass array as parameter in the function and to find the greatest number from the list of array.
Ans.
int greatest (int a[ ] , int n )
{
int j , max ;
max = a[0];
for ( j=1; j
if (max max= a[j];
}
return max;
}
void main ( ) {
int a [ 50 ], n , j ;
cout<<”Enter the range”;
cin>> n;
for (j=0;j
cout<<”Enter the array element “;
cin>> a[j];
}
cout<<”The greatest element in array is”;
greatest( a, n);
}
Q13. WAP to pass a structure in the function as parameter and return the structure from the function.
Ans. struct complex {
float real;
float imag;
};
complex add (complex a, complex b)
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return c;
}
void main( )
{
complex a,b,c;
cout<<”Enter the first complex number”;
cin>>a.real>>a.imag;
cout<<”Enter the second real number”;
cin>>b.real>>b.imag;
c=add(a,b);
cout<
Q14. What is an array? Write a program to sort an array in ascending order.
Ans. An array is collection of elements of homogeneous data type. All the elements in array are referred with common name. An index or subscript is used to access the element in the array.
Program to sort an array:
#include
#include
void main( )
{
nt a[10], i, j, temp ;
for(i=0;i<10;i++)
{
out<<”Enter the array element”;
cin>>a[i];
}
for(i=0;i<9;i++)
{
for(j=i+1;j<10;j++)
{
if (a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(i=0;i<10;i++)
{
cout< }
}
Q15. WAP to display the matrix of two by two.
Ans.
#include
#include
void main()
{
int a[2][2]={{1,2},{2,3}},i,j;
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"Enter element for”<< i+1<<” row”<
}
}
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<}
cout<
getch();
}
Q16. WAP to perform the multiplication of two matrices.
Ans.
#include
#include
void main( )
{
int a[3][3], b [3] [3], c [3] [3], i, j, k;
cout<<”Enter the first array”;
for (i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>a[i][j];
cout<<”Enter the second array”;
for (i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>b[i][j];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
c[i][j]=0;
for(k=0;k<3;k++)
c[i][j] + = a[i][k] * b[k][j];
}
}
for(i=0;i<3;i++)
{
cout<
{
cout<<”\t”<
}
getch( );
}
Q17. What is pointer? WAP to display the values of single dimensional array using pointer.
Ans. Pointer:
Pointer is an indirection operator, which refers to any other variable. Pointers are variables, which store the address of another variable. That variable may be a scalar (including another pointer), or an aggregate (array or structure). The pointer to object may be part of a larger object, such as a field of a structure or an element in an array.
Program to show the elements of an array-using pointer:
#include
#include
#define MAX 100
void show( int * a, int n)
{
int j;
for(j=0;j
void main( )
{
int arr[MAX], n, k;
cout<<”Enter the no. of elements to be entered in array”;
cin>> n;
cout<<”Enter the array”;
for(k=0;k
cout<<”Enter the array element”;
cin>>arr[k];
}
show(arr, n);
getch( );
}
Q18. What is the difference between array of pointers and pointers to an array?
Ans. A pointer to an array contains the address of the first element. In a one-dimensional array, the first element is &[0]. In two dimensional array, it is &value[0][0].
The address of the zeroth row and the zeroth column of the two-dimensional array value is assigned to the pointer variable value.
For example:
int a[ ] [ ];
int *ptr;
ptr=&a[0][0]; // or ptr= a;
Array of pointers:
The pointer may also declared like any other data type. The declaration of an integer pointer array of size 10 is
int *ptr[10];
Where ptr is an array of pointers. It can hold the addresses of various arrays.
Q19. What is the difference between call by value and call by reference? WAP to swap the value of two parameters using pointers.
Ans. Pass by reference passes a pointer to the value. This allows the callee to modify the variable directly. Pass by value gives a copy of the value to the callee. This allows the callee to modify the value without modifying the variable. (In other words, the callee simply cannot modify the variable, since it lacks a reference to it.)
Program to swap two numbers using pointers:
#include
#include
void swap( int * x, * y)
{
int temp;
temp=* x;
*x= * y;
*y=temp;
}
void main( )
{
int first, second;
cout<<”Enter the first number”;
cin>>first;
cout<<”enter the second number”;
cin>>second;
swap(&first, & second); // call by reference
cout<<”After swapping values are :”;
cout<<”First : “<
}
Q20. Write a function that will round floating-point number to an indicator decimal place.
Ans.
#include
void main()
{
float a=5,b=3,c d;
c=a/b;
cout<<”enter d”;
cin>>d;
cout<
Ans.
union stu
{
int a,b;
};
void main()
{
union stu q;
int j;
j=sizeof(q);
cout<
Q22. What is a header file? What is the purpose of using these files?
Ans. A file with extension .h is called header file. It is a library, which contains the definition of various functions. These functions assist the programmer to prepare the program in an efficient manner. These standard libraries come along with the complier as a utility software .The term include is used to include a certain library in your program. As these libraries contain several inbuilt functions, we don't need to redeclare these functions ourselves. we can include a library and use its functions by just calling them with their appropriate parameter.
Most C ++ compliers support the following standard library facilities:
1) Operations on characters 2) Operations on strings.
2) Mathematical operation 4) Storage allocation procedures
5) Input /Output operations
Q23. Using pointer write a program to add two matrixes. [IN EXAM]
Ans.
#include
#include
void main( )
{
int a[3][3], b [3] [3], c [3] [3], i, j, k;
int *p1[3], *p2[3],*p3[3];
cout<<”Enter the first array”;
for (i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>a[i][j];
cout<<”Enter the second array”;
for (i=0;i<3;i++)
for(j=0;j<3;j++)
cin>>b[i][j];
p1=&a[0][0];
p2=&b[0][0];
p3=&c[0][0];
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
p3[i][j] = p1[i][j] + p2[i][j];
}
}
for(i=0;i<3;i++)
{
cout<
{
cout<<”\t”<
}
getch( );
}
Q24. Program to convert decimal into hexadecimal.
Ans.
# include
# include
#include
void main ()
{
long int n, m; char res[20]; int r,i;
for (i =o; i<20;c++)
res [i] =\;; // to initialize string
i=0;
cont<<' counter the number ; cin >> n;
m=n;
while (m >0)
{
r= m%16;
if (r<=a)
{
res[i] = r +'0'
{
res[i]= r+'0';
}
else
{
switch (a)
{
case 10: res[i] ='a';
break;
case 11: res[i] ='b' ; break;
case 12; res[i] ='c' break;
case13: res [i] ='d' break
case 14: res[i] ='e' break
case 15: res[i] ='f' break
}
}
i++i
m/16;
}
straw (res);
cout <<' Hexadecimal equivalent of "<
}
Q25. WAP to sort an array using pointer.
Ans.
# include
#include
#define MAX 100
void sort( int * a, int n)
{
int i, temp, j;
for( i=n;i>0;i--)
{
for( j=0;j{
if (a[j]>a[j+1])
{
temp=*a[j];
*a[j]=*a[j+1];
*a[j+1]=temp;
}
}
}
}
void main( )
{
int arr[MAX], n , index;
cout<<”Enter the size of array”;
cin>>n;
for(index=0;index
cout<<”Enter the array elements”;
cin>>arr[index];
}
sort( &arr[0],n); // function called and reference to the array is passed
cout<<”Sorted array is “;
for(index=0;index
}
Q26. Write a program to count number of vowels, consonants, blank spaces and words in a line of text.
Ans.
#include
#include
#include
void main()
{
int cons=0, vow=0, bsp=0, w=1, I=0;
chat str[50];
cout<<”Enter a string”;
gets(str);
while(str[I] !=’\0’)
{
if((str[I]>=’a’ && str[I]<=’z’) ||(str[I]>=’A’ && str[I]<=’Z’))
{
if((str[I] ==’a’ || str[I]==’e’ || str[I]==’i’ || str[I]==’o’ || str[I]==’u’)||(str[I] ==’A’ || str[I]==’E’ || str[I]==’I’ || str[I]==’O’ || str[I]==’U’))
{
vow++;
}
else
cons++;
}
}
else if( str[I]==’ ‘)
{
bp++;
w++;
}
I++;
}
cout<<”Number of vowels are”<
}
Q27. Explain IF Statement in detail.
Ans. SIMPLE IF
if (condition)
{
statements
}
if ..... else
if (Condition)
{
statement
:
}
else
{
statements
:
}
If ladder
if (Condition)
{
if (condition)
{
statements
}
else
{
statements
}
}
else
{
statements
}
Q28. What is register storage class?
Ans. The variable, which requires to be processed more then other can be set as register storage class. For example the variable used as index variable in for loop may be set register storage class.
e.g.
void main()
{
int a[10];
register int i;
for (i=0 ; i<10; i++)
{
cout << Enter array element;
cin >> a[i];
}
for (i=0; ; i<10; i++)
cout << end l<< a[i];
}
Q29. Program to add all odd no's between 10-1000.
Ans.
void main ()
{
long int s=0, i;
for (i =11 ; i<1000 i +=2)
s+= i;
cont << " sum is << s;
float Average (int n)
{
int i, a;
float s=0;
for (i =o << = n; i ++)
{
cout << Enter the number
cin >> a;
s= s+a;
}
s= s/n;
}
s=s/n;
}
void main ()
{
int n;
float avg
cout << Enter the value of n;
cin >> n;
Avg = Average (n);
cout << Average is << avg ;
} Q30. Program to maintain student record using structure.
Ans.
struct student {
char name [20] :
int age ;
char sex ;
};
vid showdata (student ):// Prototype
void main ()
{
student s;
cut << Enter name of student ";
cin >> S. name ;
cout << Enter age;
cin>> s.age;
cout << Entete Sex;
cin >> s. sex;
showdata (s) : // Function call
getch ();
}
void showdata (student S )
{
cout << Name : << s. name;
cout << endl<<"age;""<< S.age;
cout << endl<<"Sex:"<< s. sex ;
}
Q31. Program to print string in reverse order.
Ans.
#include
void main()
{
char n[20],n1[20];
int c=0,i;
clrscr();
cout<<"enter string";
gets(n);
for(i=0;n[i]!=NULL;i++)
{
c++;
}
for(c=c-1,i=0;c>=0;c--,i++)
{
n1[i]=n[c];
}
n1[i]='\0';
char *p;
i=0;
while(n1[i]!='\0')
{
p=&n1[i];
cout<<*p;
i++;
p++;
}
} Q32. Write a program, which solves the following expression:
(a) c=a+b (b) c=a-b (c) c=a*b (d) c=a/b
Ans.
void main()
{
int a,b,c;
cout<<”enter a and b”;
cin>>a>>b;
c=a+b;
cout<
cout<
cout<
cout<
Q33. What do you mean by string handling? Explain all the string handling functions with examples?
Ans. String library functions are the functions, which are used regularly and stored in library file and whenever these functions are needed, you need to include the required header file in your program.
There are different types of functions
Strlen(): This function is used to count the characters in a string. It calculate the length of the string.
Syntax:
strlen(array variable);
strcpy(): This function copies the contents of one string into another
Syntax:
strcpy(target,source);
strcat(): This function is used to concatenate the source string at the end of the target string.
Syntax:
strcat(target,source);
strcmp(): This function compares the two strings to find out whether they are same or different. The two strings are compared character by character until there is a mismatch or end of the string. These function returns 0 if both the strings are identical.
Syntax:
strcmp(string1,string2);
Q34. Write various paradigms, tools, notations and graph used in object oriented system development.
OR
What are characteristic of object oriented languages?
Ans. Definition:
Using object oriented programming language we can represent information as series of objects. Object will be of class type. Once class is created, any number of objects of that class type can be created.
PARADIGMS:
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data structures are designed such that they characterize the objects.
4. Functions that operate on data of an object are tied together in the data structure.
5. Data is hidden and cannot be accessed by external functions.
6. Objects may communicate with each other through functions.
7. New data and functions can be easily added whenever necessary.
8. It follow bottom up approach in program design.
TOOLS
1. Rational rose
2. Reqisite pro
NOTATIONS AND GRAPH
1. Object Diagram
2. Use case Diagram
3. Collaboration Diagram
4. State Diagram
5. Activity Diagram
6. Physical Diagram
7. Deployment Diagram
8. Component Diagram
Q35. Write a program to display the characters line by line.
Ans.
#include< fstream.h>
#include
int main()
{
char string[80];
cout <<”enter string”;
cin>> string;
int len=strlen(string);
fstream file;
fileopen(“TEXT”, ios::in | ios::out);
for(int i=0;i
file.seekg(0);
char ch;
while(file)
{
file.get(ch);
cout<
return 0;
} Q36. Write a program to print the pascal triangle.
Ans.
void main()
{
int i,j,l,m,n;
cout<<”enter no of rows”
cin>> n;
m=1;
for(i=1;i
for(i=40-3*l;i>0;i--)
cout<<” “;
for(j=0;j<=l;j++)
{
if((j==0)|| (l==0))
m=1;
else
m=(m*(l-j+1))/j;
cout<
cout<
getch();
}
Q1. Write a program to create a class that can store the data of two employees.
Ans.
#include
#include
class employee{
char name[20],design[20];
long int bsal, age;
public:
void getdata( )
{
cout<<”Enter the name of employee”;
cin>>name;
cout<<”Enter the age of employee”;
cin>>age;
cout<<”Enter the designation”;
cin>>design;
cout<<”Enter the basic salary”;
cin>>bsal;
}
void showdata( )
{
cout<<”\nName : “<
};
void main( )
{
employee e1,e2;
e1.getdata( );
e2.getdata( );
e1.showdata ( );
e2.showdata( ) ;
}
Q2. Write a program using classes to find the roots of quadratic equation.
Ans.
#include
#include
#include
class Quad{
int a,b,c;
float d, alpha, beta;
public:
void getabc( )
{
cout<<”Enter the values of a, b & c”;
cin>>a>>b>>c;
}
void calc( )
{
d=b*b – 4*a*c ;
if (d==0)
{
cout<<”Roots are same “;
alpha= -b/2*a;
cout<
else if (d<0)
cout<<”Roots are imaginary”;
else
{
alpha= (-b + sqrt(d)) /2*a;
beta= (-b - sqrt(d)) /2*a;
cout<<”alpha : “<
}
};
void main( )
{
Quad obj;
obj.getabc( );
obj.calc( );
getch( );
}
Q3. Using operator overloading, write a program for complex number operation like ‘+’ and ‘-‘.
Ans.
#include
struct comp{
float real;
float imag;
};
comp operator+(comp a, comp b)
{
comp c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return (c );
}
comp operator –(comp a, comp b);
{
comp c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return ( c );
}
void main( )
{
comp a,b,c;
cout<<”Enter 1st complex number”;
cin>>a.real>>a.imag;
cout<<”Enter 2nd complex number”;
cin>>b.real>>b.imag;
cout<<”Complex number operations”;
cout<<” a - > add”<<”s - > subtract “;
cout<
cin>>ch;
switch ( ch)
{
case ‘a’ : c=a+b;
cout<
case ‘s’: c=a-b;
cout<<”subtraction of numbers is :”;
cout<
}
} Q4.Write a Program that removes duplicates from a string list of n numbers.
Ans.
#include
#include
int n;
void dele (int * a, int loc)
{
int i ;
fol (i=loc ; i
}
n--;
void main ()
{
int a [100] , b[100], i, fi
cout << Enter the range in array ";
cin>> n;
for (i=0; i<100;I++)//to initialize b array .
b[i]=-1
for (i=0;I
cout << Enter array elements'
cin>> a[i];
}
i=b[0], j=a[0];
for (i=1; i
for (i=0; j{
if (a[i]= = b[i]
{
dele (a,i); break;
}
}
if (i = = j)
b[j] = a[i];
}
cout << after removal list is << endl;
for (i=o i
Q5. What is Inheritance? What are its Advantages and types?
Ans. Inheritance is the process of creating new classes, called derived classes, from existing classes, the existing class is the base class. The derived class inherits all the capabilities of the base class but can add properties of its own
Advantages: -
-Protection can be increased in derived classes.
-The derived class can add data and function members to the class without affecting the
-Base class behavior.
-Code reusability
Types: - 1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hybrid inheritance.
5. Hierarchical inheritance
Q6. What is the use of static keyword in ‘C++’? Why are static members created in a class?
Ans. The main characteristic of the static variables is that the static variables are automatically initialized to zero unless it has been initialized by some other value explicitly. In C++, static member of a class can be categorized into two types, static data member and static member function. Whenever a data or function member is declared as a static type, it belongs to a class, not to instances or objects of the class.
Static data member:
Static data members are data objects that are common to all the objects of a class. They exist only once in all objects of this class. They are already created before the finite object of the respective class. This property may lead a person to think that static data member is same as that of global, but it is not true. Static data member may be declared as private, protected or public.
Static member function:
The keyword static is used to precede the member function to make a member function static. The static function is a member function of a class and the static member function can manipulate only on static member data of the class. The static member function acts as global for members of class without affecting the rest of the program. The purpose of static member is to reduce the need for global variables.
Q7. What are the different types of friend functions? Explain each with example.
Ans. Friend function is a special mechanism for letting non- member functions access private data. A friend function may be either declared or defined within scope of a class definition. The keyword friend informs the compiler that it is not a member function of the class.
Accessing private data by non member function through friend
The friend function can access the private members of a class. When it is necessary to access the private data by non- member functions, then a class may have a friend function.
Example:
#include
class sample
{
private :
int x;
public:
void getdata( )
{
cout<<”Enter the value of x”;
cin>>x;
}
friend void display( sample);
};
void display(sample abc)
{
cout<<”entered number is “<
void main( )
{
sample obj;
obj.getdata( );
display(obj);
}
Friend function with inline substitution:
If a friend function is defined within the scope of the class definition, then the inline code substitution is automatically made. If it is defined outside the class definition, then it is required to precede the return type with the keyword inline in order to make a inline code substitution.
Example:
#include
class sample{
private :
int x;
public:
inline void getdata( )
{
cout<<”Enter the value of x”;
cin>>x;
}
friend void display( sample);
};
inline void display(sample abc)
{
cout<<”entered number is “<
void main( )
{
sample obj;
obj. getdata( );
display(obj);
}
Q8. Write a program to grant friendship to another class.
Ans. A class can have friendship with another class. Let there be two classes, first and second. If the class first grants its friendship with the other class second, then the private data members of the class first are permitted to be accessed by the public members of the class second.
#include
class first
{
friend class second;
private:
int x;
public :
void getdata( )
{
cout<<”enter the number”;
cin>>x;
}
};
class second
{
public:
void disp (first a);
};
inline void second::disp(first a)
{
cout<<”Entered number is “<
void main( )
{
first objx;
second objy;
objx.getdata( );
objy.disp(objx);
}
Q9. Write a program to define two classes having the same friend.
Ans. A non-member function may have friendship with one or more classes. When a function has declared to have friendship with more than one class, the friend classes should have forward declaration. It implies that it needs to access the private members of both classes.
Example:
class second;//forward declaration
class first
{
private:
int x;
public:
void getdata( )
{
cout<<”enter the value for x”;
cin>>x;
}
void disp( )
{
cout<<”Entered number is (x)”<
friend int sum(first , second);
};
class second{
private:
int y;
public:
void getdata( )
{
cout<<”Enter the value for y”;
cin>>y;
}
void display( )
{
cout<<”Entered number is (y) “<
friend int sum(first, second);
};
int sum( first one , second two)
{
int c;
c=one.x+two.y;
return c;
}
void main ( )
{
first a;
second b;
a.getdata( );
b.getdata( );
a.disp( );
b.display( );
int c=sum(a,b);
cout<<”Sum of the two private data variables is “<
Q10. What is function overloading? How the compiler will decide which function to use? Explain with example.
Ans. Function overloading is a logical method of calling several functions with different arguments and data types that perform basically identical things by the same name.
The compiler classifies the overloaded function by its name and the number and type of arguments in the function declaration. The function declaration and definition is essential for each function with the same function name but different arguments and data types.
In this example, a function ‘ Add ‘ is overloaded to find the sum of integer variables.
if we pass a&b then Add(int ,int) is executed.
if we pass a,b&c then Add(int ,int,int) is executed.
If we pass a,b,c,d then Add(int ,int,int,int) is executed.
#include
void Add(int,int);
void Add(int,int,int);
void Add(int,int,int,int);
void main( )
{
int a=4,b=5,c=6,d=7;
Add(a,b);
Add(a,b,c);
Add(a,b,c,d);
}
void Add(int a,int b)
{
cout<<“sum of a&b=“<}
void Add(int a,int b,int c)
{
cout<<“sum of a,b,c=“<}
void Add(int a,int b,int c,int d)
{
cout<<“a+b+c+d=“<}
Q11. What is operator overloading? How ‘+’ can be overloaded with matrix addition?
Ans. C++ has the ability to overload operators. Objects derived from composed types can accept operators, which would not be accepted otherwise, and we can even modify the effect of operators that they already admit. Here is a list of all the operators that can be overloaded:
+ - * / = < > += -= *= /= << >>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= [] () new delete
To overload an operator we only need to write a class member function whose name is operator followed by the operator sign that we want to overload, following this prototype:
type operator sign (parameters);
#include
class dis {
private :
int feet ;
float inch;
public :
dis( int f,float I)
{
feet = ft;
inch=I ;
}
void getdist( )
{
cout<<“Enter feet :”;
cin>>feet;
cout<<“Enter inch :”;
cin>>inch;
}
void showdist( )
{
cout <
dis operator + (dis);
};
dis dis::operator + (dis d2)
{
int f=feet+d2.feet ;
float I =inch+d2.inch;
while(I>=12)
{
I - =12 ;
f++ ;
}
return dis(f,I)
}
void main( )
{
dis dist1 ;
dist1.getdist( ) ;
dis dist2 ;
dist2.getdist( ) ;
dis dist3 = dist1+dist2;
cout<<“dist=“;
dist3.showdist( ) ;
}
Q12. What is single inheritance? Write a program to show the concept of single
Inheritance.
Ans. Single inheritance:
Single inheritance is the process of creating new classes from an existing base class. The existing class is known as the direct base class and the newly created class is called as a singly derived class.
Single inheritance is the ability of a derived class to inherit the member functions and variables of the existing base class.
Example:
#include
class basic_info{
private:
char name[20];
long int rollno;
char sex;
public:
void getdata( )
{
cout<<”Enter the name of student”;
cin>>name;
cout<<”Enter the rollno”;
cin>>rollno;
cout<<”Enter the sex”;
cin>>sex;
}
void display( )
{
cout<
};
class physical :public basic_info{
private:
float height, weight;
public:
void getdata( )
{
basic_info::getdata( );
cout<<”Enter height and weight”;
cin>>height<
void display( )
{
basic_info::display( );
cout<
};
void main( )
{
physical a;
a.getdata( );
cout<<”\nName \t Rollno \t Sex \t Height \t Weight”;
a.display( );
}
Q13. What is Indirect Base class? Explain with Example.
Ans. Derived class can itself serve as a base class. When a derived class is declared as a base of another class, the newly derived class inherits the properties of its base classes including its data members and member functions. A class is called as an indirect base if it is not a direct base, but is a base class of one of the classes mentioned in the base list.
Example:
class base A
{
-----------
-----------
};
class derivedB:public baseA
{
-----------
-----------
};
class derivedC : public derivedB
{
-----------
-----------
};
derivedB is a base of the class derivedC that is called as in indirect base.
Multiple inheritance
A derived class could inherit from more than one base classes. When this is done it is called multiple inheritance.
Example:
class A {
-----
};
class B{
------
};
class C:public A, public B{
-------
};
The class C is derived from both A and B.
Q14. What is ambiguity in ‘C++’? Write a program to show the ambiguity in multiple inheritance.
Ans. Whenever a data member and member function are defined with the same name in both the base and the derived classes, these names must be without ambiguity. The scope resolution operator may be used to refer to any base member explicitly. This allows access to a name that has been redefined in the derived class.
Example to show how ambiguity occurs in both base class and derived class:
#include
class baseA{
public:
int a;
};
class baseB{
public :
int a;
};
class derivedC: public baseA, baseB{
public :
int a;
};
void main( )
{
derivedC obj;
obj.a=10;// local to the derived class
}
The object of derived class can directly access to its own member rather than the members of the base classes.
If one wants to access the members of base classes then the code can be written like
void main( )
{
derivedC obj;
obj.a=10;
obj.baseA::a=20; // accessing the base class A member
obj.baseB::a=90;// accessing the base class B member;
}
Q15. What are virtual functions? Give types, rules. Explain with example.
Ans. It would be nice if the appropriate member function could be selected while the program is running. This is known as runtime polymorphism. C++ support a mechanism known as virtual function to achieve runtime polymorphism. At runtime, when it is known what class object are under consideration, the appropriate version of the function is called. Since the function is linked with a particular class much later after the compilation, this binding is termed as late or dynamic binding.
Types
1. Simple virtual function(as shown in example below)
2. Pure virtual function(A pure virtual function is a virtual function with no body).
Rules
1. Virtual keyword is necessary with virtual function.
2. Its body can be outside or inside class.
3. Pure virtual function is without body.
//program for demonstration of virtual function
#include
#include
class baseA{
public:
virtual void display( )
{
cout<<”\nOne”;
}
};
class derivedB:public baseA
{
public:
virtual void display( )
{
cout<<”\nTwo”;
}
};
class derivedC:public derivedB
{
public:
virtual void display ( )
{
cout<<”\nThree”;
}
};
void main( )
{
baseA obja;
derivedB objb;
derivedC objc;
baseA *ptr[3];
ptr[0]=&obja;
ptr[1]=&objb;
ptr[2]=&objc;
for(int i=0;i<3;i++)
{
ptr[i]->display( );
}
}
Q16. Describe the importance of destructor functions and write a program that illustrates the working of destructor function.
Ans. A destructor is a function that automatically executes when an object is destroyed. A destructor function gets executed whenever an instance of the class to which it belongs goes out of existence. The primary usage of the destructor function is to release space on the heap.
PROPERTIES OF DESTRUCTOR FUNCTION:
1. They have same name as that of class.
2. These are automatically called when object is destroyed.
3. They have no return type.
4. These cannot be declared static, const, volatile.
5. They accept no arguments.
#include
#include
class ABC{
public:
ABC( )//constructor
{
cout<<”\nClass initialized”;
}
~ABC( )
{
cout<<”\nData deleted”;
}
};
void main( )
{
ABC obj;
{
ABC obj1;
}
}
Q17. What are inline functions? How are they created in ‘C++’? Explain with Example.
Ans. The inline specifier is a hint to the compiler that inline substitution of the function body is to be preferred to the usual function call implementation.
The size of the object code is considerably reduced with the use of inline function.
The use of inline function increases the execution speed of program.
Program to input date and display it using inline functions:
#include
#include
class date
{
private:
int day,month,year;
public:
void setin(int dayin,int monthin,int yearin);
void show();
};
inline void date ::setin(int dayin,int monthin,int yearin)
{
day=dayin;
month=monthin;
year=yearin;}
inline void date::show()
{
cout<
void main()
{
date d1,d2,d3;
d1.setin(24,5,2000);
d2.setin(30,7,98) ;
d3.setin(13,7,99);
cout<<"first date=";
d1.show();
cout<<"second date";
d2.show();
cout<<"third date";
d3.show();
getch();
}
Q18. Write a program to calculate the area of a triangle, rectangle, circle and square using inheritance.
Ans.
Class Common
{
protected :
int a,b;
float res ;
};
Class triangle : public common
{
public :
void getch ( )
{
cout << “Enter base & height “;
cin a>> b;
}
void showarea ( )
{
res =0.5* a*b;
cout << “Area of triangle”<
};
Class rectangle : public common
{
public :
void getlb ()
{
cout << “enter length & breadth of rectangle “;
cin>> a>> bi;
}
void showarea ()
{ res=a*b;
cout << “Area of Rectangle” << res
}
};
class circle : public common
{
public :
void gets ()
{ cout <<” Enter radius ";
cin >> ai;
} void showarea ()
{
res= 3.14 * a*a;
cout <<” Area of cirlce " << res
}
};
class square : public common
{
public
void getside ()
{
cout <<” Enter side for square " ;
cin >> a;
}
void show area ()
{
res =a*a;
cout << “Area of square”<< res;
}
};
void main ()
{
Triangle t ;
Circle c;
Square s;
Rectangle r ;
t.getch () ;
t.showarea ();
c.gets ();
c.showarea ();
s.getside ();
s.showarea ();
r.getlb ();
r.showarea ();
}
Q19. Write a program to maintain employee record.
Ans.
Class employee
{
private :
char name [20]
int age;
long int basic ;
public :
void get data ()
{
vout <
cout << Enter age & basic pay"
cin >> name :
cout << "Enter age & basic pay:
cin > age >> baisc ;
}
void Show ()
{
cout << Name : << name ;
cout << endl << "age ; <
}
};
Void main ()
{
employee e1 , ez ;
el. getdata();
ez. getdata ();
el . show ();
ez. show ();
}
Q20. Write a program to show operator overloading.
Ans. Class area
{
private:
int a, b;
float ar ;
void input (int a1)
{
a= a1;
}
void input (int a1, int b1)
{
a=a1;
b=b1;
}
Area operator ++ ()
{
ar = 3.14 * a*a;
}
Area operator – ( )
{
ar = a*b;
return * this;
}
Area show()
{
cout<
};
Void main ()
{
Area Rect , Cir;
Rect.input (20, 30);
Rect ++;
Cir.input (10) :
Cir --;
Rect . Show ();
Cir . show ( ) ;
}
Q21. Differentiate between all the conversions.
Ans. 1. Basic to class type
This conversion form basic to class type is easily carried type. It automatically done by the compiler with the help of in-built routines or by applying typecasting. In this the left-hand operand of = sign is always class type and right-hand operand is always basic type. The program given below explains the conversion from basic to class type.
2. Class type to basic data type
In this type, left hand operand is always of basic data type and right –hand operand is always of class type. While carrying this conversion, the statement should satisfy the following conditions:
1. The conversion function should not have any argument.
2. Do not mention return type
3. It should be a class member function.
3. One class type to another class type
When an object of one class is assigned to object of another class. It is necessary to give clear-cut instructions to the compiler. How to make conversion between these two user defined data type. The method must be instructed to compiler. There are two ways to convert object data type from one class to another.
1. Define conversion operator function in source class
2. One argument constructor in a destination class
Q22. Write a c++ program to extract a row or column from a matrix.
Ans.
#include
#include
void main()
{
int a[10][10],m,n,i,j,p,q;
clrscr();
cout<<"enter no of row and col";
cin>>m>>n;
cout<<"enter data in matrix";
for(i=0;i
cout<<"display data in matrix";
for(i=0;i
for(j=0;j
cout<<"\t"<}
cout<<"\n";
}
}
cout<<"\nenter row to extract";
cin>>p;
for(i=0;i
cout<<"\nenter col to extract";
cin>>q;
for(i=0;i
}
Q23. Write a program to read a set of floating point numbers using concept of overloading.
Ans.
#include
#include
void getdata(int x,int y);
void getdata(int x,int y,int z);
void main()
{
float i,j,k;
clrscr();
cout<<"enter data";
cin>>i>>j>>k;
getdata(i,j);
getdata(i,j,k);
getch();
}
void getdata(int x,int y)
{
cout<<"sum="<
void getdata(int x,int y,int z)
{
cout<<"sum="<
Q24. Write a C++ program that declares a class called employee with data members: name, father name, residence address.
Ans.
class employee
{
private:
char name[10];
char fname[20];
char address[20];
public:
void getdata();
{
cout<<”enter data”
cin>>name;
cin>>fname;
cin>>address;
}
void display()
{
cout<
};
void main()
{
employee e;
clrscr();
e.getdata();
e. display();
getch();
}
Q25. What are different types of membership functions? Explain structure of class.
Ans. Membership functions:
1. Constructor
2. Friend function
3. Destructor.
4. Static member function
5. Virtual function
6. Inline member function
STRUCTURE OF CLASS
Class
{
private:
datamember 1;
datamember 2;
datamember 3;
public:
member function1();
member function2();
member function3();
};
Q26. How constructors and destructors can be inherited?
Ans. If any base class contains a constructor with one or more arguments, then it is mandatory for derived class to have a constructor and pass arguments to base class constructors. While applying inheritance we usually create objects using derived class. Thus it makes sense for the derived class to pass arguments to base class constructor.
When both derived and base class contains constructors, the base class constructor is executed first and then constructor in derived class is executed. The constructor of the derived class receives the entire list of values as its arguments and passes them on to the base constructors in the order in which they are declared in the derived class. The base constructors are called and executed before the statements in the body of derived constructor.
General Form of derived constructor:
Base1(arglist1)
Base2(arglist2)
………………
baseN(arglistN)
{
// body of derived constructor
}
Example:
#include
using namespace std;
class alpha
{
int x;
public:
alpha(int I)
{
x = i;
cout<< ”alpha initialized \n”;
}
void show_x(void)
{
cout<< “x = “<
};
class beta
{
float y;
public:
beta(float j)
{
y = j;
cout<< “ beta initialized \n”;
}
void show_y(void)
{
cout<< “ y = “ <
};
class gamma: public beta, public alpha
{
int m, n;
public:
gamma(int a, float b, int c, int d): alpha(a), beta(b)
{
m = c;
n = d;
cout<< “gamma initialized \n”;
}
void show_mn(void)
{
cout<< “ m = “<
};
int main( )
{
gamma g(5, 10.75, 20, 30);
cout<< “\n”;
g.show_x( );
g.show_y( );
g.show_mn( );
return 0;
}
Q27. Can we pass entire structure as argument to function?
Ans. Yes, entire structure can be passed as argument to a function and can also be returned.
For example
struct student
{
char name [20] ;
int age ;
int fee;
};
struct student s[ ];
void main()
{
----------------------
----------------------
fi (struct student s[ ] )
}
struct student fi (struct student s[ ] )
{
-
-
-
-
}
Q28. Using operator overloading, write a program for floating point number operation like ‘+’ and ‘-‘.
Ans.
#include
struct complex
{
float real;
float imag;
};
complex operator +(complex a, complex b)
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return (c );
}
complex operator –(complex a, complex b);
{
complex c;
c.real=a.real+b.real;
c.imag=a.imag+b.imag;
return ( c );
}
void main( )
{
complex a,b,c;
cout<<”Enter the first complex number”;
cin>>a.real>>a.imag;
cout<<”Enter the second complex number”;
cin>>b.real>>b.imag;
cout<<”\nComplex number operations”;
cout<
cout<
cin>>ch;
switch ( ch)
{
case ‘a’ : c=a+b;
cout<
case ‘s’: c=a-b;
cout<
}
}
Q29. Differentiate between abstraction and data hiding. Why classes in C++ are abstract?
Ans. OOP encapsulates data and functions into packages called objects. The data & functions of an object are intimately tied together. Objects have the property of information hiding. This means that although objects may know how to communicate with each other, they normally do not know how other objects are implemented. That is, implementation details are hidden within the objects themselves.
Abstraction is very close to data hiding. Abstraction refers to the act of representing essential features without including the background details or explanations. Data abstraction is concerned with separation the behaviour of data object from its representation or implementation.
Abstract class: An abstract class is one that is not used to create object. Classes that declare a pure virtual function is called an abstract class. It is used as a base class for deriving. It defines properties common to other classes derived from it. Since an abstract class contains one or more functions for which there is no definition, no objects can be created using an abstract class.
Q1. How File Handling is done in C++?
Ans. File is a collection of data or a set of characters. There are two types of files in C++. Sequential and random access. In sequential files the data or text will be stored or read back sequentially. In random access files, data can be accessed and processed randomly.
The handle file fstream in supports the input/outs stream processing techniques. The
Following methods are used in C++ to read and write files:
If stream – To read a stream of object from a specified file. of stream – to write a stream of object on a specified file.
The following attributes are used for various file operations.
ios :: in open a file for reading.
ios :: out open a file for writing
ios :: app append at end
ios :: binary open in binary mode.
Q2. Explain the following functions.
Ans.
a) Eof (): It is function to check whether a file pointer has reached the end of file character or not. It has then the function return non zero else return 0.
b) Fail (): It is used to check if file has been opened successfully. If it fails then it return non zero character.
c) Bad (): It return non zero when invalid file operation has been attempted.
d) Good (): It is function to check whether the previous file operation has been successfully or not.
Q3. What is a random access file? Explain the syntactic rule for the following random access file member function?
a) seekp
b) seekg
c) tellg
d) tellp
Ans. RANDOM FILE: In random access file the file pointer can be moved to any location in the file instead of moving it sequentially. This approach is used with database files.
SEEKP: Moves put pointer to specified location.
E.g. infile.seekp(10);
It will move pointer to 10 number byte.
It can take 2 arguments also.
Seekp(offset,refposition);
SEEKG: Moves get pointer to specified location.
E.g. infile.seekg(10);
It can take 2 arguments also.
Seekg(offset,refposition);
TELLG: Gives the current position of get pointer.
E.g. ofstream fileout;
fileout.open(“hello”,ios::app);
int p=fileout.tellg();
TELLP: Given the current position of get pointer.
E.g. ofstream fileout;
fileout.open(“hello”,ios::app);
int p=fileout.tellp();
Q4. Write an algorithm for Bubble sort & explain with an example.
Ans. Algorithm BUBBLE (DATA, N)
Here DATA is an array with n elements. This algorithm sorts the elements in DATA.
1. Repeat steps 2 & 3 for k = I to N-I
2. Set PTR: = 1 [Initializes pass pointer]
3. Repeat while PTR ≤ N-K [Execute pass]
a) If DATA [PTR] > DATA [PTR +1], then interchange DATA [PTR] & DATA [PTR+1]
[End of If structure]
b) Set PTR: = PTR+1
[End of inner loop]
[End of step 1 outer loop]
4. Exit
Example: 32 51 27 85 66 23 13 57
A1 A2 A3 A4 A5 A6 A7 A8
a) Compare A1& A2: 32 <51 → no change
b) A2&A3: 51 > 27, interchanging 51 & 27
c) A3&A4 : no change
d) A4&A5: 85 > 66, interchange 85 & 66
e) A5&A6: 85 > 23, interchange 23 & 85
f) A6&A7: 85 > 13, interchange 13 & 85
g) A7&A8: 85 > 57, interchange 57 & 85
This is pass 1
Similarly, in every pass the greater element will be moved towards the end.
Since the array has 8 elements, it is sorted after the seventh pass i.e. (n-1) in pass.
Q5. Write non-recursive & recursive procedures to find the factorial of a given number.
Ans.
Procedure: FACTORIAL (FACT, N)
This procedure calculates N! & returns the value of the variable FACT in a non-recursive manner.
1. If N=0, then set FACT:=1&Return.
2. Set FACT: =1 [Initializes FACT for roop]
3. Repeat for K = I to N
Set FACT: = K * FACT
[End of roop]
4. Return
Procedure: FACTORIAL (FACT, N)
This procedure ultimate N! & returns the value in the variable FACT in a recursive manner.
1. If N=0, then Set FACT: = 1 & Return
2. Call FACTORIAL (FACT, N-1)
3. Set FACT = N*FACT
4. Return.
Q6. Explain the basic operations on stack. Write procedures to implement these operations.
Ans. A stack is a list of elements in which an element may be inserted or deleted only at one end called the top of the stack.
The two basic operations performed on stacks are:
i) Push: is the term used to insert an element into a stack.
ii) Pop: is the term used to delete an element from stack.
Procedure: PUSH (STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM on to a stack.
1. [Stack already filled]
If TOP=MAXSTK, than print: OVERFLOW & return.
2. Set TOP: = TOP + 1 [Increases TOP by 1]]
3. Set STACK [TOP]: = ITEM [Inserts ITEM in new TOP position].
4. Exit
Procedure: POP (STACK, TOP, ITEM)
This procedure deletes the top element of STACK & assigns it to the variable ITEM.
1. [Stack has an item to be removed?]
If TOP =0, then Print UNDERFLOW & Return.
2. Set ITEM: =STACK [TOP]. [Assigns top element t item]
3. Set TOP: = TOP-1 [Decreases TOP by 1]
4. Return.
Q7. Write an algorithm for evaluating a postfix expression.
Ans. Following algorithm uses a stack to calculate postfix expression. Suppose P is an arithmetic expression written in postfix notation. The following algorithm, which uses a STACK to hold operands, evaluates P. This algorithm finds the VALUE of an arithmetic expression P written in postfix notation.
1. Add a right parenthesis ‘)’ at the end of P.
2. Scan P from left to right and repeat steps 3 & 4 for each element P until the ‘)’ is encountered.
3. If an operand is encountered, then:
4. If an operator* is encountered, then:
a. Remove the two top elements of STACK, where A is the top element and B is next-to top element.
b. Evaluate B * B
c. Place the result of (b) back on STACK
5. Set VALUE equal top element on STACK
6. Return.
Q8. Write an algorithm for linear search.
Ans. Algorithm: LINEAR (DATA, N, ITEM, LDC)
Hire DATA is a linear array with N elements & ITEM is a given item of information. This algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is unsuccessful.
1. [Insert ITEM at the end of DATA]
Set DATA [N+1]: = ITEM
2. [Initialize counter]. Set LOC: =1
3. Search for ITEM]
Repeat while DATA [LOC] ITEM
Set LOC: LOC +1
[End of loop]
4. [Successful?] If LOC= N+1, then Set LOC: = 0
5. Exit.
Q9. Write an algorithm to search an element from a binary search tree.
Ans.
Variables to be used:
1.INFO is the information field of node.
2.LEFT points to left child
3.RIGHT Points to right child
4.PAR points to parent node
5.LOC points to ITEM if exists otherwise points to NULL
6.ITEM which is to search
7.ROOT is the root of tree
Algorithm:
1. If ROOT=NULL, then LOC:=NULL and PAR:=NULL
2. If ITEM=INFO[ROOT] then set LOC:=ROOT and PAR:=NULL
3. If ITEM
Else:
Set PTR:=RIGHT[ROOT] and SAVE:=ROOT
1.Repeat steps 5 and 6 while PTRNULL:
2.If ITEM=INFO[PTR], then: set LOC:=PTR and PAR:=SAVE and return
3.If ITEM
else
set SAVE:=PTR and PTR:=RIGHT[PTR]
set LOC:=NULL and PAR:=SAVE.
Exit
Q10. Write an algorithm to delete a leaf node or the node, which has exactly one child.
Ans.
Variables to be used:
1.INFO is the information field of node.
2.LEFT points to left child
3.RIGHT Points to right child
4.PAR points to parent node
5.LOC points to ITEM if exists otherwise points to NULL
6.ITEM which is to search
7.ROOT is the root of tree
8.CHILD is the child to delete
Algorithm:
9.If LEFT[LOC]=NULL and RIGHT[LOC]=NULL
Set CHILD:=NULL
Else
if LEFT[LOC]NULL
Set CHILD:=LEFT[LOC]
Else
Set CHILD:=RIGHT[LOC]
10.If PARNULL
If LOC=LEFT[PAR]
Set LEFT[PAR]:=CHILD
Else: Set RIGHT[PAR]:=CHILD
Else:
Set ROOT:=CHILD
11.Return
Q11. Discuss the advantages & disadvantages of circular linked list.
Ans. Circular lists have certain advantages over singly linked list. The first advantage is that in a circular list every mode is accessible from a given mode.
A second advantage is concerned with the deletion operation. As we know that in order to delete a mode in a singly linked list, it is necessary to give the address of the first mode of the list. This is necessary because we need to find the predecessor of the node to be deleted to find the predecessor of a search is required starting from the first node of the list. In the case of circular list, this requirement does not exist since the search for the processor of the mode to be deleted can be initiated from that mode itself.
However, there is a disadvantage in using circular lists. It is possible to get into an infinite loop. In processing a circular list, it is important that we are able to detect the end of the list.
Q12. What are the operations that can be performed on a queue? Write procedures to implement these operations.
Ans. A queue is linear list of elements in which deletions can take place only at one end, called the “front” & insertions can take place only at the other end called the “rear”.
Procedure: QINSERT (Q, F, N, R, Y)
Given F & R, pointers to the front & rear elements of a queue, a queue Q consisting of N elements & an element Y, this procedure inserts Y at the rear of queue. In the beginning, F&R have been set to zero.
1. [Overflow?]
If R≥N then write (OVERFLOW)
Return.
2. [Increment rear pointer]
R: =R+1
3. [Insert element]
Q[R]: =Y
4. [Is front pointer properly set?]
If F=0
Then F:=1
Return.
Procedure: QDELETE (Q, F, R)
Given F&R, pointers to the front & rear elements, & the queue Q, which they correspond, this function deletes & returns the last element of the queue.
Y is a temporary variable.
1.) [Underflow]
If F=0
Than write (‘underflow’)
Return (0) [0 deviates an empty queue]
2.) [Delete element]
Y ←Q[F]
3.) [Queue empty?]
If F=R then F: =R: =0
Else F: =F+1
4.) Return element]
Return (Y)
Q13. Write an algorithm for transforming infix expression into postfix expression with example.
Ans. POLISH (Q, P)
Suppose Q is an arithmetic expression written in infix mutation. This algorithm finds the equivalent postfix expression P.
1. Push “(“ onto STACK & add) “ to the end of Q
2. Scan Q from left to right & repeat steps 3 to 6 for each element of Q until the stack is empty.
3. If an operand is encountered, add it to P.
4. If a left parenthesis is encountered, push it onto STACK.
5. If an operator Q is encountered, then
a) Repeatedly pop from STACK & add to P each operator, which has the same precedence as or higher precedence than Q.
b) Add Q toy STACK
[End of If structure]
6. If a right parenthesis is encountered
c) Repeatedly pop from STACK & add to P each operator until a left parenthesis is encountered.
d) Remove the left parenthesis [Do not add the left parenthesis to P]
[End of If structure]
[End of step 2 Loop]
7. Exit
Example: Q: A+ (B*C-(D/EF) * Gill) # H
Symbol Scanned STACK Expression P
1) A ( A
2) & (+ A
3) ( (+( A
4) B (+( A B
5) * (+(* A B
6) C (+(* A B C
7) -- (+(- A B C *
8) ( (+(-( A B C *
9) D (+(-( A B C * D
10) / (+(-(/ A B C * D
11) E (+(-(/ A B C * D E
12) (+(- (/ A B C* D E
13) F (+ (- ( A B C * D E F
14) ) (+ (- A B C * D E /
15) * (+(- * A B C * D E F /
16) G (+ (- * A B C * D E F/G
17) ) (+ A B C * DE FG*-
18) * (+ * A B C * D E FG*-
19) 1+ (+ * ABC *DEF /G * -H
20) ) ABC DEF/G-H*+
Q14. Write procedure for performing insertion & deletion operations on a circular queue.
Ans. A circular queue is the same as a queue but the front & rear ends of a queue are joined together to form a circular ring.
Procedure: CQINSERT (F, R, Q, N, Y)
1. Reset rear pointer? ]
If R = N then R: =1
Else R: = R+1
2. [Overflow?]
If F = R
Then write (‘overflow’)
Return
3. [Insert element]
Q[R] Y
4. [Is front pointers properly set?]
If F=0
Then F1
Return.
Function: CQDELETE (F, R, Q, N)
1) [Underflow?]
If F=0 then write (‘underflow’)
Return (0)
2) [Delete element]
Y Q [F]
3) [Queue Empty?]
If F=R
Then F: R: =D
Return (y)
4) [Increment front pointer]
If F=N then F:=1
Else F: =F + 1
Return (y)
Q15. Write algorithms for Tree traversals.
Ans. Algorithm PREORDER (T): Given a binary tree whose root mode address is given by a pointer variable Toy, this algorithm traverse the tree in preorder in a recursive manner.
1. [Process the root node]
If Toy NULL then write (DATA (Toy) )
Else write (‘Empty Tree”)
Return.
2. [Process the left subtree]
If LPTR NULL
Then call PREORDER (LPTR (7) )
3. [Process the right subtree0
If RPTR (T) NULL
Then call PREORDER (RPTR (T) )
4. Exit
Algorithm INORDER (T):
1. [Check for empty tree]
If T= NULL
Then write (‘empty tree’)
Return.
2. [Process the left subtree]
If LPTR NULL
Then call IN ORDER (LPTR (T)
3. [Process the root mode]
Write (DATA (T))
4. [Process the right subtree]
If RPTR NULL
Then call RINORDER (RPTR (Toy)))
5. Exit.
Algorithm POSTORDER (T):
1. [Check for empty tree]
If Toy=NULL then write (‘Empty tree’)
Return
2. [Process the left subtree]
If LPTR (T) NULL
Then call POSTORDER (LPTR (T))
3. [Process the right subtree]
If RPTR (Toy) NULL
Then call POSTORDER (RPTR (T))
4. [Process the root mode]
Write (DATA (Toy)
5. Exit
Q16. What are linked lists. How do they overcome the drawbacks of arrays.
Linear Linked Lists
Ans. Linked List
List means to a linear collection of data items. Till now we are storing elements in array. Arrays has some disadvantages like:
1.Wastage of memory, because total space allocated must be known in advance, otherwise enough space can be wasted.
2.Some operations like Insertion and Deletions require extra time, because insertion and deletion requires enough shifting of elements.
Due to these disadvantages we use dynamic memory allocation i.e., using Linked List.
A linked list is a linear collection of data elements, called nodes. Pointers give the linear order. Each node is divided into two or more parts. Concept of linked list uses dynamic memory allocation. A linked can be of the following type.
1 Linear linked list or one-way list
2 Double linked list or two way list
Linear linked list:
In a linear linked list, also called singly linked list, each node is divided in two parts:
1 First part contains the information of the element, and
2 Second part, called the link field contains the address of the next node in the list
We require a pointer variable Start, used that contains the address of the first element of the list. End of list is denoted by NULL. Link field of last node contains NULL.
This is shown in fig
100 101 102 110 x
Head
Q17. Define pointer. Write an algorithm to create a linked list & insert an item into a linked list.
Ans. A pointer is a variable that stores the address of another variable.
Algorithm: INFIRST (INFO, LINK, START, AVAIL, ITEM). This algorithm inserts ITEM as the first mode in the list.
1. [Overflow?] If AVAIL = NULL
then: Write overflow L Exit
2. Remove first mode from AVAIL list]
Set NEW: = AVAIL and AVAIL:= LINK [AVAIL]
3. Set INFO [NEW]: = ITEM [Copies new data into new mode.
4. Set LINK [NEW]: =START [New mode points to original first mode].
5. Set START: = NEW [Changes START so it points to the new mode].
6. Exit.
Q18. Write a program to maintain a file.
Ans.
void main ()
{
ofstreams in file ;
infile .open ("abc. txt");
char name [20]:
int age;
cout<<" Enter name ;"
cin > name;
cout << Enter age";
cin >> age;
infile << name <
}
Q19. Write a program to copy the content of one file to another.
Ans.
#include
#include
#include
void main()
{
ofstream ofile;
ifstream ifile;
char fname1[10],fname2[10];
char ch;
cout<<”Enter the source file name”;
cin>>fname1;
cout<<”Enter the target file name”;
cin>>fname2;
ifile.open(fname1);
if( ifile.fail())
{
cerr<<”File not found”;
return;
}
ofile.open(fname2);
if (ofile.fail())
{
cout<<”can not make file”;
return;
}
while( ! ifile.eof())
{
ch=(char) ifile.get();
ofile.put(ch);
}
ifile.close();
ofile.close();
}
Q20. Using classes write a program to copy text from one file to another.
Ans.
#include
#include
class student
{
private:
char name[20];
int age;
public:
void getdata( )
{
cout<<”Enter the name and age of the student”;
cin>>name>>age;
}
void show( )
{
cout<<”Name : “<
};
void main( )
{
student s;
fstream infile, outfile;
outfile.open(“stucopy”,ios::out); // file opened in write mode
infile.open(“stu”,ios::in); // file opened to read data from
while (! infile.eof( ))
{
infile.read((char *) &s, sizeof( s));
outfile.write((char *) &s, sizeof(s));
}
infile.close( );
outfile.close ( );
outfile.open(“stucopy”,ios::in); // file in which data was copied is opened in read mode
while (! outfile.eof( ))
{
outfile.read((char *) &s, sizeof( s));
s.show( );
}
outfile.close( );
}
*********************************************************************
Programming Puzzles
Some companies certainly ask for these puzzles. Specially Microsoft. Here are my favorite puzzles.
14. Write a "Hello World" program in 'C' without using a semicolon.
15. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
16. C/C++ : Exchange two numbers without using a temporary variable.
17. C/C++ : Find if the given number is a power of 2.
18. C/C++ : Multiply x by 7 without using multiplication (*) operator.
19. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
20. Remove duplicates in array
21. Finding if there is any loop inside linked list.
22. Remove duplicates in an no key access database without using an array
23. Convert (integer) number in binary without loops.
24. Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
25. From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
26. Given an array (group) of numbers write all the possible sub groups of this group.
C/C++ Questions
These are sample questions. Personally I hate asking questions related to code. If you want some old question papers of some Indian IT industries , You many find it here
37. What is the output of printf("%d")
38. What will happen if I say delete this
39. Difference between "C structure" and "C++ structure".
40. Diffrence between a "assignment operator" and a "copy constructor"
41. What is the difference between "overloading" and "overridding"?
42. Explain the need for "Virtual Destructor".
43. Can we have "Virtual Constructors"?
44. What are the different types of polymorphism?
45. What are Virtual Functions? How to implement virtual functions in "C"
46. What are the different types of Storage classes?
47. What is Namespace?
48. What are the types of STL containers?.
49. Difference between "vector" and "array"?
50. How to write a program such that it will delete itself after exectution?
51. Can we generate a C++ source code from the binary file?
52. What are inline functions?
53. Talk sometiming about profiling?
54. How many lines of code you have written for a single program?
55. What is "strstream" ?
56. How to write Multithreaded applications using C++?
57. Explain "passing by value", "passing by pointer" and "passing by reference"
58. Write any small program that will compile in "C" but not in "C++"
59. Have you heard of "mutable" keyword?
60. What is a "RTTI"?
61. Is there something that I can do in C and not in C++?
62. Why preincrement operator is faster than postincrement?
63. What is the difference between "calloc" and "malloc"?
64. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?
65. What is Memory Alignment?
66. Explain working of printf.
67. Difference between "printf" and "sprintf".
68. What is "map" in STL?
69. When shall I use Multiple Inheritance?
70. What are the techniques you use for debugging?
71. How to reduce a final size of executable?
72. Give 2 examples of a code optimization.
**************************************************************8
C++
1. What is a class?
2. What is an object?
3. What is the difference between an object and a class?
4. What is the difference between class and structure?
5. What is public, protected, private?
6. What are virtual functions?
7. What is friend function?
8. What is a scope resolution operator?
9. What do you mean by inheritance?
10. What is abstraction?
11. What is polymorphism? Explain with an example.
12. What is encapsulation?
13. What do you mean by binding of data and functions?
14. What is function overloading and operator overloading?
15. What is virtual class and friend class?
16. What do you mean by inline function?
17. What do you mean by public, private, protected and friendly?
18. When is an object created and what is its lifetime?
19. What do you mean by multiple inheritance and multilevel inheritance? Differentiate between them.
20. Difference between realloc() and free?
21. What is a template?
22. What are the main differences between procedure oriented languages and object oriented languages?
23. What is R T T I ?
24. What are generic functions and generic classes?
25. What is namespace?
26. What is the difference between pass by reference and pass by value?
27. Why do we use virtual functions?
28. What do you mean by pure virtual functions?
29. What are virtual classes?
30. Does c++ support multilevel and multiple inheritance?
31. What are the advantages of inheritance?
32. When is a memory allocated to a class?
33. What is the difference between declaration and definition?
34. What is virtual constructors/destructors?
35. In c++ there is only virtual destructors, no constructors. Why?
36. What is late bound function call and early bound function call? Differentiate.
37. How is exception handling carried out in c++?
38. When will a constructor executed?
39. What is Dynamic Polymorphism?
40. Write a macro for swapping integers.
41. How do you link a C++ program to C functions?
42. Explain the scope resolution operator.
43. What are the differences between a C++ struct and C++ class?
44. How many ways are there to initialize an int with a constant?
45. How does throwing and catching exceptions differ from using setjmp and longjmp?
46. What is a default constructor?
47. What is a conversion constructor?
48. What is the difference between a copy constructor and an overloaded assignment operator?
49. When should you use multiple inheritance?
50. What is a virtual destructor?
51. Explain the ISA and HASA class relationships. How would you implement each in a class design?
52. When is a template a better solution than a base class?
53. What is a mutable member?
C++
54. What is an explicit constructor?
55. What is the Standard Template Library?
56. Describe run-time type identification.
57. What problem does the namespace feature solve?
58. Write a function of factorial
59. Use recursion to write a function of factorial.
60. Write a function that reverse the words in the sentence ,for example "This is a string " becomes "string a is This".
61. You have a linked list. How can you tell that there is no cycling in it?
62. How would you write a program to find a file on disk.
63. What is the difference between basic building blocks in C and C++?
64. What is virtual destructor and when do you need to use it?"
65. Write code for Reverse linked list.
66. What is the purpose of the preprocessor directive #error?
67. How do you code an infinite loop in C ?
68. What are the uses of the keyword static?
DATA STRUCTURE
1. What is a data structure?
2. What does abstract data type means?
3. Evaluate the following prefix expression " ++ 26 + - 1324" (Similar types can be asked)
4. Convert the following infix expression to post fix notation ((a+2)*(b+4)) -1 (Similar types can be asked)
5. How is it possible to insert different type of elements in stack?
6. Stack can be described as a pointer. Explain.
7. Write a Binary Search program
8. Write programs for Bubble Sort, Quick sort
9. Explain about the types of linked lists
10. How would you sort a linked list?
11. Write the programs for Linked List (Insertion and Deletion) operations
12. What data structure would you mostly likely see in a non recursive implementation of a recursive algorithm?
13. What do you mean by Base case, Recursive case, Binding Time, Run-Time Stack and Tail Recursion?
14. Explain quick sort and merge sort algorithms and derive the time-constraint relation for these.
15. Explain binary searching, Fibinocci search.
16. What is the maximum total number of nodes in a tree that has N levels? Note that the root is level (zero)
17. How many different binary trees and binary search trees can be made from three nodes that contain the key values 1, 2 & 3?
18. A list is ordered from smaller to largest when a sort is called. Which sort would take the longest time to execute?
19. A list is ordered from smaller to largest when a sort is called. Which sort would take the shortest time to execute?
20. When will you sort an array of pointers to list elements, rather than sorting the elements themselves?
21. The element being searched for is not found in an array of 100 elements. What is the average number of comparisons needed in a sequential search to determine that the element is not there, if the elements are completely unordered?
22. What is the average number of comparisons needed in a sequential search to determine the position of an element in an array of 100 elements, if the elements are ordered from largest to smallest?
23. Which sort show the best average behavior?
24. What is the average number of comparisons in a sequential search?
DATA STRUCTURE
25. Which data structure is needed to convert infix notations to post fix notations?
26. What do you mean by:
o Syntax Error
o Logical Error
o Runtime Error
How can you correct these errors?
27. In which data structure, elements can be added or removed at either end, but not in the middle?
28. How will inorder, preorder and postorder traversals print the elements of a tree?
29. Parenthesis are never needed in prefix or postfix expressions. Why?
30. Which one is faster? A binary search of an orderd set of elements in an array or a sequential search of the elements.*
*********************************************************************************************
Programming Puzzles
Some companies certainly ask for these puzzles. Specially Microsoft.
27. Write a "Hello World" program in 'C' without using a semicolon.
28. Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1;
29. C/C++ : Exchange two numbers without using a temporary variable.
30. C/C++ : Find if the given number is a power of 2.
31. C/C++ : Multiply x by 7 without using multiplication (*) operator.
32. C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7
33. Remove duplicates in array
34. Finding if there is any loop inside linked list.
35. Remove duplicates in an no key access database without using an array
36. Convert (integer) number in binary without loops.
37. Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed.
38. From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly.
39. Given an array (group) of numbers write all the possible sub groups of this group.
C++ Questions
73. What is the output of printf("%d")
74. What will happen if I say delete this
75. Difference between "C structure" and "C++ structure".
76. Diffrence between a "assignment operator" and a "copy constructor"
77. What is the difference between "overloading" and "overridding"?
78. Explain the need for "Virtual Destructor".
79. Can we have "Virtual Constructors"?
80. What are the different types of polymorphism?
81. What are Virtual Functions? How to implement virtual functions in "C"
82. What are the different types of Storage classes?
83. What is Namespace?
84. What are the types of STL containers?.
85. Difference between "vector" and "array"?
86. How to write a program such that it will delete itself after exectution?
87. Can we generate a C++ source code from the binary file?
88. What are inline functions?
89. Talk sometiming about profiling?
90. How many lines of code you have written for a single program?
91. What is "strstream" ?
92. How to write Multithreaded applications using C++?
93. Explain "passing by value", "passing by pointer" and "passing by reference"
94. Write any small program that will compile in "C" but not in "C++"
95. Have you heard of "mutable" keyword?
96. What is a "RTTI"?
97. Is there something that I can do in C and not in C++?
98. Why preincrement operator is faster than postincrement?
99. What is the difference between "calloc" and "malloc"?
100. What will happen if I allocate memory using "new" and free it using "free" or allocate sing "calloc" and free it using "delete"?
101. What is Memory Alignment?
102. Explain working of printf.
103. Difference between "printf" and "sprintf".
104. What is "map" in STL?
105. When shall I use Multiple Inheritance?
106. What are the techniques you use for debugging?
107. How to reduce a final size of executable?
108. Give 2 examples of a code optimization.
Q5. From the following program
foo()
int foo(int a, int b)
{
if (a&b) return 1;
return 0;
}
a) if either a or b are zero returns always 0
b) if both a & b are non zero returns always 1
c) if both a and b are negative returns 0
Q6. The following function gives some error. What changes have to be made
void ( int a,int b)
{
int t; t=a; a=b; b=t;
}
a) define void as int and write return t
b) change everywhere a to *a and b to *b
Q7. Which of the following is incorrect
a) if a and b are defined as int arrays then (a==b) can never be true
b) parameters are passed to functions only by values
c) defining functions in nested loops
Q8. include
void swap(int*,int*);
main()
{
int arr[8]={36,8,97,0,161,164,3,9}
for (int i=0; i<7; i++)
{
for (int j=i+1; j<8;j++)
if(arr[i]
}
void swap(int*x,int*y)
{
int temp; static int cnt=0;
temp= *x;
*x=*y;
*y=temp;
cnt++;
}
What is cnt equal to
a) 7
b) 15
c) 1
d) none of these
Q9. int main()
{
FILE *fp;
fp=fopen("test.dat","w");
fprintf(fp,'hello\n");
fclose(fp);
fp=fopen ("test.dat","w");
fprintf (fp, "world");
fclose(fp);
return 0;
}
If text.dat file is already present after compiling and execution how many bytes does the file occupy ?
a) 0 bytes
b) 5 bytes
c) 11 bytes
d) data is insufficient
Q10. f1(int*x,intflag)
int *y;
*y=*x+3;
switch(flag)
{
case 0:
*x=*y+1;
break;
case 1:
*x=*y;
break;
case 2:
*x=*y-1;
break;
}
return(*y)
main()
{
*x=5;
i=f1(x,0); j=f1(x,1);
printf("%d %d %d ",i,j,*x);
}
What is the output?
a) 8 8 8
b) 5 8 8
c) 8 5 8
d) none of these
Q12. A function is like this
swap( int a,int b)
{
int temp;
temp=a;
a=b;}
8. enum number { a= -1, b= 4,c,d,e}
What is the value of e ?
(a) 7
(b) 4
(c) 5
(d) 15
(e) 3
19. The very first process created by the kernal that runs till the kernal process is halts is
a) init
b) getty
c) both (a) and (b)
d) none of these
Ans. (a)
20. Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf("%d,",i);
}
}
a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error
Ans. (d)
21. What is the ouptut in the following program
main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(cprintf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(iprintf("pass2");
else
printf("Fail2")
}
a) Pass1,Pass2
b) Pass1,Fail2
c) Fail1,Pass2
d) Fail1,Fail2
e) None of these
Ans. (c)
22. In the process table entry for the kernel process, the process id value is
(a) 0
(b) 1
(c) 2
(d) 255
(e) it does not have a process table entry
Ans. (a)
23. Which of the following API is used to hide a window
a) ShowWindow
b) EnableWindow
c) MoveWindow
d) SetWindowPlacement
e) None of the above
Ans. (a)
24. What will the following program do?
void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
25. In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}
a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT
Ans. (a)
26. PATH = /bin : /usr : /yourhome
The file /bin/calender has the following line in it
cal 10 1997
The file /yourhome/calender has the following line in it
cal 5 1997
If the current directory is /yourhome and calender is executed
a) The calendar for May 1997 will be printed on screen
b) The calendar for Oct 1997 will be printed on screen
c) The calendar for the current month( whatever it is) will be printed
d) Nothing will get printed on screen
e) An error massage will be printed
27. What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
a) The string is : string
b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Ans. (b)
28. What will be result of the following program?
void myalloc(char *x, int n)
{x= (char *)malloc(n*sizeof(char));
memset(x,\0,n*sizeof(char));
}
main()
{char *g="String";
myalloc(g,20);
strcpy(g,"Oldstring");
printf("The string is %s",g);
}
a) The string is : String
b) Run time error/Core dump
c) The string is : Oldstring
d) Syntax error during compilation
e) None of these
13. Which is a good way of representing varaibles in recursion
a) local variables
b) static varaibles
c) global variables
14. Given the following c program
func()
{
static int i = 10;
printf("%d",i);
i++;
}
What is the value of i if the function is called twice ?
15. Given the following c program
func(int *i, int*j)
{*i=*i * *i;
*j=*j* *j;
}
main()
{ int i = 5, j = 2;
func(&i,&j);
printf("%d %d", i, j);}
What is the output?
16. Given page table, page size and offset find the corresponding physical address ?
17. In a memory chip 4k size and 16bit words are to be stored.
No of address and data lines required is:
18. Identify in which pass of the 2 pass compiler are the following compiled
1) literals
2) address resolution
3) listing
19. Object code does not require
a) relocation bits
b) external names and place where they are located
c) absolute adress
d) all the object codes
20. ARP is in reference to
a) MAC to IP
b) IP to MAC
21. Question on Balanced tree -
A balanced tree is given and a node is addded at the leaf.
Find the no of unbalanced nodes?
22. What is the order of Hashing time:
a) 0(1)
b) 0(n2)
23. Given that:
s -> s + s ; s -> s * s ; s -> a
Find the no of parse trees for a+a*a+a
a) 4
b) 5
c) 6
d) 7
24. Order of deleting a node from a linked list.
(pointer is to an arbitrary node)
a)0(1)
b)0(n)
25. A choclate of size nXn is given and is to be made into pices of size 1x1.
At a time both horizontal and a vertical cut is done.
Find the order of complexity
a) O(n2)
b) O(nlogn)
c) O(logn)
1. There was a circuit given using three nand gates with two inputs and one output.
Find the output.
a) OR
b) AND
c) XOR
d) NOT
Ans. (a)
2. Suggest a sorting algorithm which is efficient (in worst case) to 10 values
a) Binary tree
b) Selection
c) Bubble
d) Any of the above
3. What is the number of comparisons in the worst case to merge two sorted lists containing n elements each.
a) 2n
b) 2n-1
c) 2n+1
d) 2n-2
4.Iintegrated check value(ICV) are used as:
Ans. The client computes the ICV and then compares it with the senders value.
5. Question on client-server system using asychronous request from the client
6. If a binary tree is constructed using nodes with two pointers each,
how many null pointers does a tree with N nodes have
a) n-1
b) n
c) n+1
d) Depends on the number of edges
7. Which of following statements about heap is wrong
a) An n element heap has height log n(base of log is 2)
b) Smallest element of heap is always a leaf
c) A array in reverse sorted order is a heap
d) A heap can't contain any element more than once
8. When applets are downloaded from web sites , a byte verifier performs _________?
Ans. Status check.
9. For the following C program
void insert(key,r)
typekey key,data array r;
{extern int n;
if(n>=max) /*error table if full */
else r[n++].k=key;
}
This on executing, enables a
a) Basic sequential search
b) Binary search
c) Interpolation search
d) None
10. Find the outpur of the following C program
void f(char *p)
{p=(char *) malloc(6);
strcpy(p,"hello");
}
void main( )
{char *P="bye";
f(p);
printf("%s',p);
}
11. Time taken to access cache is 100ns and to access memory is 1000ns.
Hit ratio given. Find the average access time
12. Path testing is
a) Black box testing strategy
b) White box testing strategy
c) An installation .........
d) An enviornment
13. X:verification' asks are we building the right product
Y:validation' asks are we building the product right
14. Which one of the following can't be used to find an internet address given the domain name
a) /etc/host
b) NIS yellow pages
c) DNS
d) ARP
15. Flow control is necessary for the transport protocol layer due to the following reasons
a) Unreliable link
b) Congestion at receiver
c) Packets out of sequence
d) None of these
16. In public key encryption, if A wants to send a message to B so that no one else can read the message
then A encrypts the message using
a) A's public key
b) A's private key
c) B's public key
d) B's private key
17. Which of the following is not condition having a deadlock resource previous granted
can be forcebly taken away from a process
a) Resources need to be used in mutually exclusion fashion
b) Process can request new resources, as they continue to hold on to old ones
c) Here is a cycle in the resource allocation graph
16. An IP/IPX packet received by a computer using... having IP/IPX both how the packet is handled.
Ans. Read the, field in the packet header with to send IP or IPX protocol.
17. The range of the 32 bit number in two's complement form is _______
18. Cyclomatic complexity
{if((x=0) or (y=0))
p=0;
else
{p=x;i=1;
while(i!=y)
{p=p+x;
i=i+1; }
}
}
19. Activation record will contain the
a) Storage for simple names
b) Information about attributes for local names
c) Return address
d) All of the above
20. Global static variable within a file is intended to
a) Localize swap
b) Retain value persistently
c) Define constant
d) Fixed address in memory
21. Why is thread switch faster than a process switch
22. What is the binary equivalent of 41.6875
23. Checkpoint value will be calculated in
24. DHCP is used for
a) IP address allocation
b)dynamic host configuration protocol
25. For the following C program
int x(char *a)
{a=(char *) malloc(10*sizeof(char));
*a="hello";
}
main()
{char *a="new";
x(a);
printf("%s",a);
}
The output is
a) Hello
b) New
c) Hello new
d) Run time error
1. What is the mistake in the following program segment ?
f()
{
int a;
void c;
f2(&c,&a);}
2. a=0;
b=(a=0)?2:3;
a) What will be the value of b and why ?
b) If in first statement a= 0 is replaced by a= -1, b = ?
c) If in second statement a=0 is replaced by a = -1, b=?
3. char *a[2];
int const *p;
int *const p;
struct new { int a;int b; *var[5] (struct new)}
Describe the statements in the above given construct ?
4. f()
{
int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
}
What is the value of c ?
5. f1()
{
f(3);
}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
What is the value of c?
6. What is the fallacy in the following program segment ?
int *f1()
{
int a=5;
return &a;
}
f()
int *b=f1()
int c=*b;
}
7. Give the C language equivalents of the following
a)Function returning an int pointer
b)Function pointer returning an int pointer
c)Function pointer returning an array of integers
d)Array of function pointer returning an array of integers
8. Find the fallacy in the following program segment?
int a;
short b;
b=a;
9. Define function ? Explain arguments in functions ?
10. How does C pass variables to a function ?
11. Explain the following program segment.
f(){
int *b;
*b=2;
}
12. Explain binary trees and their use ?
13. Draw the diagram showing the function stack, illustrating the variables that were pushed on the stack at the point when function f2 has been introduced .
type def struct
{ double x,double y} point; }
main( int argc, char *arg[3])
{ double a;
int b,c;
f1(a,b); }
f1(double x, int y)
{point p;
stack int n;
f2(p,x,y)
}
f2(point p, double angle)
{ int i,j,k,int max;
}
9. Find the output for the following C program
int array[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
for (i=2;i<0;i--)
for(j=2;j<=0;j--)
printf("%d", arr[i][j]);
10. Find the output for the following C program
#include
void main()
{int i,x,sum=0;
int arr[6]=[1,2,3,4,5,6]
for (i=0;i<4;i++)
sum+ = func(arr[i]);
printf("%d", sum);
}
func(int x)
{ int val,x;
val = 2;
return(x+ val++);
}
11. Given the following data:
• Process P1 takes 2 seconds
• Process P2 takes 3 seconds
• Process P3 takes 4 seconds
• Process P4 takes 1 second
• Process P5 takes 6 seconds
Find the average time in case of shortest job first (SJF) scheduling.
12. Given a string STOCK and a stack of size 4.
Which of the following strings cannot be generated using this stack.
(a) TSOCK
(b) TOSKC
(c) STOCK
(d) TKOSC
(e) None of these
13. Inversion of a matrix will take which of the following time complexities?
(a) O(n)
(b) O(n²)
(c) O(log n)
(d) O(n³)
(e) None of these
14. A drum rotates at 4000 rpm. What is its average access time.
15. What range of integral values can be stored using 32 bits?
16. Where are the following variables stored
• Automatic
• Global
• Static
17. If a layer 4 transfers data at the rate of 3000 bytes/sec.
What will be the size of data block transferred by Layer 2
18. What is the greatest disadvantage of dynamic RAM over static RAM
Ans. High Power and need to refresh every 2 ms.
19. What happens when the CPU gets interrupted?
20. Find the Postfix of the following string
(a + b) * ((-d) *f (ab - cd))
21. E --> E + E| E * E | E/E | E - E| .... then which is correct
(a) It is ambigous
(b) It is inherently ambigous
(c) It is non inherently ambigous
(d) None of the above
22. If there are n nodes and K edges in a graph then what is the order of traversing
Ans. O(n²)
23. A graph is represented as an adjacency list with n vertices and e edges
What is its time complexity
Ans. O(n + e)
24. An array with address KV[a] had n elements. Which of the following correctly addresses the ith element of the array.
(a) KV(a) - 2a + 2i
(b) KV(a) +2i
(c) KV(a) - 2a
(d) None of these
25. Give an example of a primitive instruction in microprocessors.
26. A computer has 8 bit data bus and 16 bit address line.
How many machine cycles will it take to store the contents to a memory location?
27. Where is a variable defined in a function stores?
Ans. Process Swappable Area
28. For the following C progralm
int d=0;
for(int i=0;i<31;i++)
for(int j=0;j<31;j++)
for(int k=0;k<31;k++)
if (((i+j+k) % 3)==0)
d=d+1;
Find value of d
29. e=
What forms do the expressions created by the above definition fit in
Ans. All arithematic expressions
30. If a set of numbers are in sorted order then which of the following sorting method is best
Ans. Bubble Sort
31. A magnetic tape is similar to which of the following structures
Ans. List
32. The s/n id 3 dB Find the capacity of the line.
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
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 part of this question can be answered in at least
three ways:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */
3. 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 of 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-function 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.)
7. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers.
Write the way to initialize the 2nd element to 10.
8. In the above question an array of pointers is declared.
Write the statement to initialize the 3rd element of the 2 element to 10;
9.
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.
10.
void main()
{
int i=7;
printf("%d",i++*i++);
}
Ans: 56
11.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
12.
void main()
{
intcount=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20
13. There was question in c working only on unix machine with pattern matching.
14. what is alloca()
Ans : It allocates and frees memory after use/after getting out of scope
15.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
Ans: 321
16.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}
Ans: anything is good.
17.
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"
6. For the following C program
#define AND &&
#define ARRANGE (a>25 AND a<50)
main()
{int a = 30;
if (ARRANGE)
printf("within range");
else
printf("out of range");
}
What is the output?
7. For the following C program
#define AREA(x)(3.14*x*x)
main()
{floatr1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000
8. What do the following statements indicate. Explain.
• int(*p)[10]
• int*f()
• int(*pf)()
• int*p[10]
Refer to:
-- Kernighan & Ritchie page no. 122
-- Schaum series page no. 323
9. Write a C program to find whether a stack is progressing in forward
or reverse direction.
10. Write a C program that reverses the linked list.
28. What is the function of the linker?
29. void f(int y)
{
struct s *ptr;
ptr = malloc (sizeof (struct)+99*sizeof(int));
}
struct s
{
int i;
float p;
};
when free (ptr) is executed, what will happen?
1. The C language terminator is
(a) semicolon (b) colon (c) period (d) exclamation mark
2. What is false about the following -- A compound statement is
(a) A set of simple statements (b) Demarcated on either side by curly brackets
(c) Can be used in place of simple statement (d) A C function is not a compound statement.
3. What is true about the following C Functions
(a) Need not return any value (b) Should always return an integer
(c) Should always return a float (d) Should always return more than one value
4. Main must be written as
(a) The first function in the program (b) Second function in the program
(c) Last function in the program (d) Any where in the program
5. Which of the following about automatic variables within a function is correct ?
(a) Its type must be declared before using the variable (b) They are local
(c) They are not initialized to zero (d) They are global
6. Write one statement equivalent to the following two statements: x=sqr(a); return(x);
Choose from one of the alternatives
(a) return(sqr(a)); (b) printf("sqr(a)");
(c) return(a*a*a); (d) printf("%d",sqr(a));
7. Which of the following about the C comments is incorrect ?
(a) Comments can go over multiple lines
(b) Comments can start any where in the line
(c) A line can contain comments with out any language statements
(d) Comments can occur within comments
8. What is the value of y in the following code?
x=7;
y=0;
if(x=6) y=7;
else y=1;
(a) 7 (b) 0 (c) 1 (d) 6
9. Read the function conv() given below
conv(int t)
{
int u;
u=5/9 * (t-32);
return(u);
}
What is returned
(a) 15 (b) 0 (c) 16.1 (d) 29
10. Which of the following represents true statement either x is in the range of 10 and 50 or y is zero
(a) x >= 10 && x <= 50 || y = = 0 (b) x<50
(c) y!=10 && x>=50 (d) None of these
11. Which of the following is not an infinite loop ?
(a) while(1)\{ ....} (b) for(;;){...}
(c) x=0; (d) # define TRUE 0
do{ /*x unaltered within the loop*/ ...
.....}while(x = = 0); while(TRUE){ ....}
12. What does the following function print?
func(int i)
{
if(i%2)return 0;
else return 1;
}
main()
{
int =3;
i=func(i);
i=func(i);
printf("%d",i);
}
(a) 3 (b) 1 (c) 0 (d) 2
13. How does the C compiler interpret the following two statements
p=p+x;
q=q+y;
(a) p= p+x; (b)p=p+xq=q+y; (c)p= p+xq;
Q1. typedef struct{
char *;
nodeptr next;
} * nodeptr ;
What does nodeptr stand for?
Q2. What does. int *x[](); means ?
Q3. struct list{
int x;
struct list *next;
}*head;
the struct head.x =100
Is the above assignment to pointer is correct or wrong ?
Ans. Wrong
Q4.What is the output of the following ?
int i;
i=1;
i=i+2*i++;
printf(%d,i);
Ans. 4
Q5. FILE *fp1,*fp2;
fp1=fopen("one","w")
fp2=fopen("one","w")
fputc('A',fp1)
fputc('B',fp2)
fclose(fp1)
fclose(fp2)}
a.error b. c. d.
Ans. no error. But It will over writes on same file.
What are the output(s) for the following ?
Q6. #include
char *f()
{char *s=malloc(8);
strcpy(s,"goodbye")}
main()
{
char *f();
printf("%c",*f()='A');
}
Q7. #define MAN(x,y) (x)>(y)?(x):(y)
{
inti=10;j=5;k=0;
k= MAX(i++,++j)
printf(%d %d %d %d,i,j,k)
}
Ans. 10 5 0
Q8. a=10;b= 5;c=3;d=3;
if(a printf(%d %d %d %d a,b,c,d)
else printf("%d %d %d %d a,b,c,d);
Q9. #include
show(int t,va_list ptr1)
{
int a,x,i;
a=va_arg(ptr1,int)
printf("\n %d",a)
}
display(char)
{
int x;
listptr;
va_star(otr,s);
n=va_arg(ptr,int);
show(x,ptr);
}
main()
{
display("hello",4,12,13,14,44);
}
Q10. main()
{
printf("hello");
fork();
}
Q11. main()
{
int i = 10;
printf(" %d %d %d \n", ++i, i++, ++i);
}
Q12. #include
main()
{
int *p, *c, i;
i = 5;
p = (int*) (malloc(sizeof(i)));
printf("\n%d",*p);
*p = 10;
printf("\n%d %d",i,*p);
c = (int*) calloc(2);
printf("\n%d\n",*c);
}
Q13. #define MAX(x,y) (x) >(y)?(x):(y)
main()
{
inti=10,j=5,k=0;
k= MAX(i++,++j);
printf("%d..%d..%d",i,j,k);
}
Q14. #include
main()
{
enum _tag{ left=10, right, front=100, back};
printf("left is %d, right is %d, front is %d, back is %d",left,right,front,back);
}
Q15. main()
{
inta=10,b=20;
a>=5?b=100:b=200;
printf("%d\n",b);
}
Q16. #define PRINT(int) printf("int = %d ",int)
main()
{< BR> intx,y,z;
x=03;y=02;z=01;
PRINT(x^x);
z<<=3;PRINT(x);
y>>=3;PRINT(y);
}
Q17. #include
main()
{
char s[] = "Bouquets and Brickbats";
printf("\n%c, ",*(&s[2]));
printf("%s, ",s+5);
printf("\n%s",s);
printf("\n%c",*(s+2));
}
Q18. main()
{
struct s1
{
char *str;
struct s1 *ptr;
};
static struct s1 arr[] = { {"
};
struct s1 *p[3];
int i; < BR> for(i=0;i<=2;i++)
p[i] = arr[i].ptr;
printf("%s\n",(*p)->str);
printf("%s\n",(++*p)->str);
printf("%s\n",((*p)++)->str);
}
Q19. .main()
{
char *p = "hello world!";
p[0] = 'H';
printf("%s",p);
}
15. Give the output of the following program
main()
{char *s;
s="hot java";
strcpy(s,"solarrs java")
}
16. Give the output of the following program
main()
{printf("hot java");
fork()
exit(0);
}
(i). When redirected to a screen what will be printed.
(ii). When redirected to file what will be printed.
17. Give the output of the following program
main()
{int ret;
ret=fork();ret=fork();ret=fork();ret=fork();
if(!ret)
printf("sun");
else
printf("solaris");
18. Give the output of the following program
main()
{char *p='a';
int *i=100/*p;
}
what will be the value of *i= 1
19. Which data structure gives efficient search
1 B-tree
2 binary tree
3 array
4 linked list
20. Find the error in the following program
struct point
{struct point *next;
int data;
}
x;
main()
{int i;
for(x=p;x!=0;)
x=x->next,x++;
freelist(x);
}
freelist(x)
{free(x);
return
}
1. Point out error, if any, in the following program
main()
{
int i=1;
switch(i)
{
case 1:
printf("\nRadioactive cats have 18 half-lives");
break;
case 1*2+4:
printf("\nBottle for rent -inquire within");
break;
}
}
Ans. No error. Constant expression like 1*2+4 are acceptable in cases of a switch.
2. Point out the error, if any, in the following program
main()
{
int a=10,b;
a>= 5 ? b=100 : b=200;
printf("\n%d",b);
}
Ans. lvalue required in function main(). The second assignment should be written in parenthesis as follows:
a>= 5 ? b=100 : (b=200);
3. In the following code, in which order the functions would be called?
a= f1(23,14)*f2(12/4)+f3();
a) f1, f2, f3 b) f3, f2, f1
c) The order may vary from compiler to compiler d) None of the above
4. What would be the output of the following program?
main()
{
int i=4;
switch(i)
{
default:
printf("\n A mouse is an elephant built by the Japanese");
case 1:
printf(" Breeding rabbits is a hair raising experience");
break;
case 2:
printf("\n Friction is a drag");
break;
case 3:
printf("\n If practice make perfect, then nobody's perfect");
}
}
a) A mouse is an elephant built by the Japanese b) Breeding rabbits is a hare raising experience
c) All of the above d) None of the above
5. What is the output of the following program?
#define SQR(x) (x*x)
main()
{
int a,b=3;
a= SQR(b+2);
printf("%d",a);
}
a) 25 b) 11 c) error d) garbage value
6. In which line of the following, an error would be reported?
1. #define CIRCUM(R) (3.14*R*R);
2. main()
3. {
4. float r=1.0,c;
5. c= CIRCUM(r);
6. printf("\n%f",c);
7. if(CIRCUM(r))==6.28)
8. printf("\nGobbledygook");
9. }
a) line 1 b) line 5 c) line 6 d) line 7
7. What is the type of the variable b in the following declaration?
#define FLOATPTR float*
FLOATPTR a,b;
a) float b) float pointer c) int d) int pointer
8. In the following code;
#include
main()
{
FILE *fp;
fp= fopen("trial","r");
}
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.
9. We should not read after a write to a file without an intervening call to fflush(), fseek() or rewind() < TRUE/FALSE>
Ans. True
10. If the program (myprog) is run from the command line as myprog 1 2 3 , What would be the output?
main(int argc, char *argv[])
{
int i;
for(i=0;i
}
a) 1 2 3 b) C:\MYPROG.EXE 1 2 3
c) MYP d) None of the above
11. If the following program (myprog) is run from the command line as myprog 1 2 3, What would be the output?
main(int argc, char *argv[])
{
int i,j=0;
for(i=0;i
printf("%d",j);
}
a) 1 2 3 b) 6 c) error d) "123"
12. If the following program (myprog) is run from the command line as myprog monday tuesday wednesday thursday,
What would be the output?
main(int argc, char *argv[])
{
while(--argc >0)
printf("%s",*++argv);
}
a) myprog monday tuesday wednesday thursday b) monday tuesday wednesday thursday
c) myprog tuesday thursday d) None of the above
13. In the following code, is p2 an integer or an integer pointer?
typedef int* ptr
ptr p1,p2;
Ans. Integer pointer
14. Point out the error in the following program
main()
{
const int x;
x=128;
printf("%d",x);
}
Ans. x should have been initialized where it is declared.
15. What would be the output of the following program?
main()
{
int y=128;
const int x=y;
printf("%d",x);
}
a) 128 b) Garbage value c) Error d) 0
16. What is the difference between the following declarations?
const char *s;
char const *s;
Ans. No difference
17. What is the difference between the following declarations?
const char *const s; char const *const s;
Ans. No difference
18. What would be the output of the following program?
main()
{
char near * near *ptr1;
char near * far *ptr2;
char near * huge *ptr3;
printf("%d %d %d",sizeof(ptr1),sizeof(ptr2),sizeof(ptr3));
}
a) 1 1 1 b) 1 2 4 c) 2 4 4 d) 4 4 4
19. If the following program (myprog) is run from the command line as myprog friday tuesday sunday,
What would be the output?
main(int argc, char*argv[])
{
printf("%c",**++argv);
}
a) m b) f c) myprog d) friday
20. If the following program (myprog) is run from the command line as myprog friday tuesday sunday,
What would be the output?
main(int argc, char *argv[])
{
printf("%c",*++argv[1]);
}
a) r b) f c) m d) y
21. If the following program (myprog) is run from the command line as myprog friday tuesday sunday,
What would be the output?
main(int argc, char *argv[])
{
while(sizeofargv)
printf("%s",argv[--sizeofargv]);
}
a) myprog friday tuesday sunday b) myprog friday tuesday
c) sunday tuesday friday myprog d) sunday tuesday friday
22. Point out the error in the following program
main()
{
int a=10;
void f();
a=f();
printf("\n%d",a);
}
void f()
{
printf("\nHi");
}
Ans. The program is trying to collect the value of a "void" function into an integer variable.
23. In the following program how would you print 50 using p?
main()
{
int a[]={10, 20, 30, 40, 50};
char *p;
p= (char*) a;
}
Ans. printf("\n%d",*((int*)p+4));
24. Would the following program compile?
main()
{
int a=10,*j;
void *k;< BR> j=k=&a;
j++;
k++;
printf("\n%u%u",j,k);
}
a) Yes b) No, the format is incorrect
c) No, the arithmetic operation is not permitted on void pointers
d) No, the arithmetic operation is not permitted on pointers
25. According to ANSI specifications which is the correct way of declaring main() when it receives command line arguments?
a) main(int argc, char *argv[]) b) main(argc,argv) int argc; char *argv[];
c) main() {int argc; char *argv[]; } d) None of the above
26. What error would the following function give on compilation?
f(int a, int b)
{
int a;
a=20;
return a;
}
a) missing parenthesis in the return statement b) The function should be declared as int f(int a, int b)
c) redeclaration of a d) None of the above
27. Point out the error in the following program
main()
{
const char *fun();
*fun()='A';
}
const char *fun()
{
return "Hello";
}
Ans. fun() returns to a "const char" pointer which cannot be modified
28. What would be the output of the following program?
main()
{
const int x=5;
int *ptrx;
ptrx=&x;
*ptrx=10;
printf("%d",x);
}
a) 5 b) 10 c) Error d) Garbage value
29. A switch statement cannot include
a) constants as arguments b) constant expression as arguments
c) string as an argument d) None of the above
30. How long the following program will run?
main()
{
printf("\nSonata Software");
main();
}
a) infinite loop b) until the stack overflows
c) All of the above d) None of the above
31. On combining the following statements, you will get char*p; p=malloc(100);
a) char *p= malloc(100) b) p= (char*)malloc(100)
c) All of the above d) None of the above
32. What is the output of the following program?
main()
{
int n=5;
printf("\nn=%*d",n,n);
}
a) n=5 b) n=5
c) n= 5 d) error
Q1.Convert 0.9375 to binary
a) 0.0111
b) 0.1011
c) 0.1111
d) none
Ans. (c)
Q2.( 1a00 * 10b )/ 1010 = 100
a) a=0, b=0
b)a=0, b=1
c) none
Ans. (b)
Q3. In 32 bit memory machine 24 bits for mantissa and 8 bits for exponent. To increase the range of floating point.
a) more than 32 bit is to be there.
b) increase 1 bit for mantissa and decrease 1 bit for exponent
c) increase 1 bit for exponent and decrease one bit for mantissa
Q4.In C, "X ? Y : Z " is equal to
a) if (X==0) Y ;else Z
b) if (X!=0) Y ;else Z
c) if (X==0) Y ; Z
Ans. (b)
Q5. From the following program
foo()
int foo(int a, int b)
{
if (a&b) return 1;
return 0;
}
a) if either a or b are zero returns always 0
b) if both a & b are non zero returns always 1
c) if both a and b are negative returns 0
Q6. The following function gives some error. What changes have to be made
void ( int a,int b)
{
int t; t=a; a=b; b=t;
}
a) define void as int and write return t
b) change everywhere a to *a and b to *b
Q7. Which of the following is incorrect
a) if a and b are defined as int arrays then (a==b) can never be true
b) parameters are passed to functions only by values
c) defining functions in nested loops
Q8. include
void swap(int*,int*);
main()
{
int arr[8]={36,8,97,0,161,164,3,9}
for (int i=0; i<7; i++)
{
for (int j=i+1; j<8;j++)
if(arr[i]
}
void swap(int*x,int*y)
{
int temp; static int cnt=0;
temp= *x;
*x=*y;
*y=temp;
cnt++;
}
What is cnt equal to
a) 7
b) 15
c) 1
d) none of these
Q9. int main()
{
FILE *fp;
fp=fopen("test.dat","w");
fprintf(fp,'hello\n");
fclose(fp);
fp=fopen ("test.dat","w");
fprintf (fp, "world");
fclose(fp);
return 0;
}
If text.dat file is already present after compiling and execution how many bytes does the file occupy ?
a) 0 bytes
b) 5 bytes
c) 11 bytes
d) data is insufficient
Q10. f1(int*x,intflag)
int *y;
*y=*x+3;
switch(flag)
{
case 0:
*x=*y+1;
break;
case 1:
*x=*y;
break;
case 2:
*x=*y-1;
break;
}
return(*y)
main()
{
*x=5;
i=f1(x,0); j=f1(x,1);
printf("%d %d %d ",i,j,*x);
}
What is the output?
a) 8 8 8
b) 5 8 8
c) 8 5 8
d) none of these
Q12. A function is like this
swap( int a,int b)
{
int temp;
temp=a;
a=b;}
18. enum number { a= -1, b= 4,c,d,e}
What is the value of e ?
(a) 7
(b) 4
(c) 5
(d) 15
(e) 3
19. The very first process created by the kernal that runs till the kernal process is halts is
a) init
b) getty
c) both (a) and (b)
d) none of these
Ans. (a)
20. Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf("%d,",i);
}
}
a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error
Ans. (d)
21. What is the ouptut in the following program
main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(cprintf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(iprintf("pass2");
else
printf("Fail2")
}
a) Pass1,Pass2
b) Pass1,Fail2
c) Fail1,Pass2
d) Fail1,Fail2
e) None of these
Ans. (c)
22. In the process table entry for the kernel process, the process id value is
(a) 0
(b) 1
(c) 2
(d) 255
(e) it does not have a process table entry
Ans. (a)
23. Which of the following API is used to hide a window
a) ShowWindow
b) EnableWindow
c) MoveWindow
d) SetWindowPlacement
e) None of the above
Ans. (a)
24. What will the following program do?
void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
25. In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}
a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT
Ans. (a)
26. PATH = /bin : /usr : /yourhome
The file /bin/calender has the following line in it
cal 10 1997
The file /yourhome/calender has the following line in it
cal 5 1997
If the current directory is /yourhome and calender is executed
a) The calendar for May 1997 will be printed on screen
b) The calendar for Oct 1997 will be printed on screen
c) The calendar for the current month( whatever it is) will be printed
d) Nothing will get printed on screen
e) An error massage will be printed
27. What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
a) The string is : string
b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Ans. (b)
28. What will be result of the following program?
void myalloc(char *x, int n)
{x= (char *)malloc(n*sizeof(char));
memset(x,\0,n*sizeof(char));
}
main()
{char *g="String";
myalloc(g,20);
strcpy(g,"Oldstring");
printf("The string is %s",g);
}
a) The string is : String
b) Run time error/Core dump
c) The string is : Oldstring
d) Syntax error during compilation
e) None of these
29. Which of the following function is used to repaint a window immediately
a) Sendmessage(hWnd,WM_PAINt,......)
b) InvalidateRect(.......)
c) MoveWindow
d) WM_COPY
e) None
30. Which function is the entry point for a DLL in MS Windows 3.1
a) Main
b) Winmain
c) Dllmain
d) Libmain
e) None
Ans. (b)
31. The standard source for standard input, standard output and standard error is
a) the terminal
b) /dev/null
c) /usr/you/input, /usr/you/output/, /usr/you/error respectively
d) None
Ans. (a)
32. What will be the result of the following program?
main()
{char p[]="String";
int x=0;
if(p=="String")
{printf("Pass 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
else
{
printf("Fail 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
}
a) Pass 1, Pass 2
b) Fail 1, Fail 2
c) Pass 1, Fail 2
d) Fail 1, Pass 2
e) syntax error during compilation
33. Which of the choices is true for the mentioned declaration ?
const char *p;
and
char * const p;
a) You can't change the character in both
b) First : You can't change the characterr & Second : You can;t change the pointer
c) You can't change the pointer in both
d) First : You can't change the pointer & Second : You can't chanage the character
e) None
34. The redirection operators > and >>
a) do the same function
b) differ : > overwrites, while >> appends
c) differ : > is used for input while >> is used for output
d) differ : > write to any file while >> write only to standard output
e) None of these
Ans. (b)
35. The command grep first second third /usr/you/myfile
a) prints lines containing the words first, second or third from the file /usr/you/myfile
b) searches for lines containing the pattern first in the files
second, third, and /usr/you/myfile and prints them
c) searches the files /usr/you/myfiel and third for lines containing the words first or second and prints them
d) replaces the word first with the word second in the files third and /usr/you/myfile
e) None of the above
Ans. (b)
18. Cyclomatic complexity
{if((x=0) or (y=0))
p=0;
else
{p=x;i=1;
while(i!=y)
{p=p+x;
i=i+1; }
}
}
25. For the following C program
int x(char *a)
{a=(char *) malloc(10*sizeof(char));
*a="hello";
}
main()
{char *a="new";
x(a);
printf("%s",a);
}
The output is
a) Hello
b) New
c) Hello new
d) Run time error
***************
1.What would be the output of the following program.
#include
main()
{
extern int a;
printf("%d",a);;
}
int a=20;
(a) 20 (b) 0 (c) garbage value (d) error!!
2.What would be the output of the following program.
main()
{
int a[5]={2,3};
printf("\n %d %d %d",a[2],a[3],a[4]);
}
(a) garbage value (b) 2 3 3 (c) 3 2 2 (d) 0 0 0
3.What would be the output of the following program.
main()
{
inti=-3,j=2,k=0,m;
m=++i&&++j||++k;
printf("\n %d %d %d %d",i,j,k,m);
}
(a) -2 3 0 1 (b) -3 2 0 1 (c) -2 3 1 1 (d) error
4.What would be the output of the following program.
main()
{
int a,b;
a=sumdig(123);
b=sumdig(123);
printf("%d %d",a,b);
}
sumdig(int n)
{
static int s=0;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
s=s+d;
sumdig(n);
}
else return(s);
}
(a) 12 6 (b) 6 12 (c) 3 15 (d) error
5.What would be the output of the following program.
#define CUBE(x) (x*x*x)
main()
{
int a,b=3;
a=CUBE(b++);
printf("\n %d %d",a,b);
}
(a) 64 4 (b) 27 4 (c) 27 6 (d) 64 6
6.What would be the output of the following program.
main()
{
const int x=get();
printf("%d",x);
}
get()
{
return(20);
}
(a) 20 (b) garbage value (c) error (d) 0
7.A function has this prototype void f1(int **x),
How will you call this function?
(a) int **a; (b) int a; (c) int *a; (d) int a=5;
f1(a); f1(&a); f1(&a); f1(&&a);
8.pointout the error, if any, in the for loop
main()
{
int l=1;
for(;;)
{
printf("%d",l++);
if(l>10)
break;
}
}
(a) The condition in the for loop is a must (b) The two semicolons should be dropped
(c) The for loop should be replaced by awhile loop (d) No error
9.Can the following piece of code be executed?
int main(void)
{
char strA[10]="compile",strB[10];
my_strcpy(strB,strA);
puts(strB);
}
char * my_strcpy(char *destination,char *source)
{
char *p=destination;
while(*source!='\0')
{
*p++=*source++;
}
*p='\0';
return destination;
}
(a) Compilation will only give a warning but will proceed to execute & will display "compile"
(b) The compilation error char *(char *,char *) differs in levels of indirection from 'int()' will occur
(c) Yes & it will print compile on the screen (d) None of the above
10.What would be the output of the following program.
#include
main()
{
char str[5]="fast";
static char *ptr_to_array = str;
printf("%s",ptr_to_array);
}
(a) Compilation will only give a warning but will proceed to execute & will display "fast"
(b) display "fast" on screen (c) will give a compilation error (d) none of the above
11.What would be the output of the following program.
main()
{
int num,*p;
num=5;
p=#
printf("%d",*p);
}
(a) 6 (b) 5 (c) junk value (d) compilation error
12.What would be the output of the following program.
main()
{
int a[3]={2,3,4};
char *p;
p=a;
p=(char *)((int *)p+1);
printf("%d",p);
}
(a) 2 (b) 0 (c) junk value (d) 3
13.What would be the output of the following program.
main()
{
int i=10;
fn(i);
printf("%d",i);
}
fn(int i)
{
return ++i;
}
(a) 10 (b) 11 (c) 12 (d) Compilation error
14. What will be the value of i & j after the loop isexecuted?
for(i=0,j=0;i<5,j<25;i++,j++)
(a) i=4,j= 24 (b) i=24,j= 24 (c) i=25,j= 25 (d) i=5,j=25
15.What would be the output of the following program.
main()
{
int i,j;
i=10;
j=sizeof(++i);
printf("%d",i);
}
(a) 11 (b) 10 (c) 4 (d) compilation error
16.What would be the output of the following program.
main()
{
int i=7;
printf("%d\n",i++*i++);
}
(a) 49 (b) 56 (c) 72 (d) compilation error
17. What will the printf print?
main()
{
char *p,*f();
p=f();
printf("f() returns:%s\n",p);
}
char *f()
{
char result[80];
strcpy(result,"anything will do");
return (result);
}
(a) f() returns: anything will do (b) f() returns:
(c) compilation error (d) The printf statement is not going to be executed
18.How many times the following program would print 'Jamboree'?
main()
{
printf("\n Jamboree");
main();
}
(a) infinite number of times (b) 32767 times
(c) 65535 times (d) till the stack does not overflow
19.Notice the error in the default statement in the code snippet below.Will it give a compilation error?
main()
{
int a=10,j;
j=fn(a);
switch(j)
{
case 30: printf("the value is 30");
break;
case 50: printf("the value is 50");
break;
default:printf("the value is not 30 or 50");
}
}
fn(int a)
{
return (++a);
}
(a) Will display "the value is 30" (b) Will display "The value is not 30 or 50"
(c) Yes a compilation error would happen
(d) No compilation errors but there will be no output on the screen
20.What would be the output of the following program.
main()
{
struct emp
{
char name[20];
int age;
float sal;
};
struct emp e = {"tiger"};
printf("\n %d %f",e.age,e.sal);
}
(a) 0 0.000000 (b) Garbage values (c) Error (d) none of the above
***********
1. Write a program to insert a node in a sorted linked list.
2. Write a program to implement the Fibinocci series.
3. Write a program to concatenate two circular linked lists into a single circular list.
4. A function even_odd_difference()passes the array of elements. Write a program to calculate the difference of the two sums of which one sum adds the elements of odd ones and another adds the elements of even ones.
5. Write a program to reverse a linked list.
1. The starting location of an array is 1000. If the array[1..5/...4] is stored in row major order, what is the location of element [4,3]. Each word occupies 4 bytes.
2. In a tertiary tree, which has three childs for every node, if the number of internal nodes are N, then the total number of leaf nodes are
3. Explain the term "locality of reference" ?
4. What is the language used for Artificial Intelligence
Ans: lisp
5. What is the character set used in JAVA 2.0 ?
Ans: Unicode
6. char a =0xAA ;
int b ;
b = (int) a ;
b = b >> 4 ;
printf("%x",b);
What is the output of the above program segment ?
7. struct s1 { struct { struct { int x; } s2 } s3 }y; How does one access x in the above given structure definition ?
8. Why there is no recursion in Fortran ?
Ans. There is no dynamic allocation.
9. What is the worst case complexity of Quick sort?
Ans. O(n2)
10. What will be sequence of operating system activities when an interrupt occurs ?
11. In a sequential search, what is the average number of comparisons it takes to search through n elements ?
Ans: (n+1)/2.
12. What is the size of the array declared as double * X[5] ?
Ans. 5 * sizeof ( double * )
13. A binary search tree with node information as 1,2,3,4,5,6,7,8 is given. Write the result obtained on preorder traversal of the binary search tree ?
Ans : 53124768
14. If size of the physical memory is 232-1, then what is the size of the virtual memory ?
15. S -> A0B A-> BB|0 B-> AA|1
How many strings of length 5 are possible with the above productions?
16. (3*4096+15*256+3*16+3). How many 1's are there in the binary representation of the result ?
Ans. 10
17. In memory mapped I/O how is I/O is accessed ?
18. What is the use of ALE in 8085 ?
Ans. To latch the lower byte of the address.
19. If the logical memory of 8 X 1024 is mapped into 32 frames, then the number of bits for the logical address are____ ?
Ans. 13
20. Context free grammar is useful for which purpose ?
21. In ternary number representation, numbers are represented as 0,1,-1.(Here -1 is represented as 1 bar.) How is 352/9 represented in ternary number representation?
22. There are processes which take 4,1,8,1 machine cycles respectively. If these are executed in round robin fashion with a time quantum of 1, what is the time it take for process 4 to complete ?
Ans. 9
23. The minimum frequency of operation is specified for every processor because......
a) for interfacing slow peripherals
b) dynamic memory refreshing.
c) to make compatible with other processor.
24. For linked list implementation , which search is not applicable ?
Ans: Binary search.
25. Each character is represented by 7 bits, 1 bit is used to represent error bit and another bit for parity. If total number of bits transmitted is 1200 bits, then what is the number of symbols that can be transmitted ?
Ans: 133
26. Explain set associatively of cache ?
27. Write the postfix form of the following expression : A+[[(B+C)+(D+E)*F]/G]
28. What is the function of the linker?
29. void f(int y)
{
struct s *ptr;
ptr = malloc (sizeof (struct)+99*sizeof(int));
}
struct s
{
int i;
float p;
};
when free (ptr) is executed, what will happen?
30. To concatenate two linked lists strings, the order is O(1) is obtained for what kind of list
. The integers from 1 to n are stored in an array in a random
fashion. but one integer is missing. Write a program to find the
missing integer.
Ans). Hint : The sum of n natural numbers is = n(n+1)/2.
if we subtract the above sum from the sum of all the
numbers in the array , the result is nothing but the
missing number.
5. Some bit type of questions has been given on pointers asking to
to find whether it is correct from syntax point of view. and if
it is correct explain what it will do.(around 15 bits).
SECTION-B
6. For the following C program
#define AND &&
#define ARRANGE (a>25 AND a<50)
main()
{int a = 30;
if (ARRANGE)
printf("within range");
else
printf("out of range");
}
What is the output?
7. For the following C program
#define AREA(x)(3.14*x*x)
main()
{floatr1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000
8. What do the following statements indicate. Explain.
• int(*p)[10]
• int*f()
• int(*pf)()
• int*p[10]
Refer to:
-- Kernighan & Ritchie page no. 122
-- Schaum series page no. 323
9. Write a C program to find whether a stack is progressing in forward
or reverse direction.
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
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 part of this question can be answered in at least
three ways:
1. char *(*(*a[N])())();
2. Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */
3. 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 of 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-function 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.)
7. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers.
Write the way to initialize the 2nd element to 10.
8. In the above question an array of pointers is declared.
Write the statement to initialize the 3rd element of the 2 element to 10;
9.
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.
10.
void main()
{
int i=7;
printf("%d",i++*i++);
}
Ans: 56
11.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
12.
void main()
{
intcount=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20
13. There was question in c working only on unix machine with pattern matching.
14. what is alloca()
Ans : It allocates and frees memory after use/after getting out of scope
15.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
Ans: 321
16.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}
Ans: anything is good.
17.
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"
6. The binary equivalent of 3B7F is
Ans. 0011 1011 0111 1111
7. The register used by the shift reduce passing method is
Ans. Stack
8. A microprogram can be defines as to consist of
Ans. A primitive operation
9. Find the output for the following C program
int array[4][4] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
for (i=2;i<0;i--)
for(j=2;j<=0;j--)
printf("%d", arr[i][j]);
10. Find the output for the following C program
#include
void main()
{int i,x,sum=0;
int arr[6]=[1,2,3,4,5,6]
for (i=0;i<4;i++)
sum+ = func(arr[i]);
printf("%d", sum);
}
func(int x)
{ int val,x;
val = 2;
return(x+ val++);
}
11. Given the following data:
• Process P1 takes 2 seconds
• Process P2 takes 3 seconds
• Process P3 takes 4 seconds
• Process P4 takes 1 second
• Process P5 takes 6 seconds
Find the average time in case of shortest job first (SJF) scheduling.
12. Given a string STOCK and a stack of size 4.
Which of the following strings cannot be generated using this stack.
(a) TSOCK
(b) TOSKC
(c) STOCK
(d) TKOSC
(e) None of these
13. Inversion of a matrix will take which of the following time complexities?
(a) O(n)
(b) O(n²)
(c) O(log n)
(d) O(n³)
(e) None of these
14. A drum rotates at 4000 rpm. What is its average access time.
15. What range of integral values can be stored using 32 bits?
16. Where are the following variables stored
• Automatic
• Global
• Static
17. If a layer 4 transfers data at the rate of 3000 bytes/sec.
What will be the size of data block transferred by Layer 2
18. What is the greatest disadvantage of dynamic RAM over static RAM
Ans. High Power and need to refresh every 2 ms.
19. What happens when the CPU gets interrupted?
20. Find the Postfix of the following string
(a + b) * ((-d) *f (ab - cd))
21. E --> E + E| E * E | E/E | E - E| .... then which is correct
(a) It is ambigous
(b) It is inherently ambigous
(c) It is non inherently ambigous
(d) None of the above
22. If there are n nodes and K edges in a graph then what is the order of traversing
Ans. O(n²)
23. A graph is represented as an adjacency list with n vertices and e edges
What is its time complexity
Ans. O(n + e)
24. An array with address KV[a] had n elements. Which of the following correctly addresses the ith element of the array.
(a) KV(a) - 2a + 2i
(b) KV(a) +2i
(c) KV(a) - 2a
(d) None of these
25. Give an example of a primitive instruction in microprocessors.
26. A computer has 8 bit data bus and 16 bit address line.
How many machine cycles will it take to store the contents to a memory location?
27. Where is a variable defined in a function stores?
Ans. Process Swappable Area
28. For the following C progralm
int d=0;
for(int i=0;i<31;i++)
for(int j=0;j<31;j++)
for(int k=0;k<31;k++)
if (((i+j+k) % 3)==0)
d=d+1;
Find value of d
29. e=
What forms do the expressions created by the above definition fit in
Ans. All arithematic expressions
30. If a set of numbers are in sorted order then which of the following sorting method is best
Ans. Bubble Sort
31. A magnetic tape is similar to which of the following structures
Ans. List
32. The s/n id 3 dB Find the capacity of the line.
1. What is the mistake in the following program segment ?
f()
{
int a;
void c;
f2(&c,&a);}
2. a=0;
b=(a=0)?2:3;
a) What will be the value of b and why ?
b) If in first statement a= 0 is replaced by a= -1, b = ?
c) If in second statement a=0 is replaced by a = -1, b=?
3. char *a[2];
int const *p;
int *const p;
struct new { int a;int b; *var[5] (struct new)}
Describe the statements in the above given construct ?
4. f()
{
int a=2;
f1(a++);
}
f1(int c)
{
printf("%d", c);
}
What is the value of c ?
5. f1()
{
f(3);
}
f(int t)
{
switch(t);
{
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
What is the value of c?
6. What is the fallacy in the following program segment ?
int *f1()
{
int a=5;
return &a;
}
f()
int *b=f1()
int c=*b;
}
7. Give the C language equivalents of the following
a)Function returning an int pointer
b)Function pointer returning an int pointer
c)Function pointer returning an array of integers
d)Array of function pointer returning an array of integers
8. Find the fallacy in the following program segment?
int a;
short b;
b=a;
9. Define function ? Explain arguments in functions ?
10. How does C pass variables to a function ?
11. Explain the following program segment.
f(){
int *b;
*b=2;
}
12. Explain binary trees and their use ?
13. Draw the diagram showing the function stack, illustrating the variables that were pushed on the stack at the point when function f2 has been introduced .
type def struct
{ double x,double y} point; }
main( int argc, char *arg[3])
{ double a;
int b,c;
f1(a,b); }
f1(double x, int y)
{point p;
stack int n;
f2(p,x,y)
}
f2(point p, double angle)
{ int i,j,k,int max;
}
1. Given the following statement
enum day = { jan = 1 ,feb=4, april, may}
What is the value of may?
(a) 4
(b) 5
(c) 6
(d) 11
(e) None of the above
2. Find the output for the following C program
main
{int x,j,k;
j=k=6;x=2;
x=j*k;
printf("%d", x);
3. Find the output for the following C program
fn f(x)
{ if(x<=0)
return;
else f(x-1)+x;
}
4. Find the output for the following C program
i=20,k=0;
for(j=1;j{k+=j<10?4:3;
}
printf("%d", k);
Ans. k=4
5. Find the output for the following C program
int i =10
main()
{int i =20,n;
for(n=0;n<=i;)
{int i=10;
i++;
}
printf("%d", i);
Ans. i=20
6. Find the output for the following C program
int x=5;
y= x&y
7.Find the output for the following C program
Y=10;
if( Y++>9 && Y++!=10 && Y++>10)
{printf("%d", Y);
else
printf("%d", Y);
}
Ans. 13
8. Find the output for the following C program
f=(x>y)?x:y
a) f points to max of x and y
b) f points to min of x and y
c)error
Ans. (a)
9. What is the sizeof(long int)
(a) 4 bytes
(b) 2 bytes
(c) compiler dependent
(d) 8 bytes
10. Which of the function operator cannot be over loaded
(a) <=
(b) ?:
(c) ==
(d) *
11. Find the output for the following C program
main()
{intx=2,y=6,z=6;
x=y==z;
printf(%d",x)
}
11. Find the output for the following C program
main()
{intx=2,y=6,z=6;
x=y==z;
printf(%d",x)
}
Section C (Programming Skills)
Answer the questions based on the following program
STRUCT DOUBLELIST
{ DOUBLE CLINKED
INT DET; LIST VOID
STRUCT PREVIOUS; (BE GIVEN AND A PROCEDURE TO DELETE)
STRUCT NEW; (AN ELEMENT WILL BE GIVEN)
}
DELETE(STRUCT NODE)
{NODE-PREV-NEXT NODE-NEXT;
NODE-NEXT-PREV NODE-PREV;
IF(NODE==HEAD)
NODE
}
Q. In what case the prev was
(a) All cases
(b) It does not work for the last element
(c) It does not for the first element
(d) None of these
Answer the questions based on the following program
VOID FUNCTION(INT KK)
{KK+=20;
}
VOID FUNCTION (INT K)
INT MM,N=&M
KN = K
KN+-=10;
}
Q. What is the output of the following program
main()
{ int var=25,varp;
varp=&var;
varp p = 10;
fnc(varp)
printf("%d%d,var,varp);
}
(a) 20,55
(b) 35,35
(c) 25,25
(d)55,55
6. If a binary tree is constructed using nodes with two pointers each,
how many null pointers does a tree with N nodes have
a) n-1
b) n
c) n+1
d) Depends on the number of edges
7. Which of following statements about heap is wrong
a) An n element heap has height log n(base of log is 2)
b) Smallest element of heap is always a leaf
c) A array in reverse sorted order is a heap
d) A heap can't contain any element more than once
8. When applets are downloaded from web sites , a byte verifier performs _________?
Ans. Status check.
9. For the following C program
void insert(key,r)
typekey key,data array r;
{extern int n;
if(n>=max) /*error table if full */
else r[n++].k=key;
}
This on executing, enables a
a) Basic sequential search
b) Binary search
c) Interpolation search
d) None
10. Find the outpur of the following C program
void f(char *p)
{p=(char *) malloc(6);
strcpy(p,"hello");
}
void main( )
{char *P="bye";
f(p);
printf("%s',p);
}
11. Time taken to access cache is 100ns and to access memory is 1000ns.
Hit ratio given. Find the average access time
12. Path testing is
a) Black box testing strategy
b) White box testing strategy
c) An installation .........
d) An enviornment
13. X:verification' asks are we building the right product
Y:validation' asks are we building the product right
14. Which one of the following can't be used to find an internet address given the domain name
a) /etc/host
b) NIS yellow pages
c) DNS
d) ARP
15. Flow control is necessary for the transport protocol layer due to the following reasons
a) Unreliable link
b) Congestion at receiver
c) Packets out of sequence
d) None of these
16. In public key encryption, if A wants to send a message to B so that no one else can read the message
then A encrypts the message using
a) A's public key
b) A's private key
c) B's public key
d) B's private key
17. Which of the following is not condition having a deadlock resource previous granted
can be forcebly taken away from a process
a) Resources need to be used in mutually exclusion fashion
b) Process can request new resources, as they continue to hold on to old ones
c) Here is a cycle in the resource allocation graph
16. An IP/IPX packet received by a computer using... having IP/IPX both how the packet is handled.
Ans. Read the, field in the packet header with to send IP or IPX protocol.
17. The range of the 32 bit number in two's complement form is _______
18. Cyclomatic complexity
{if((x=0) or (y=0))
p=0;
else
{p=x;i=1;
while(i!=y)
{p=p+x;
i=i+1; }
}
}
19. Activation record will contain the
a) Storage for simple names
b) Information about attributes for local names
c) Return address
d) All of the above
20. Global static variable within a file is intended to
a) Localize swap
b) Retain value persistently
c) Define constant
d) Fixed address in memory
21. Why is thread switch faster than a process switch
22. What is the binary equivalent of 41.6875
23. Checkpoint value will be calculated in
24. DHCP is used for
a) IP address allocation
b)dynamic host configuration protocol
25. For the following C program
int x(char *a)
{a=(char *) malloc(10*sizeof(char));
*a="hello";
}
main()
{char *a="new";
x(a);
printf("%s",a);
}
The output is
a) Hello
b) New
c) Hello new
d) Run time error
NOTE: The questions are of multiple choice format in the paper
What is the output of the program given below
#include
main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}
What is the output of the following program
#include
main()
{
int i=0;
fork();
printf("%d",i++);
fork();
printf("%d",i++);
fork();
wait();
}
What is the memory allocated by the following definition ?
int (*x)[10];
What is the memory allocated by the following definition ?
int (*x)();
In the following program segment
#include
main()
{
int a=2;
int b=9;
int c=1;
while(b)
{
if(odd(b))
c=c*a;
a=a*a;
b=b/2;
}
printf("%d\n",c);
}
How many times is c=c*a calculated?
In the program segment in question 5 what is the value of a at the end of the while loop?
What is the output for the program given below
typedef enum grade{GOOD,BAD,WORST,}BAD;
main()
{
BAD g1;
g1=1;
printf("%d",g1);
}
Give the output for the following program.
#define STYLE1 char
main()
{
typedef char STYLE2;
STYLE1 x;
STYLE2 y;
clrscr();
x=255;
y=255;
printf("%d %d\n",x,y);
}
In the following program
#include
main()
{
char *pDestn,*pSource="I Love You Daddy";
pDestn=malloc(strlen(pSource));
strcpy(pDestn,pSource);
printf("%s",pDestn);
free(pDestn);
}
(a)Free() fails
(b)Strcpy() fails
(c)prints I love You Daddy
(d)error
What is the output for the following program
#include
main()
{
char a[5][5],flag;
a[0][0]='A';
flag=((a==*a)&&(*a==a[0]));
printf("%d\n",flag);
}
A sorting program is given .You need to print the output of every outer ‘for’ loop.
Main()
{
int n=8,I,j,k;
int a[7]={44,55,42,12,6,94,67};
for(I=0;I
k=I;
x=a[k];
for(j=I+1;j
if(a[j]
k=j;
x=a[k];
a[k]=a[I];
a[I]=x;
}
}
}
The precedence of operators are given, you have to find the value highest :+ followed by -,*,/ parentheses r given higher precedence to operators unary operator ‘-‘ is always written within parentheses association is from right to left
Questions were given like L-Value R-Value
a) z[I+2]
b)*x
c)&x
d)&(&x)
e)
Assume the following:
a. A tape drive can store 4096 bytes/millimeter
b. Forgot
c. A IRG is necessary and the length is 2 millimeter
Answer the following question:
For storing 20MB how many millimeters of tape is required
What is the storage capacity if the tape is 10000meters long
For a infinite storage how many IRGs are required in a tape that stores 1 GB of data.
The following program is to calculate the number of lines, number of words, number of characters from file. You got to complete the C program (15 marks)
# define IN 1
# define OUT ------
main()
{
int nc=nw=nl= ------,state= ------.c;
while((----=getchar()!=EOF))
{
++ ----;
if (c= = ‘\n’)
++ ----;
if(c = = ‘ ‘ || c = = ‘\n’ || c= =’\t’)
state= ----;
elseif(state = ----)
{
state= -----;
++ -----;
}
}
}
C TEST
This test consists of 50 questions. The Set Code for this paper is D.
1. The C language terminator is
(a) semicolon (b) colon (c) period (d) exclamation mark
2. What is false about the following -- A compound statement is
(a) A set of simple statements (b) Demarcated on either side by curly brackets
(c) Can be used in place of simple statement (d) A C function is not a compound statement.
3. What is true about the following C Functions
(a) Need not return any value (b) Should always return an integer
(c) Should always return a float (d) Should always return more than one value
4. Main must be written as
(a) The first function in the program (b) Second function in the program
(c) Last function in the program (d) Any where in the program
5. Which of the following about automatic variables within a function is correct ?
(a) Its type must be declared before using the variable (b) They are local
(c) They are not initialized to zero (d) They are global
6. Write one statement equivalent to the following two statements: x=sqr(a); return(x);
Choose from one of the alternatives
(a) return(sqr(a)); (b) printf("sqr(a)");
(c) return(a*a*a); (d) printf("%d",sqr(a));
7. Which of the following about the C comments is incorrect ?
(a) Comments can go over multiple lines
(b) Comments can start any where in the line
(c) A line can contain comments with out any language statements
(d) Comments can occur within comments
8. What is the value of y in the following code?
x=7;
y=0;
if(x=6) y=7;
else y=1;
(a) 7 (b) 0 (c) 1 (d) 6
9. Read the function conv() given below
conv(int t)
{
int u;
u=5/9 * (t-32);
return(u);
}
What is returned
(a) 15 (b) 0 (c) 16.1 (d) 29
10. Which of the following represents true statement either x is in the range of 10 and 50 or y is zero
(a) x >= 10 && x <= 50 || y = = 0 (b) x<50
(c) y!=10 && x>=50 (d) None of these
11. Which of the following is not an infinite loop ?
(a) while(1)\{ ....} (b) for(;;){...}
(c) x=0; (d) # define TRUE 0
do{ /*x unaltered within the loop*/ ...
.....}while(x = = 0); while(TRUE){ ....}
12. What does the following function print?
func(int i)
{
if(i%2)return 0;
else return 1;
}
main()
{
int =3;
i=func(i);
i=func(i);
printf("%d",i);
}
(a) 3 (b) 1 (c) 0 (d) 2
13. How does the C compiler interpret the following two statements
p=p+x;
q=q+y;
(a) p= p+x; (b)p=p+xq=q+y; (c)p= p+xq; (d)p=p+x/q=q+y;
q=q+y; q=q+y;
For questions 14,15,16,17 use the following alternatives:
a.int b.char c.string d.float
14. '9'
15. "1 e 02"
16. 10e05
17. 15
18. Read the folllowing code
# define MAX 100
# define MIN 100
....
....
if(x>MAX)
x=1;
else if(x
x=50;
if the initial value of x=200,what is the value after executing this code?
(a) 200 (b) 1 (c) -1 (d) 50
19. A memory of 20 bytes is allocated to a string declared as char *s then the following two statements are executed:
s="Entrance"
l=strlen(s);
what is the value of l ?
(a)20 (b)8 (c)9 (d)21
20. Given the piece of code
int a[50];
int *pa;
pa=a;
To access the 6th element of the array which of the following is incorrect?
(a) *(a+5) (b) a[5] (c) pa[5] (d) *(*pa + 5}
21. Consider the following structure:
struct num nam
{
int no;
char name[25];
}
struct num nam n1[]={{12,"Fred"},{15,"Martin"},{8,"Peter"},{11,Nicholas"}};
.....
.....
printf("%d%d",n1[2],no,(*(n1 + 2),no) + 1);
What does the above statement print?
(a) 8,9 (b) 9,9 (c) 8,8 (d) 8,unpredictable value
22. Identify the in correct expression
(a)a=b=3=4; (b)a=b=c=d=0; (c)float a=int b= 3.5; (d)int a; floatb;a=b=3.5;
23. Regarding the scope of the varibles;identify the incorrect statement:
(a) automatic variables are automatically initialized to 0 (b) static variables are are automatically initialized to 0
(c) the address of a register variable is not accessible (d) static variables cannot be initialized with any expression
24. cond 1?cond 2?cond 3?:exp 1:exp 2:exp 3:exp 4;
is equivalent to which of the following?
(a) if cond 1
exp 1;
else if cond 2
exp 2;
else if cond 3
exp 3;
else exp 4;
(b) if cond 1
if cond 2
if cond 3
exp 1;
else exp 2;
else exp 3;
else exp 4;
(c) if cond 1 && cond 2 && cond 3
exp 1 |exp 2|exp 3|exp 4;
(d) if cond 3
exp 1;
else if cond 2 exp 2;
else if cond 3 exp 3;
else exp 4;
25. The operator for exponentiation is
(a) ** (b) ^ (c) % (d) not available
26. Which of the following is invalid
(a) a+=b (b) a*=b (c) a>>=b (d) a**=b
27. What is y value of the code if input x=10
y=5;
if (x==10)
else if(x==9)
else y=8;
(a)9 (b)8 (c)6 (d)7
28. What does the following code do?
fn(int n, int p, int r)
{
static int a=p;
switch(n)
{
case 4:a+=a*r;
case 3:a+=a*r;
case 2:a+=a*r;
case 1:a+=a*r;
}
}
(a) computes simple interest for one year (b) computes amount on compound interest for 1 to 4 years
(c) computes simple interest for four year (d) computes compound interest for 1 year
29.
a=0;
while(a<5)
printf("%d\\n",a++);
How many times does the loop occurs?
(a) infinite (b)5 (c)4 (d)6
30. How many times does the loop iterated ?
for(i=0;i=10;i+=2)
printf("Hi\\n");
(a)10 (b) 2 (c) 5 (d) None of these
31. What is incorrect among the following
A recursive function
(a) calls itself (b) is equivalent to a loop
(c) has a termination condition (d) does not have a return value at all
32. Which of the following go out of the loop if expn 2 becoming false
(a) while(expn 1)\{...if(expn 2)continue;} (b) while(!expn 1)\{if(expn 2)continue;...}
(c) do{..if(expn 1)continue;..}while(expn 2); (d) while(!expn 2)\{if(expn 1)continue;..\}
33. Consider the following program
main()
{
unsigned int i=10;
while(i>=0)
{
printf("%u",i)
i--;
}
}
How many times the loop will get executed
(a)10 (b)9 (c)11 (d) infinite
34.Pick out the odd one out
(a) malloc() (b) calloc() (c) free() (d) realloc()
35.Consider the following program
main()
{
int a[5]={1,3,6,7,0};
int *b;
b=&a[2];
}
The value of b[-1] is
(a) 1 (b) 3 (c) -6 (d) none
36. # define prod(a,b)=a*b
main()
{
int x=2;
int y=3;
printf("%d",prod(x+2,y-10));
}
the output of the program is
(a) 8 (b) 6 (c) 7 (d) None
37.Consider the following program segment
int n,sum=1;
switch(n)
{
case 2:sum=sum+2;
case 3:sum*=2;
break;
default:sum=0;
}
If n=2, what is the value of sum
(a) 0 (b) 6 (c) 3 (d) None of these
38. Identify the incorrect one
1.if(c=1)
2.if(c!=3)
3.if(a 4.if(c==1)
(a) 1 only (b) 1&3 (c) 3 only (d) All of the above
39. The format specified for hexa decimal is
(a) %d (b) %o (c) %x (d) %u
40. Find the output of the following program
main()
{
int x=5, *p;
p=&x
printf("%d",++*p);
}
(a) 5 (b) 6 (c) 0 (d) none of these
41.Consider the following C code
main()
{
int i=3,x;
while(i>0)
{
x=func(i);
i--;
}
int func(int n)
{
static sum=0;
sum=sum+n;
return(sum);
}
}
The final value of x is
(a) 6 (b) 8 (c) 1 (d) 3
43. Int *a[5] refers to
(a) array of pointers (b) pointer to an array (c) pointer to a pointer (d) none of these
44.Which of the following statements is incorrect
(a) typedef struct new
{
int n1;
char n2;
} DATA;
(b) typedef struct
{
int n3;
char *n4;
}ICE;
(c) typedef union
{
int n5;
float n6;
} UDT;
(d) #typedef union
{
int n7;
float n8;
} TUDAT;
~Boredguru.com~
************************
1. Find the locus of the point whose sum of distance from 2 fixed points is constant.
2. [-infinity to +infinity]integration(exp(-x*x))
3. The product of any 3 consecutive nos is always divisible by _ ? options[12/6/10/24]
4 int i=0,j=50
while (i
if(
{
i++
}
elseif(
{
j--
}
else(
{
j--
}
}
How many times the body of the loopis going to be executed?
options[unknown/25/50/depends on the given condtn]
5 How can you include a library code written in C++ in a source code written in C?
(Options are there)
Ans. Some cross-linked platform(compiler) is required for this.
6 int a[20],i
for(i=0;i<20;i++)
{
a[i]=i;
}
for(i=0;i<20;i++)
{
a[i]=a[20-i]
}
What is the final content of the program.
ALTER
Sample Test Paper :Alter Engineering
int b=10;
int *p=&b;
*p++;
printf("%d",*p);
what is the output?
What is the difference between malloc, calloc and realloc?
What does malloc return in C and C++?
main()
{
char *a="hello";
char *b="bye";
char *c="hai";
int x=10,y=100;
c=(x
printf("%s",c);
}
whats the output?
void main()
{
int a,b;
a=sumdig(123);
b=sumdig(123);
printf("%d %d",a,b);
}
int sumdig(int n)
{
static int sum;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
sum=sum+d;
sumdig(n);
}
else
return s;
}
what is the output?
Declare a pointer to a function that takes a char pointer
as argument and returns a void pointer.
How do we open a binary file in Read/Write mode in C?
C++
class A
{
public:
A()
{
}
~A();
};
class derived:public A
{
derived();
};
what is wrong with this type of declaration?
what do you mean by exception handling?
What are "pure virtual" functions?
What is the difference between member functions and
static member functions?
What is the4 difference between delete[] and delete?
Question on Copy constructor.
What are namespaces?
One question on namespace.
What are pass by valu and pass by reference?
what is the disadvantage of pass by value?
I didnt get this. if you have the answer plz tell me.
How to invoke a C function using a C++ program?
char *str;
char *str1="Hello World";
sscanf(str1,"%s",str);
what is the output?
Difference between function overloading and function overriding.
There is a base class sub, with a member function fnsub(). There are
two classes super1 and super2 which are subclasses of the base class sub.
if and pointer object is created of the class sub which points to any
of the two classes super1 and super2, if fnsub() is called which one
will be inoked?
main()
{
char s[]={‘1’,’2’,’3’,0,’1’,’2’,’3’};
printf(“%s”,s);
}
a)123 123
b)123123
c)1230123
d)error
main()
{
char *p=”Caritor”;
*++p;
printf(“%s”,p);
*++p;
printf(“%s”,*p);
}
Ans: aritor ritor
main()
{
int K,j;
for(k=0;k<10;k++)
{
some codes
}
}
Ans : ERROR since k not declared
How to print “%” symbol in printf?
Ans:
printf(“\%”);
What is the max no of char in command line arguments?
Can arithmetic Operation be performed on void pointers?
main()
{
char str1[]=”HELLO”;
char str2[]=”HELLO”;
if(str1==str2)
printf(“EQUAL”);
else
printf(“NOT EQUAL”);
}
Ans: NOT EQUAL ,Since string can be compared only using strcmp()
main(int argc)
{
int a;
printf(“%d”,a);
}
How to declare argc and argv
ans: main(int argc,char* argv[])
main()
{
int s=5;
printf(“%d”,s,s<<2,s>>2);
}
ans:5 20 1
main()
{
int a[2][2]={2,3}
printf(“%d%d%d%d”,a[0][0],a[0][1],a[1][0],a[1][1]};
}
a)2000
b)0002
c)2300
d)error
ans: 2300
main
{
int a[5]={2,3};
printf(“%d%d%d”,a[2],a[3],a[4]);
}
extern int I; is it a declaration or definition?
main()
{
int i=-3,j=2,k=0,m;
m= ++j&&++i||++k;
printf(“%d%d%d”,i,j,k,m);
}
main()
{
int i=-3,j=2,k=0,m;
m= ++j&&++i&&++k;
printf(“%d%d%d”,i,j,k,m);
}
main()
{
const int i=7;
printf(“%d”,++i);
}
#define I 6
main()
{
printf(“%d”,++I);
}
f array begins at position 1002
main()
{
int a[2][3][4]={{1,2,3,4,5,6,7,8,9,1,1,2},{2,3,4,7,6,7,8,9,0,0,0,0}};
printf(“%d%d%d%d”,a,*a,**a,***a);
}
main()
{
printf(“%c”,7[“sundaram”]);
}
struct name
{
int a;
char b;
char n;
short s;
}n1;
main()
{
printf(“%d”,sizeof(n1));
}
main()
{
enum{ m=2,n,o=60,p};
printf(“%d”,p);
}
If A file contains the line “I am a boy\r\n” then on reading this line into the array str using fgets()
What would str contain?
In command line enter myprog 1 2 3 what is output?
main(int argc , char * argv[])
{
int I,j=0;
for(i=0;i
printf(%d”,j);
}
In command line enter myprog Friday Tuesday Thursday what is output?
main(int argc , char * argv[])
{
printf(“%c”,**++argv):
}
14>
main()
{
printf(“%d”,-1>>4);
}
**********************
main()
{
printf("as");
printf("\bhi");
printf("is\n");
} wat will b printed.
main()
{
unsigned short a=-1;
unsigned char b=a;
printf("%d %d ",a,b);
}
wat is o/p of the program
a. 65535 -1
b. 65535 65535
c. -1 -1
arrays base address is 1000....array is a[5][4]..then wat is de
correct address of a[4][3]...
ans:1056
one packet is 64bytes..no of pkts send is 16000..then total no of bytes send is
ans 1024000
#define maxval 5
int main (void)
{
int i=1;
if(i-maxval)
{
printf("inside");
}
else
{
printf("out");
}
find o/p???
#define a 3+3
#define b 11-3
main()
{
printf("%d",a*b);
}
wat is o/p?????
A question in which segment address is given ..logical address is 800..base addresses also given ..u hav 2 find physical address..
There was a question on processor speed in nanocycles..then it performs a instruction in x cycles..dont remember
main()
{
int *i;
int s=(int *)malloc(10*sizeof(int));
for (i=0;i<10;i++)
{
printf("%d",i*i)
}
wats o/p
************************8
DHARMA
Give the output of the programs in each case unless mentioned otherwise
void main()
{
int d=5;
printf("%f",d);
}Ans: Undefined
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
void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}Ans: 6
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
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}Ans: less
void main()
{
float j;
j=1000*1000;
printf("%f",j);
}
1. 1000000
2. Overflow
3. Error
4. None
Ans: 4
How do you declare an array of N pointers to functions returning pointers to functions returning pointers to characters? Ans: The first part of this question can be answered in at least three ways:
Build the declaration up incrementally, using typedefs:
typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */
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 of 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-function 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.)
A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers.
Write the way to initialize the 2nd element to 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
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.
void main()
{
int i=7;
printf("%d",i++*i++);
}Ans: 56
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
void main()
{
intcount=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}
Ans: 20 20 20
There was question in c working only on unix machine with pattern matching.
what is alloca() Ans : It allocates and frees memory after use/after getting out of scope
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}
Ans: 321
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}
Ans: anything is good.
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"
Which of the following about the following two declaration is true
i ) int *F()
ii) int (*F)()
Choice :
a) Both are identical
b) The first is a correct declaration and the second is wrong
c) The first declaraion is a function returning a pointer to an integer and the second is a pointer to function returning
int
d) Both are different ways of declarin pointer to a function Answer : c) The first de...
What are the values printed by the following program?
#define dprint(expr) printf(#expr "=%d\n",expr)
main()
{
int x=7;
int y=3;
dprintf(x/y);
}
Choice:
a) #2 = 2 b) expr=2 c) x/y=2 d) none
Answer: c)x/y=2
Which of the following is true of the following program
main()
{
char *c;
int *p;
c =(char *)malloc(100);
ip=(int *)c;
free(ip);
}
ans: The code functions properly releasing all the memory allocated
.output of the following.
main()
{
int i;
char *p;
i=0X89;
p=(char *)i;
p++;
printf("%x\n",p);
}
ans:0X8A
which of the following is not a ANSI C language keyword? ans:Function.
When an array is passed as parameter to a function, which of the following statement is correct choice:
a) The function can change values in the original array
b) In C parameters are passed by value. The funciton cannot change the original value in the array
c) It results in compilation error when the function tries toaccess the elements in the array
d) Results in a run time error when the funtion tries to access the elements in the array
Answer: a) The fu...
The type of the controlling expression of a switch statement cannot be of the type
a) int b) char c) short d)float e) none
Answer : d)float
What is the value of the expression (3^6) + (a^a)?
a) 3 b) 5 c) 6 d) a+18 e) None
Answer : 5
What is the value assigned to the variable X if b is 7 ?
X = b>8 ? b <<3 : b>4 ? b>>1:b;
a) 7 b) 28 c) 3 d) 14 e) None
ans: 3;
Which is the output produced by the following program
main()
{
int n=2;
printf("%d %d\n", ++n, n*n);
}
a) 3,6 b) 3,4 c) 2,4 d) cannot determine
Answer : b) 3,4
What is th output of the following program?
int x= 0x65;
main()
{
char x;
printf("%d\n",x)
}
a) compilation error b) 'A' c) 65 d) unidentified
What is the output of the following program
main()
{
int a=10;
int b=6;
if(a=3)
b++;
printf("%d %d\n",a,b++);
}
a) 10,6 b)10,7 c) 3,6 d) 3,7 e) none
Answer : d) 3,7
What can be said of the following program?
main()
{
enum Months {JAN =1,FEB,MAR,APR};
Months X = JAN;
if(X==1)
{
printf("Jan is the first month");
}
}
a) Does not print anything
b) Prints : Jan is the first month
c) Generates compilation error
d) Results in runtime error
Answer: b) Prints : Jan..
What is the output of the following program?
main()
{
char *src = "Hello World";
char dst[100];
strcpy(src,dst);
printf("%s",dst);
}strcpy(char *dst,char *src)
{while(*src) *dst++ = *src++;
}
) "Hello World" b)"Hello" c)"World" d) NULL e) unidentified
Answer: d) NULL
What is the output of the following program?
main()
{
int l=6;
switch(l)
{ default : l+=2;
case 4: l=4;
case 5: l++;
break;
}
printf("%d",l);
}
a)8 b)6 c)5 d)4 e)none
Answer : c)5
What is the output of the following program?
main()
{
int x=20;
int y=10;
swap(x,y);
printf("%d %d",y,x+2);
}
swap(int x,int y)
{
int temp;
temp =x;
x=y;
y=temp;
}
a)10,20 b) 20,12 c) 22,10 d)10,22 e)none
Answer:d)10,22
What is the output of the following problem ?
#define INC(X) X++
main()
{
int X=4;
printf("%d",INC(X++));
}
a)4 b)5 c)6 d)compilation error e) runtime error
Answer : d) compilation error
what can be said of the following
struct Node {
char *word;
int count;
struct Node left;
struct Node right;
}
a) Incorrect definition
b) structures cannot refer to other structure
c) Structures can refer to themselves. Hence the statement is OK
d) Structures can refer to maximum of one other structure
Answer :c)
What is the size of the following union. Assume that the size of int =2, size of float =4 and size of
char =1.
Union Tag{
int a;
flaot b;
char c;
};
a)2 b)4 c)1 d) 7
What is the output of the following program? (. has been used to indicate a space)
main()
{
char s[]="Hello,.world";
printf(%15.10s",s);
}
a )Hello,.World...
b)....Hello,.Wor
c)Hello,.Wor....
d)None of the above
main()
{
printf("%d",printf("HelloSoft"));
} Output?
case 1: case 2:
typedef Struct { typedef Struct {
int a; char p;
char b; int q;
int d; char k;
char e; int l;
}A; }A;
Assuming 'packing' is not enabled, which case will give an error of Sizeof(A) less.
main()
{
int i=3;
printf("%d %d %d",i++,i,++i);
}
main()
{
int i=10;
int j,k=5;
int a[10];
for(j=0;j<10;j++)
a[j]=(i+k)+(i*k);
}
Optimize the above code.
Write In Order Tree Traversal Pseudo-code.
main()
{
int *p=0x100;
int *q=0x100;
int k=p*q;
printf("%x\n",k);
} Output ?
Char* foo(Str...) {
char str[4];
strcpy(str,"HelloSoft");
return str;
} Output?
int a[10][20][30][40];
int *p
How to access an element of a using p?
main()
{
int i=10;
if(i>20)
if(i==10)
print("Hi");
else
printf("Bye");
} Output ?
main()
{
float f;
int i;
//something like this not remember these 4 questionsexactly
f=(float *)malloc(sizeof((float *)*4));
}
#define ADD(X,Y) X+Y
main()
{
#undef ADD(X,Y);
fun();
}
fun()
{
int y=ADD(3,2);
printf("%d",y);
}
o/p?
Runtime error(linker error): _add undefined in module
Which of the following is illegal
(a)void v;
(b)void *v;
(c)void **v;
(d)all are legal
#define int INTEGER/*line1*/
#define INTEGER int/*line 2*/
main()
{
INTEGER p=10;/*line 5*/
printf("%d",p);
}
o/p?
(a) compiler error at line 1
(b) compiler error at line 2
(c) compiler error at line 5
(d) No error,prints 10
ans:c
main()
{
int counter=1;
for(;;)
{
counter++;
if(counter>9)
break;
}
}
in the above program
(a)error b'coz for should have parameters
(b)error bcoz 2 semicolons in a for loop are invalid
(c)no error,loop is executed once
(d) no error ,loop is executed 10 times
main()
{
char str={'H','E','L','L','O','\0'}
printf("%s/n",str+1);
}
o/p?
(a)prints ELLO
(b)prints HELLO
(c)prints ILLO (i.e.'H' is incremented by 1)
(d)...
i=23, j=4, c=0;
c=i++-++j;
o/p?
#define CUBE(x) x*x*x
#define MUL3(x,y) 3*x*y
#define ADD(x) x+y
some statement maikng use of the preprocessors defined above............find o/p.
virtual destructors r used for ?
2 questions on friend functions & classes
char c[]="123456789";
i=4;
printf("%c %c", c[i], i[c]);
o/p?
one more question on these lines.
int *ptr;
p=0;
p++;
printf("%u", p);
o/p?
a. 0 b. garbage value c. 4 d. none of the above
double i=0.0;
switch(i)
{
case 0.0:
printf("jgdj");
case 1.0:
printf("ptoy");
break;
default:
printf("hdfv");
}
o/p?
volatile int i;
in d above statement, is "volatile"
a. a type declaration b. type qualifier c. storage class d. none of the above
**************
void checkA()
{
int a=2;
if(a=3!=3)
printf(" 3 ");
else
printf(" 2 ");
return;
}
ans. 2
main()
{
char P[]={"Hello World"};
printf(" %s \n",p);
main();
} ans (abnormal program termination)
# define D 10
# define Y D+10
# define D 30
main(int argc, char *arc[])
{
printf(" %d \n",D);
}
ans.30
# define TRUE 0
main()
{
int i=0;
while(TRUE)
{
printf(" %d \n",i);
i++;
}
printf(" %d \n",i);
i++;
}
if(fp == fopen(\"dfas\",\"r\") = = NULL), what is the value of fp
a. NULL
b. 0
c. 1
d. 0 or 1
#define sqr(x) x*x, what is value of j if j == 2 * sqr(3 + 4)
#define FILENAME(extension) test_##extension, how will it print FILENAME(back)
a. test_back
b. test_#back
c. test_##back
d. ??
char *p == \"hello world\"
p[0] == \'H\', what will be printf(\"%s\", p);
a. Hello world
b. hello world
c. H
d. compile error
int fun(), how do u define pointer to this function ??
what is ment by int (* xyz)[13]
what is true from
a. base call ferernece is compatible with child class
b. child class reference is compatible with base class
c. no reference to class
d. ??
class b
{
}
class a
{
friend class b
}
then what is ture
a. a can access all protected and public members in b
b. b can access all protected and public members in a
c. a can access all members of a
d. b can access all members of b
What is the output
#include
main()
{
int n=0;
int i;
i=2;
switch(1)
{
case 0:do{
case 1:n++;
case 2:n++;
}
while(--i>0);
}
printf(\"n==%d\",n);
}
a. compile error
b. 4
c. 1
d. 0
Mathematics
Two liquids A : B in ratio 7:5 and now 24 gallons drain out and b is added the ratio becomes 5:7 what is containr capacity ? 30, 48 , 84, none
man has rope of length 660 mtr to fence a area , what is the max area he can fence ?
Son is about to celebrate 10th birthday. after 11 years his age will be half the average of his parents. his mother is 17 years older to him. what is the age of the father.
DI question where hotels project are given and no of rooms in each hotels , investment , project yr . and company name
were asked to find min cost per room is for which hotel , which avg cost per room etc.
Avg of 6 no is 8 what 7 th no shud be added to make avg 10;
difference of cube of a no and its square is a perfect square , what is the no. -> 5
diff of three consecutive nos square and the nos is 214; find the nos :
Interview Technical
Write a minimal C++ program .
(a) Talk about yourself
(b) What are your strengths.
(c) Where do you think you have to improve.
(d) Where do you see yourself after 5 years
main()
{
int i==2;
int a==4;
if((i+==3)>a)
{
printf( \" TRUE \");
}
else
{
printf(\"FALSE \");
}
}
What is the output of the program ..
Ans ) TRUE , coz i+==3 becomes incremented and i becomes 5 . So i is greater than a
C:-know about
calloc,
exit(),
pointer and arrays,
pointer to functions(5 th
chapter in K & R c book.(pointer fn. arguments thro'pointer)
some protype functions like swap,sinfunction in math.h
NOTE: Above paper we get before our test. They given all above quetions
and some of missing we are writing below. If any repeated skip that.
-pointer arithmatic
-what is the value of "i"?
i=Strlen("BLUE") + strlen ("purple")/strlen("red")-strlen("green")
ans:-1
i=2
printf("%ld%ld2%ld",i,i++,i--,i++);
answer check care fully may be 2223
what is the output of the following statements(string)
printf("what is /0 the output"):
ans.what is
3) some problem appears like this
main()
{
int i,a[10];
int *x
i = &a[6] - a;
printf("%d", i)
;
}
answers are given as 1 , 6 , not compiled , machine dependent
answer is 6;
4)
another program apperas like this
main()
{
int *x , y=2;
int * fun(int* );
x = (int *) malloc(sizeof(int));
fun(x,&y);
printf("%d%d",x,y);
}
int* fun(int *a, int *b)
{
*a = (*b)++;
return;
}
Program exactly i doesn,t know but the stress is on *a = (*b)++
but for me answers are not tallied i think the answer now is 2,3;
but in answers it is not given;
5)
another programme
struct pt
{ int x;
int y; }
struct
{ pt ptr;
int xtr}lt,*lptr=<
he will give some accessing methods of data
but the correctone is
lptr->ptr.x;
7)some problem is there which says some jumps but the correct one is
setjump and longjump
you study the jumps and clarify it;
8)
ne problem like this
c prototype for math function
ans is external double sin(double);
8) one problem on variables apperars answer is "file" dam shure
that is actually the scope of external static variabl;
9) child procees-> fork ( this is given in c programmes)
10) for parsing another problem ans is lex and yacc;
11) for backups and archieves ans is tar;
12) onebit on redirection of std error
ans may be $command >outfile 2>&1 check it;
13)
what is
int* p(char (*s)[]);
ans there is c you read it from schaum series;
14) what for chmod 654
rw-rw-r-- check it
15)
one small c programme that appears like this
main()
{ char *s = "hellow"
char *m = " how are you";
strcat(s,m);
pritnf("%s",s) ;
}
do this and note;
16) you read stdin, stdout, stderr files and how to redirect that files.
wrong statement about c++
a)code removably
b)encapsulation of data and code
c)program easy maintenance
d)program runs faster
struct base
{
int a,b;
base();
int virtual function1();
}
struct derv1:base{
int b,c,d;
derv1()
int virtual function1();
}
struct derv2 : base
{int a,e;
}
base::base()
{
a=2;b=3;
}
derv1::derv1(){
b=5;
c=10;d=11;}
base::function1()
{return(100);
}
derv1::function1()
{
return(200);
}
main()
base ba;
derv1 d1,d2;
printf("%d %d",d1.a,d1.b)
o/p is
a)a=2;b=3;
b)a=3; b=2;
c)a=5; b=10;
d)none
for the above program answer the following q's
main()
base da;
derv1 d1;
derv2 d2;
printf("%d %d %d",da.function1(),d1.function1(),d2.function1());
o/p is
a)100,200,200;
b)200,100,200;
c)200,200,100;
d)none
struct {
int x;
int y;
}abc;
you can not access x by the following
1)abc-->x;
2)abc[0]-->x;
abc.x;
(abc)-->x;
a)1,2,3
b)2&3
c)1&2
d)1,3,4
automatic variables are destroyed after fn. ends because
a)stored in swap
b)stored in stack and poped out after fn. returns
c)stored in data area
d)stored in disk
variable DESTDIR in make program is accessed as
a) $(DESTDIR)
b) ${DESTDIR}
c) DESTDIR
d) DESTDIR
The keystroke mouse entrie are interpreted in ms windows as
a) interrupt
b) message
c) event
d) none of the above
link between program and out side world (ms -win)
a)device driver and hardware disk
b)application and device driver
c)application and hardware device
d)none
after logout the process still runs in the background by giving the command
a)nohop
b)
process dies out but still waita
a)exit
b)wakeup
c)zombie
d)steep
n dynamic memory allocation we use
a) doubly linked list
b) circularly linked
c) B trees
d) L trees
e) none
To find the key of search the data structure is
a)hask key
b)trees
c)linked lists
d)records
18. Which is an error.
Int *p[3]
Int (*p)[3]
(Int *)(int ,int)
Int (*p[3])
Int *(p[3])
19. Which is not a processor.
(intel,duran,Celeron,athelon)
20. a[5]=={1,2,3,4,5}
printf("%d",a[3]);
printf("%d",3[a]);
printf("%d",*(a+3);
21. what is the output.
if(r= =5!= =4)
printf("inside");
else
printf("outside");
printf("%d",r);
22. for(i=0,j=0;i<10,j<10;i++,j+);
printf("%d",j); (compilation error,run time error,0)
23. Which is not an inter process communication.
(tee,shared memory,pipe,queue,file)
24. for loop on string.
25. Which is not a database.
(oracle,smalltalk,db2,Sybase)
26. #define prod((a>b)?a*a:b*b)
int p==0,q==-1;
prod(p++,q++)
what is result.
27. what is reference.
Some loop statements on "c" are given which are very easy.
28. main()
{
printf("hello");
main();
}
how many times it will print?
29. complexity of heap sort(ans:o(nlogn).
30. what will be the o/p?
int main()
{
char a,b;
printf(“%d%d%d%d”,sizeof(‘A’), sizeof(‘NULL’), sizeof(‘a’), sizeof(main));
}
31. necessity of pairty bit(ans:b).
32. >what is the o/p?
#DEFINE xyz(exr)printf(“exr=%d”,exr)
main()
{
int x=3;y=2;
xyz(x/y);
}
35 comments:
Hello my friends,
Just joined the gang. Hope to have very good time here.
luv
Riya
xanax online xanax brand versus generic - xanax and alcohol hangover
alprazolam price mastercard xanax online no prescription - xanax overdose treatment
buy tramadol online buy tramadol overnight shipping - tramadol jaw pain
generic xanax lisinopril xanax drug interactions - generic for xanax
xanax cost xanax side effects 0.5 mg - xanax and alcohol ok
buy tramadol online tramadol mechanism of action - generic-tramadol
buy tramadol online gabapentin tramadol withdrawal - cheap tramadol online
xanax online xanax bars overdose - xanax online no prescription cheap
order tramadol tramadol good withdrawal - tramadol hydrochloride sr 100mg
tramadol online pharmacy get high tramadol 50mg - what is a normal dosage of tramadol for dogs
cheap alprazolam xanax help zoloft withdrawal - xanax dosage insomnia
buy tramadol online que es tramadol 50 mg - tramadol for cats
carisoprodol no prescription drug test for carisoprodol - soma carisoprodol prescribing information
buy carisoprodol cod carisoprodol 350 mg directions - carisoprodol long term use
xanax online xanax high fun - online rx no prescription xanax
cheap cialis online generic cialis release date - cialis online andorra
I could not refrain from commеnting. Well ωritten!
Look at my webpage ephedra plant
buy cialis online cialis golf tips - generic cialis 200mg
Howdy, I believе уour web site could be having
іnternet bгowser compatibility issuеs.
When I lοok at yоuг web sitе іn Safari, it
loοks fine hοwever when οpening in Ιnternet Εхplorer, it has some overlappіng іssues.
І simply wantеd tо prоvide you
wіth a quiсk heads up! Other than
that, wonderful blоg!
Also visit my web blog :: ephedrine reaction hcl
my site :: ephedrine buy online
buy cialis online is it safe to buy cialis online usa - buy cheap cialis today
buy xanax xanax xr dosage anxiety - long does 1mg xanax xr last
http://landvoicelearning.com/#21906 tramadol high feeling - order tramadol online cheap
buy tramadol tramadol 50 mg much - tramadol mg
buy tramadol online no prescription tramadol renal failure - order tramadol cod overnight
buy tramadol tramadol addiction statistics - tramadol no prescription overnight delivery
buy tramadol tramadol high dosage - order tramadol online without script
buy tramadol cheap generic tramadol 200mg - buy tramadol online overnight fedex
http://buytramadolonlinecool.com/#30694 tramadol ultram same - buy tramadol valium online
I pay a quick visit every day some websites and
information sites to read posts, but this webpage provides quality based posts.
Feel free to visit my webpage - cedarfinance.com
ways to buy ativan online ativan trazodone overdose - uncommon side effects ativan
buy tramadol online tramadol vs vicodin high - tramadol 50 mg use dogs
http://staam.org/#90723 tramadol hcl 50mg get you high - buy tramadol online in usa
I was recommended this web site by my cousin. I am not sure whether this post is
written by him as no one else know such detailed about my difficulty.
You're amazing! Thanks!
Look into my blog ... http://www.youtube.com/watch?v=caSEY6ykNKw
Hey! That’s a really nice post. I’m very certain I'll suggest it to my co-workers.In the event you publish more posts please email them to me.
Look at my homepage - having trouble getting pregnant the third time
Post a Comment