Rocks

  • October 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Rocks as PDF for free.

More details

  • Words: 179,810
  • Pages: 635
Table of Contents

Data Structures Aptitude....................................................................................................3 C Aptitude .........................................................................................................................12 C++ Aptitude and OOPS..................................................................................................76 Quantitative Aptitude......................................................................................................105 UNIX Concepts...............................................................................................................123 RDBMS Concepts...........................................................................................................137 SQL..................................................................................................................................155 Computer Networks........................................................................................................163 Operating Systems..........................................................................................................171

2

Data Structures Aptitude 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. 3

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)

Null Branches

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.     4

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. 5

Given tree: A

C

B

D

G

F

E

H

I

J

 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? 1

2

3

4 6

5

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.

7

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? The given graph:

 BFS:

AXGHPEMYJ

 DFS:

AXHPEYMJG

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? 8

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 11

5

4

-

6

-

19

7

-

8

-

16

-

24

20

22

78

92

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.

9

600

1 410

3

612

310

2985

2

200

5 400

4

1421

the equivalent minimal spanning tree is: 1

3 310

612

410

200

2

4

5

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) *

A

10

*

+

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. 01 STUDENT_REC

02

02

NAME

03 FIRST_NAME

11

YEAR_OF_STUDY

03 LAST_NAME

03 FIRST_SEM

03 SECOND_SEM

C Aptitude

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 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 12

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: 54321 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; } 13

} Answer: 2222223465 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: 00131 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)); 14

} Answer: 12 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); } 15

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 16

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<stdio.h> 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<stdio.h> 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<stdio.h> main() 17

{ 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<stdio.h> 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 18

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 19

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 <stdio.h> #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: 20

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)

21

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.

22

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<stdio.h> main() { int i=1,j=2; switch(i) { case 1: printf("GOOD"); break;

23

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).

24

40)

#include<stdio.h> 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<stdio.h> 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<stdio.h> main() { struct xx { int x;

25

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:

26

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

27

+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)

28

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.

29

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 4 th 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

30

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)

54)

31

main() { int i, n; char *x = “girl”; n = strlen(x); *x = x[n]; for(i=0; i, 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.

32

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: 255 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;

33

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:

34

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;

35

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:

36

-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<stdio.h> 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<stdio.h> 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<stdio.h> main() { register i=5; char j[]= "hello"; printf("%s %d",j,i); } Answer: hello 5 Explanation:

37

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()

38

{ 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.

39

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 <stdio.h> int one_d[]={1,2,3}; main() { int *ptr; ptr=one_d; ptr+=3; printf("%d",*ptr); } Answer: garbage value

40

Explanation: ptr pointer is pointing to out of the array range of one_d. 83)

# include<stdio.h> 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<stdio.h> 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;

41

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

42

3 2

1 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) {

43

/* 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()

44

{ 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: 0000 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;

45

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:

46

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=1j=1k=1

47

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)

48

#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

49

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 postdecrement 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)

50

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 51

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 52

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 53

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 00 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])) ); 54

} 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 . arr2D arr2D[1] arr2D[2] arr2D[3]

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() 55

{ 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”);} 56

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:

57

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) 58

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); }

59

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' a="Hi"

: legal : 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.

60

138)

main() { int i=4,j=7; j = j || i++ && printf("YOU CAN"); printf("%d %d", i, j); } Answer: 41 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:

61

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

62

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),

63

*(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i)); } } Answer: 1 2 3 4 5 6 7 8 9

1 4 7 2 5 8 3 6 9

1 2 3 4 5 6 7 8 9

1 4 7 2 5 8 3 6 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; }

64

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: 11 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: 21 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

65

00000010. So the integer corresponding to it is 00000010 00101100 => 556. 151)

#include <stdio.h> main() { char * str = "hello"; char * ptr = str; char least = 127; while (*ptr++) least = (*ptr
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.month, &student.dob.year);

&student.dob.day,

} 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. 66

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

67

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++
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.

68

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) 69

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

70

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)

71

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;

72

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.

73

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)

74

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.

75

C++ Aptitude and OOPS C++ Aptitude and OOPS Note : All the programs are tested under Turbo C++ 3.0, 4.5 and Microsoft VC++ 6.0 compilers. It is assumed that,  Programs run under Windows environment,  The underlying machine is an x86 based system,  Program is compiled using Turbo C/C++ compiler. The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). 1) class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << endl; } int main() { Sample s1= 10; SomeFunc(s1); s1.PrintVal(); } Answer: 76

Say i am in someFunc Null pointer assignment(Run-time error) Explanation: As the object is passed by value to SomeFunc the destructor of the object is called when the control returns from the function. So when PrintVal is called it meets up with ptr that has been freed.The solution is to pass the Sample object by reference to SomeFunc: void SomeFunc(Sample &x) { cout << "Say i am in someFunc " << endl; } because when we pass objects by refernece that object is not destroyed. while returning from the function. 2) Which is the parameter that is added to every non-static member function when it is called? Answer: ‘this’ pointer 3) class base { public: int bval; base(){ bval=0;} }; class deri:public base { public: int dval; deri(){ dval=1;} }; void SomeFunc(base *arr,int size) { for(int i=0; i<size; i++,arr++) cout<<arr->bval; cout<<endl; } int main() { base BaseArr[5]; SomeFunc(BaseArr,5); deri DeriArr[5]; SomeFunc(DeriArr,5); 77

} Answer: 00000 01010 Explanation: The function SomeFunc expects two arguments.The first one is a pointer to an array of base class objects and the second one is the sizeof the array.The first call of someFunc calls it with an array of bae objects, so it works correctly and prints the bval of all the objects. When Somefunc is called the second time the argument passed is the pointeer to an array of derived class objects and not the array of base class objects. But that is what the function expects to be sent. So the derived class pointer is promoted to base class pointer and the address is sent to the function. SomeFunc() knows nothing about this and just treats the pointer as an array of base class objects. So when arr++ is met, the size of base class object is taken into consideration and is incremented by sizeof(int) bytes for bval (the deri class objects have bval and dval as members and so is of size >= sizeof(int)+sizeof(int) ). 4) class base { public: void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from base Explanation: As we have seen in the previous case, SomeFunc expects a pointer to a base class. Since a pointer to a derived class object is passed, it treats the argument only as a base class pointer and the corresponding base function is called. 78

5) class base { public: virtual void baseFun(){ cout<<"from base"<<endl;} }; class deri:public base { public: void baseFun(){ cout<< "from derived"<<endl;} }; void SomeFunc(base *baseObj) { baseObj->baseFun(); } int main() { base baseObject; SomeFunc(&baseObject); deri deriObject; SomeFunc(&deriObject); } Answer: from base from derived Explanation: Remember that baseFunc is a virtual function. That means that it supports runtime polymorphism. So the function corresponding to the derived class object is called. void main() { int a, *pa, &ra; pa = &a; ra = a; cout <<"a="<
const int size = 5; void print(int *ptr) { cout<
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 <dim1<<" "<dim2<<" "; } /*class fig3d : public fig2d { int dim3; public: fig3d() { dim3=7;} virtual void operator<<(ostream &rhs); }; void fig3d::operator<<(ostream &rhs) { fig2d::operator <<(rhs); rhs<dim3; } */ void main() { fig2d obj1; // fig3d obj2; // } 81

obj1 << cout; obj2 << cout;

/* Answer : 56 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; 82

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<
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="<
out(); } 84

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; } };

85

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, 86

 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-ata-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). 87

 

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 nonobject- 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 88

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; ... }; 89

Array1D operator[] (int index); const Array1D operator[] (int index) const; ... }; The following then becomes legal: Array2Ddata(10,20); ........ cout< :: ?: 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: 90

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 91

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( )) 92

{ 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.

93

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(); smart_pointer(const X& x)

// makes a null pointer // makes pointer to copy of x

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

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 95

ival__3Bar Consider this derivation: class Foo : public Bar { public: int ival; ... } The internal representation of a Foo object is the concatenation of its base and derived class members. // Pseudo C++ code // Internal representation of Foo class Foo { public: int ival__3Bar; int ival__3Foo; ... }; Unambiguous access of either ival members is achieved through name mangling. Member functions, because they can be overloaded, require an extensive mangling to provide each with a unique name. Here the compiler generates the same name for the two overloaded instances(Their argument lists make their instances unique). 39. What are proxy objects? Answer: Objects that points to other objects are called proxy objects or surrogates. Its an object that provides the same interface as its server object but does not have any functionality. During a method invocation, it routes data to the true server object and sends back the return value to the object. 40. Differentiate between declaration and definition in C++. Answer: A declaration introduces a name into the program; a definition provides a unique description of an entity (e.g. type, instance, and function). Declarations can be repeated in a given scope, it introduces a name in a given scope. There must be exactly one definition of every object, function or class used in a C++ program. A declaration is a definition unless:  it declares a function without specifying its body,  it contains an extern specifier and no initializer or function body,  it is the declaration of a static class data member without a class definition,  it is a class name definition,  it is a typedef declaration. A definition is a declaration unless:  it defines a static class data member,  it defines a non-inline member function. 96

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 : 97

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 98

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. 99

 Association: Its' just a semantic connection two classes. e.g.: uses class B class A  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 car

wheels

 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. class B

class A

 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. class A

class B

class C

 Dependency: It is the relationship between dependent and independent classes. Any 100

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? 101

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:

102

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. 103

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.

104

Quantitative Aptitude Quantitative Aptitude Exercise 1 Solve the following and check with the answers given at the end. 1.

It was calculated that 75 men could complete a piece of work in 20 days. When work was scheduled to commence, it was found necessary to send 25 men to another project. How much longer will it take to complete the work?

2.

A student divided a number by 2/3 when he required to multiply by 3/2. Calculate the percentage of error in his result.

3.

A dishonest shopkeeper professes to sell pulses at the cost price, but he uses a false weight of 950gm. for a kg. His gain is …%.

4.

A software engineer has the capability of thinking 100 lines of code in five minutes and can type 100 lines of code in 10 minutes. He takes a break for five minutes after every ten minutes. How many lines of codes will he complete typing after an hour?

5.

A man was engaged on a job for 30 days on the condition that he would get a wage of Rs. 10 for the day he works, but he have to pay a fine of Rs. 2 for each day of his absence. If he gets Rs. 216 at the end, he was absent for work for ... days.

6.

A contractor agreeing to finish a work in 150 days, employed 75 men each working 8 hours daily. After 90 days, only 2/7 of the work was completed. Increasing the number of men by ________ each working now for 10 hours daily, the work can be completed in time.

7.

what is a percent of b divided by b percent of a? (a) a (b) b (c) 1

8.

105

(d)

10

(d)

100

A man bought a horse and a cart. If he sold the horse at 10 % loss and the cart at 20 % gain, he would not lose anything; but if he sold the horse at 5% loss and the cart at 5% gain, he would lose Rs. 10 in the bargain. The amount paid by him was Rs._______ for the horse and Rs.________ for the cart.

9.

A tennis marker is trying to put together a team of four players for a tennis tournament out of seven available. males - a, b and c; females – m, n, o and p. All players are of equal ability and there must be at least two males in the team. For a team of four, all players must be able to play with each other under the following restrictions: b should not play with m, c should not play with p, and a should not play with o. Which of the following statements must be false? 1. b and p cannot be selected together 2. c and o cannot be selected together 3. c and n cannot be selected together. 10-12. The following figure depicts three views of a cube. Based on this, answer questions 10-12. 6

5 1

2

4 22

2

3

6 3

10.

The number on the face opposite to the face carrying 1 is _______ .

11.

The number on the faces adjacent to the face marked 5 are _______ .

12.

Which of the following pairs does not correctly give the numbers on the opposite faces. (1) 6,5 (2) 4,1 (3) 1,3 (4) 4,2

13.

Five farmers have 7, 9, 11, 13 & 14 apple trees, respectively in their orchards. Last year, each of them discovered that every tree in their own orchard bore exactly the same number of apples. Further, if the third farmer gives one apple to the first, and the fifth gives three to each of the second and the fourth, they would all have exactly the same number of apples. What were the yields per tree in the orchards of the third and fourth farmers?

14.

Five boys were climbing a hill. J was following H. R was just ahead of G. K was between G & H. They were climbing up in a column. Who was the second?

15-18 John is undecided which of the four novels to buy. He is considering a spy thriller, a Murder mystery, a Gothic romance and a science fiction novel. The books are written by Rothko, Gorky, Burchfield and Hopper, not necessary in that order, and published by Heron, Piegon, Blueja and sparrow, not necessary in that order. 106

1 2 3 4

(1) The book by Rothko is published by Sparrow. (2) The Spy thriller is published by Heron. (3) The science fiction novel is by Burchfield and is not published by Blueja. (4)The Gothic romance is by Hopper.

15.

Pigeon publishes ____________.

16.

The novel by Gorky ________________.

17.

John purchases books by the authors whose names come first and third in alphabetical order. He does not buy the books ______.

18.

On the basis of the first paragraph and statement (2), (3) and (4) only, it is possible to deduce that 1. Rothko wrote the murder mystery or the spy thriller 2. Sparrow published the murder mystery or the spy thriller 3. The book by Burchfield is published by Sparrow.

19.

If a light flashes every 6 seconds, how many times will it flash in ¾ of an hour?

20.

If point P is on line segment AB, then which of the following is always true? (1) AP = PB (2) AP > PB (3) PB > AP (4) AB > AP (5) AB > AP + PB

21.

All men are vertebrates. Some mammals are vertebrates. Which of the following conclusions drawn from the above statement is correct. All men are mammals All mammals are men Some vertebrates are mammals. None

22.

Which of the following statements drawn from the given statements are correct? Given: All watches sold in that shop are of high standard. Some of the HMT watches are sold in that shop. a) All watches of high standard were manufactured by HMT. b) Some of the HMT watches are of high standard. c) None of the HMT watches is of high standard. d) Some of the HMT watches of high standard are sold in that shop.

23-27. 1. 2. 3. 4. 5. 6. 107

Ashland is north of East Liverpool and west of Coshocton. Bowling green is north of Ashland and west of Fredericktown. Dover is south and east of Ashland. East Liverpool is north of Fredericktown and east of Dover. Fredericktown is north of Dover and west of Ashland. Coshocton is south of Fredericktown and west of Dover.

23.

Which of the towns mentioned is furthest of the north – west (a) Ashland (b) Bowling green (c) Coshocton (d) East Liverpool (e) Fredericktown

24.

Which of the following must be both north and east of Fredericktown? (a) Ashland (b) Coshocton (c) East Liverpool I a only II b only III c only IV a & b Va&c

25.

Which of the following towns must be situated both south and west of at least one other town? A. Ashland only B. Ashland and Fredericktown C. Dover and Fredericktown D. Dover, Coshocton and Fredericktown E. Coshocton, Dover and East Liverpool.

26.

Which of the following statements, if true, would make the information in the numbered statements more specific? (a) Coshocton is north of Dover. (b) East Liverpool is north of Dover (c) Ashland is east of Bowling green. (d) Coshocton is east of Fredericktown (e) Bowling green is north of Fredericktown

27.

Which of the numbered statements gives information that can be deduced from one or more of the other statements? (A) 1 (B) 2 (C) 3 (D) 4 (E) 6

28.

Eight friends Harsha, Fakis, Balaji, Eswar, Dhinesh, Chandra, Geetha, and Ahmed are sitting in a circle facing the center. Balaji is sitting between Geetha and Dhinesh. Harsha is third to the left of Balaji and second to the right of Ahmed. Chandra is sitting between Ahmed and Geetha and Balaji and Eshwar are not sitting opposite to each other. Who is third to the left of Dhinesh?

29.

If every alternative letter starting from B of the English alphabet is written in small letter, rest all are written in capital letters, how the month “ September” be written. (1) SeptEMbEr (2) SEpTeMBEr (3) SeptembeR (4) SepteMber (5) None of the above.

30.

The length of the side of a square is represented by x+2. The length of the side of an equilateral triangle is 2x. If the square and the equilateral triangle have equal perimeter, then the value of x is _______.

108

31.

It takes Mr. Karthik y hours to complete typing a manuscript. After 2 hours, he was called away. What fractional part of the assignment was left incomplete?

32.

Which of the following is larger than 3/5? (1) ½ (2) 39/50 (3) 7/25

(4)

3/10

(5)

59/100

33.

The number that does not have a reciprocal is ____________.

34.

There are 3 persons Sudhir, Arvind, and Gauri. Sudhir lent cars to Arvind and Gauri as many as they had already. After some time Arvind gave as many cars to Sudhir and Gauri as many as they have. After sometime Gauri did the same thing. At the end of this transaction each one of them had 24. Find the cars each originally had.

35.

A man bought a horse and a cart. If he sold the horse at 10 % loss and the cart at 20 % gain, he would not lose anything; but if he sold the horse at 5% loss and the cart at 5% gain, he would lose Rs. 10 in the bargain. The amount paid by him was Rs._______ for the horse and Rs.________ for the cart.

Answers: 1.

Answer: 30 days. Explanation: Before: One day work One man’s one day work Now: No. Of workers One day work

= =

1 / 20 1 / ( 20 * 75)

= =

50 50 * 1 / ( 20 * 75)

The total no. of days required to complete the work = (75 * 20) / 50 = 30 2.

Answer: 0% Explanation: Since 3x / 2 = x / (2 / 3)

3.

Answer: 5.3 % Explanation: He sells 950 grams of pulses and gains 50 grams. If he sells 100 grams of pulses then he will gain (50 / 950) *100 = 5.26

4.

Answer: 250 lines of codes

109

5.

Answer: 7 days Explanation: The equation portraying the given problem is: 10 * x – 2 * (30 – x) = 216 where x is the number of working days. Solving this we get x = 23 Number of days he was absent was 7 (30-23) days.

6.

Answer: 150 men. Explanation: One day’s work One hour’s work One man’s work

= = =

2 / (7 * 90) 2 / (7 * 90 * 8) 2 / (7 * 90 * 8 * 75)

The remaining work (5/7) has to be completed within 60 days, because the total number of days allotted for the project is 150 days. So we get the equation (2 * 10 * x * 60) / (7 * 90 * 8 * 75) = 5/7 where x is the number of men working after the 90th day. We get x = 225 Since we have 75 men already, it is enough to add only 150 men. 7.

Answer: (c) 1 Explanation: a percent of b : (a/100) * b b percent of a : (b/100) * a a percent of b divided by b percent of a : ((a / 100 )*b) / (b/100) * a )) = 1

8.

Answer: Cost price of horse = Rs. 400 & the cost price of cart = 200. Explanation:Let x be the cost price of the horse and y be the cost price of the cart. In the first sale there is no loss or profit. (i.e.) The loss obtained is equal to the gain. Therefore

(10/100) * x

= (20/100) * y

X = 2 * y -----------------(1) In the second sale, he lost Rs. 10. (i.e.) The loss is greater than the profit by Rs. 10. 110

Therefore (5 / 100) * x = (5 / 100) * y + 10 -------(2) Substituting (1) in (2) we get (10 / 100) * y = (5 / 100) * y + 10 (5 / 100) * y = 10 y = 200 From (1) 2 * 200 = x = 400 9.

Answer: 3. Explanation: Since inclusion of any male player will reject a female from the team. Since there should be four member in the team and only three males are available, the girl, n should included in the team always irrespective of others selection.

10.

Answer: 5

11.

Answer: 1,2,3 & 4

12.

Answer: B

13.

Answer: 11 & 9 apples per tree. Explanation: Let a, b, c, d & e be the total number of apples bored per year in A, B, C, D & E ‘s orchard. Given that a + 1 = b + 3 = c – 1 = d + 3 = e – 6 But the question is to find the number of apples bored per tree in C and D ‘s orchard. If is enough to consider c – 1 = d + 3. Since the number of trees in C’s orchard is 11 and that of D’s orchard is 13. Let x and y be the number of apples bored per tree in C & d ‘s orchard respectively. Therefore 11 x – 1 = 13 y + 3 By trial and error method, we get the value for x and y as 11 and 9

14.

Answer: G. Explanation: The order in which they are climbing is R – G – K – H – J

15 – 18 Answer: Novel Name Spy thriller 111

Author Rathko

Publisher Heron

Murder mystery Gothic romance Science fiction

Gorky Burchfield Hopper

Piegon Blueja

Explanation: Given Novel Name Spy thriller Murder mystery Gothic romance Science fiction

Author Rathko Gorky Burchfield Hopper

Publisher Heron Piegon Blueja Sparrow

Sparrow

Since Blueja doesn’t publish the novel by Burchfield and Heron publishes the novel spy thriller, Piegon publishes the novel by Burchfield. Since Hopper writes Gothic romance and Heron publishes the novel spy thriller, Blueja publishes the novel by Hopper. Since Heron publishes the novel spy thriller and Heron publishes the novel by Gorky, Gorky writes Spy thriller and Rathko writes Murder mystery. 19.

Answer: 451 times. Explanation: There are 60 minutes in an hour. In ¾ of an hour there are (60 * ¾) minutes = 45 minutes. In ¾ of an hour there are (60 * 45) seconds = 2700 seconds. Light flashed for every 6 seconds. In 2700 seconds 2700/6 = 450 times. The count start after the first flash, the light will flashes 451 times in ¾ of an hour.

20.

Answer: (4) Explanation: P A B Since p is a point on the line segment AB, AB > AP

21.

Answer: (c)

22.

Answer: (b) & (d).

112

Ahmed 23 - 27.Answer: Fakis 28.

Answer: Fakis Explanation:

Chandra

Harsha

Geetha Eswar

Balaji Dhinesh

29.

Answer: (5). Explanation: Since every alternative letter starting from B of the English alphabet is written in small letter, the letters written in small letter are b, d, f... In the first two answers the letter E is written in both small & capital letters, so they are not the correct answers. But in third and fourth answers the letter is written in small letter instead capital letter, so they are not the answers.

30.

Answer: x=4 Explanation: Since the side of the square is x + 2, its perimeter = 4 (x + 2) = 4x + 8 Since the side of the equilateral triangle is 2x, its perimeter = 3 * 2x = 6x Also, the perimeters of both are equal. (i.e.) 4x + 8 = 6x (i.e.) 2x = 8  x = 4.

31.

Answer: 5 (y – 2) / y. Explanation: To type a manuscript karthik took y hours. Therefore his speed in typing = 1/y. He was called away after 2 hours of typing. Therefore the work completed = 1/y * 2. Therefore the remaining work to be completed = 1 – 2/y. (i.e.) work to be completed = (y-2)/y

32.

Answer: (2)

33.

Answer: 1 Explanation:

113

One is the only number exists without reciprocal because the reciprocal of one is one itself. 34.

Answer: Sudhir had 39 cars, Arvind had 21 cars and Gauri had 12 cars. Explanation: Sudhir Arvind Finally 24 Before Gauri’s transaction 12 Before Arvind’s transaction 6 Before Sudhir’ s transaction 39

35.

24 12 42 21

Gauri 24 48 24 12

Answer: Cost price of horse: Rs. 400 & Cost price of cart: Rs. 200 Explanation: Let x be the cost of horse & y be the cost of the cart. 10 % of loss in selling horse = 20 % of gain in selling the cart Therefore (10 / 100) * x = (20 * 100) * y  x = 2y -----------(1) 5 % of loss in selling the horse is 10 more than the 5 % gain in selling the cart. Therefore (5 / 100) * x - 10 = (5 / 100) * y  5x - 1000 = 5y Substituting (1) 10y - 1000 = 5y 5y = 1000 y = 200 x = 400 from (1)

Exercise 2.1 For the following, find the next term in the series 1. 6, 24, 60,120, 210 a) 336

b) 366

c) 330

d) 660

Answer : a) 336 Explanation : The series is 1.2.3, 2.3.4, 3.4.5, 4.5.6, 5.6.7, ..... 2. 1, 5, 13, 25 Answer : 41 Explanation : The series is of the form 0^2+1^2, 1^2+2^2,... 114

( '.' means product)

3. 0, 5, 8, 17 Answer : 24 Explanation : 1^2-1, 2^2+1, 3^2-1, 4^2+1, 5^2-1 4. 1, 8, 9, 64, 25

(Hint : Every successive terms are related)

Answer : 216 Explanation : 1^2, 2^3, 3^2, 4^3, 5^2, 6^3 5. 8,24,12,36,18,54 Answer : 27 6. 71,76,69,74,67,72 Answer : 67 7. 5,9,16,29,54 Answer : 103 Explanation : 5*2-1=9; 9*2-2=16; 16*2-3=29; 29*2-4=54; 54*2-5=103 8. 1,2,4,10,16,40,64 (Successive terms are related) Answer : 200 Explanation : The series is powers of 2 (2^0,2^1,..). All digits are less than 8. Every second number is in octal number system. 128 should follow 64. 128 base 10 = 200 base 8. Exercise 2.2 Find the odd man out. 1. 3,5,7,12,13,17,19 Answer : 12 Explanation : All but 12 are odd numbers 2. 2,5,10,17,26,37,50,64 Answer : 64 Explanation : 2+3=5; 5+5=10; 10+7=17; 17+9=26; 26+11=37; 37+13=50; 50+15=65; 3. 105,85,60,30,0,-45,-90 Answer : 0 Explanation : 105-20=85; 85-25=60; 60-30=30; 30-35=-5; -5-40=-45; -45-45=-90; Exercise 3 Solve the following. 115

1. What is the number of zeros at the end of the product of the numbers from 1 to 100? Answer : 127 2. A fast typist can type some matter in 2 hours and a slow typist can type the same in 3 hours. If both type combinely, in how much time will they finish? Answer : 1 hr 12 min Explanation : The fast typist's work done in 1 hr = 1/2 The slow typist's work done in 1 hr = 1/3 If they work combinely, work done in 1 hr = 1/2+1/3 = 5/6 So, the work will be completed in 6/5 hours. i.e., 1+1/5 hours = 1hr 12 min 3. Gavaskar's average in his first 50 innings was 50. After the 51st innings, his average was 51. How many runs did he score in his 51st innings. (supposing that he lost his wicket in his 51st innings) Answer : 101 Explanation : Total score after 50 innings = 50*50 = 2500 Total score after 51 innings = 51*51 = 2601 So, runs made in the 51st innings = 2601-2500 = 101 If he had not lost his wicket in his 51st innings, he would have scored an unbeaten 50 in his 51st innings. 4. Out of 80 coins, one is counterfeit. What is the minimum number of weighings needed to find out the counterfeit coin? Answer : 4 5. What can you conclude from the statement : All green are blue, all blue are red. ? (i) some blue are green (ii) some red are green (iii) some green are not red (iv) all red are blue (a) i or ii but not both (b) i & ii only (c) iii or iv but not both (d) iii & iv Answer : (b) 6. A rectangular plate with length 8 inches, breadth 11 inches and thickness 2 inches is available. What is the length of the circular rod with diameter 8 inches and equal to the volume of the rectangular plate? Answer : 3.5 inches Explanation : Volume of the circular rod (cylinder) = Volume of the rectangular plate (22/7)*4*4*h = 8*11*2 h = 7/2 = 3.5 116

7. What is the sum of all numbers between 100 and 1000 which are divisible by 14 ? Answer : 35392 Explanation : The number closest to 100 which is greater than 100 and divisible by 14 is 112, which is the first term of the series which has to be summed. The number closest to 1000 which is less than 1000 and divisible by 14 is 994, which is the last term of the series. 112 + 126 + .... + 994 = 14(8+9+ ... + 71) = 35392 8. If s(a) denotes square root of a, find the value of s(12+s(12+s(12+ ...... upto infinity. Answer : 4 Explanation : Let x = s(12+s(12+s(12+..... We can write x = s(12+x). i.e., x^2 = 12 + x. Solving this quadratic equation, we get x = -3 or x=4. Sum cannot be -ve and hence sum = 4. 9. A cylindrical container has a radius of eight inches with a height of three inches. Compute how many inches should be added to either the radius or height to give the same increase in volume? Answer : 16/3 inches Explanation : Let x be the amount of increase. The volume will increase by the same amount if the radius increased or the height is increased. So, the effect on increasing height is equal to the effect on increasing the radius. i.e., (22/7)*8*8*(3+x) = (22/7)*(8+x)*(8+x)*3 Solving the quadratic equation we get the x = 0 or 16/3. The possible increase would be by 16/3 inches. 10. With just six weights and a balance scale, you can weigh any unit number of kgs from 1 to 364. What could be the six weights? Answer : 1, 3, 9, 27, 81, 243 (All powers of 3) 11. Diophantus passed one sixth of his life in childhood, one twelfth in youth, and one seventh more as a bachelor; five years after his marriage a son was born who died four years before his father at half his final age. How old is Diophantus? Answer : 84 years Explanation : x/6 + x/12 + x/7 + 5 + x/2 + 4 = x 12 . If time at this moment is 9 P.M., what will be the time 23999999992 hours later? Answer : 1 P.M. Explanation : 24 billion hours later, it would be 9 P.M. and 8 hours before that it would be 1 P.M. 13. How big will an angle of one and a half degree look through a glass that magnifies things three times? Answer : 1 1/2 degrees Explanation : The magnifying glass cannot increase the magnitude of an angle.

117

14. Divide 45 into four parts such that when 2 is added to the first part, 2 is subtracted from the second part, 2 is multiplied by the third part and the fourth part is divided by two, all result in the same number. Answer: 8, 12, 5, 20 Explanation: a + b + c + d =45; a+2 = b-2 = 2c = d/2; a=b-4; c = (b-2)/2; d = 2(b-2); b-4 + b + (b-2)/2 + 2(b-2) = 45; 15. I drove 60 km at 30 kmph and then an additional 60 km at 50 kmph. Compute my average speed over my 120 km. Answer : 37 1/2 Explanation : Time reqd for the first 60 km = 120 min.; Time reqd for the second 60 km = 72 min.; Total time reqd = 192 min Avg speed = (60*120)/192 = 37 1/2 Questions 16 and 17 are based on the following : Five executives of European Corporation hold a Conference in Rome Mr. A converses in Spanish & Italian Mr. B, a spaniard, knows English also Mr. C knows English and belongs to Italy Mr. D converses in French and Spanish Mr. E , a native of Italy knows French 16. Which of the following can act as interpreter if Mr. C & Mr. D wish to converse a) only Mr. A b) Only Mr. B c) Mr. A & Mr. B d) Any of the other three Answer : d) Any of the other three. Explanation : From the data given, we can infer the following. A knows Spanish, Italian B knows Spanish, English C knows Italian, English D knows Spanish, French E knows Italian, French To act as an interpreter between C and D, a person has to know one of the combinations Italian&Spanish, Italian&French, English&Spanish, English&French A, B, and E know atleast one of the combinations. 17. If a 6th executive is brought in, to be understood by maximum number of original five he should be fluent in a) English & French b) Italian & Spanish c) English & French d) French & Italian Answer : b) Italian & Spanish Explanation : No of executives who know i) English is 2 ii) Spanish is 3 iii) Italian is 3 118

iv) French is 2 Italian & Spanish are spoken by the maximum no of executives. So, if the 6th executive is fluent in Italian & Spanish, he can communicate with all the original five because everybody knows either Spanish or Italian. 18. What is the sum of the first 25 natural odd numbers? Answer : 625 Explanation : The sum of the first n natural odd nos is square(n). 1+3 = 4 = square(2) 1+3+5 = 9 = square(3) 19. The sum of any seven consecutive numbers is divisible by a) 2 b) 7 c) 3 d) 11 Exercise 3 Try the following. 1. There are seventy clerks working in a company, of which 30 are females. Also, 30 clerks are married; 24 clerks are above 25 years of age; 19 married clerks are above 25 years, of which 7 are males; 12 males are above 25 years of age; and 15 males are married. How many bachelor girls are there and how many of these are above 25? 2. A man sailed off from the North Pole. After covering 2,000 miles in one direction he turned West, sailed 2,000 miles, turned North and sailed ahead another 2,000 miles till he met his friend. How far was he from the North Pole and in what direction? 3. Here is a series of comments on the ages of three persons J, R, S by themselves. S : The difference between R's age and mine is three years. J : R is the youngest. R : Either I am 24 years old or J 25 or S 26. J : All are above 24 years of age. S : I am the eldest if and only if R is not the youngest. R : S is elder to me. J : I am the eldest. R : S is not 27 years old. S : The sum of my age and J's is two more than twice R's age. One of the three had been telling a lie throughout whereas others had spoken the truth. Determine the ages of S,J,R. 4. In a group of five people, what is the probability of finding two persons with the same month of birth? 5. A father and his son go out for a 'walk-and-run' every morning around a track formed by an equilateral triangle. The father's walking speed is 2 mph and his 119

running speed is 5 mph. The son's walking and running speeds are twice that of his father. Both start together from one apex of the triangle, the son going clockwise and the father anti-clockwise. Initially the father runs and the son walks for a certain period of time. Thereafter, as soon as the father starts walking, the son starts running. Both complete the course in 45 minutes. For how long does the father run? Where do the two cross each other? 6. The Director of Medical Services was on his annual visit to the ENT Hospital. While going through the out patients' records he came across the following data for a particular day : " Ear consultations 45; Nose 50; Throat 70; Ear and Nose 30; Nose and Throat 20; Ear and Throat 30; Ear, Nose and Throat 10; Total patients 100." Then he came to the conclusion that the records were bogus. Was he right? 7. Amongst Ram, Sham and Gobind are a doctor, a lawyer and a police officer. They are married to Radha, Gita and Sita (not in order). Each of the wives have a profession. Gobind's wife is an artist. Ram is not married to Gita. The lawyer's wife is a teacher. Radha is married to the police officer. Sita is an expert cook. Who's who? 8. What should come next? 1, 2, 4, 10, 16, 40, 64, Questions 9-12 are based on the following : Three adults – Roberto, Sarah and Vicky – will be traveling in a van with five children – Freddy, Hillary, Jonathan, Lupe, and Marta. The van has a driver’s seat and one passenger seat in the front, and two benches behind the front seats, one beach behind the other. Each bench has room for exactly three people. Everyone must sit in a seat or on a bench, and seating is subject to the following restrictions: An adult must sit on each bench. Either Roberto or Sarah must sit in the driver’s seat. Jonathan must sit immediately beside Marta. 9. Of the following, who can sit in the front passenger seat ? (a) Jonathan (b) Lupe (c) Roberto (d) Sarah (e) Vicky 10. Which of the following groups of three can sit together on a bench? (a) Freddy, Jonathan and Marta (b) Freddy, Jonathan and Vicky (c) Freddy, Sarah and Vicky (d) Hillary, Lupe and Sarah (e) Lupe, Marta and Roberto 11. If Freddy sits immediately beside Vicky, which of the following cannot be true ? a. Jonathan sits immediately beside Sarah b. Lupe sits immediately beside Vicky c. Hillary sits in the front passenger seat d. Freddy sits on the same bench as Hillary 120

e. Hillary sits on the same bench as Roberto 12. If Sarah sits on a bench that is behind where Jonathan is sitting, which of the following must be true ? a. Hillary sits in a seat or on a bench that is in front of where Marta is sitting b. Lupe sits in a seat or on a bench that is in front of where Freddy is sitting c. Freddy sits on the same bench as Hillary d. Lupe sits on the same bench as Sarah e. Marta sits on the same bench as Vicky 13. Make six squares of the same size using twelve match-sticks. (Hint : You will need an adhesive to arrange the required figure) 14. A farmer has two rectangular fields. The larger field has twice the length and 4 times the width of the smaller field. If the smaller field has area K, then the are of the larger field is greater than the area of the smaller field by what amount? (a) 6K (b) 8K (c) 12K (d) 7K 15. Nine equal circles are enclosed in a square whose area is 36sq units. Find the area of each circle. 16. There are 9 cards. Arrange them in a 3*3 matrix. Cards are of 4 colors. They are red, yellow, blue, green. Conditions for arrangement: one red card must be in first row or second row. 2 green cards should be in 3 rd column. Yellow cards must be in the 3 corners only. Two blue cards must be in the 2nd row. At least one green card in each row. 17. Is z less than w? z and w are real numbers. (I) z2 = 25 (II) w = 9 To answer the question, a) Either I or II is sufficient b) Both I and II are sufficient but neither of them is alone sufficient c) I & II are sufficient d) Both are not sufficient 18. A speaks truth 70% of the time; B speaks truth 80% of the time. What is the probability that both are contradicting each other? 19. In a family 7 children don't eat spinach, 6 don't eat carrot, 5 don't eat beans, 4 don't eat spinach & carrots, 3 don't eat carrot & beans, 2 don't eat beans & spinach. One doesn't eat all 3. Find the no. of children. 20. Anna, Bena, Catherina and Diana are at their monthly business meeting. Their occupations are author, biologist, chemist and doctor, but not necessarily in that order. Diana just told the neighbour, who is a biologist that Catherina was on her 121

way with doughnuts. Anna is sitting across from the doctor and next to the chemist. The doctor was thinking that Bena was a good name for parent's to choose, but didn't say anything. What is each person's occupation?

122

UNIX Concepts UNIX Concepts SECTION - I FILE MANAGEMENT IN UNIX 1. How are devices represented in UNIX? All devices are represented by files called special files that are located in/dev directory. Thus, device files and other files are named and accessed in the same way. A 'regular file' is just an ordinary data file in the disk. A 'block special file' represents a device with characteristics similar to a disk (data transfer in terms of blocks). A 'character special file' represents a device with characteristics similar to a keyboard (data transfer is by stream of bits in sequential order). 2. What is 'inode'? All UNIX files have its description stored in a structure called 'inode'. The inode contains info about the file-size, its location, time of last access, time of last modification, permission and so on. Directories are also represented as files and have an associated inode. In addition to descriptions about the file, the inode contains pointers to the data blocks of the file. If the file is large, inode has indirect pointer to a block of pointers to additional data blocks (this further aggregates for larger files). A block is typically 8k. Inode consists of the following fields:  File owner identifier  File type  File access permissions  File access times  Number of links  File size  Location of the file data 3. Brief about the directory representation in UNIX A Unix directory is a file containing a correspondence between filenames and inodes. A directory is a special file that the kernel maintains. Only kernel modifies directories, but processes can read directories. The contents of a directory are a list of filename and inode number pairs. When new directories are created, kernel makes two entries named '.' (refers to the directory itself) and '..' (refers to parent directory). System call for creating directory is mkdir (pathname, mode). 4. What are the Unix system calls for I/O? 123

 open(pathname,flag,mode) - open file  creat(pathname,mode) - create file  close(filedes) - close an open file  read(filedes,buffer,bytes) - read data from an open file  write(filedes,buffer,bytes) - write data to an open file  lseek(filedes,offset,from) - position an open file  dup(filedes) - duplicate an existing file descriptor  dup2(oldfd,newfd) - duplicate to a desired file descriptor  fcntl(filedes,cmd,arg) - change properties of an open file  ioctl(filedes,request,arg) - change the behaviour of an open file The difference between fcntl anf ioctl is that the former is intended for any open file, while the latter is for device-specific operations. 5. How do you change File Access Permissions? Every file has following attributes:  owner's user ID ( 16 bit integer )  owner's group ID ( 16 bit integer )  File access mode word 'r w x -r w x- r w x' (user permission-group permission-others permission) r-read, w-write, x-execute To change the access mode, we use chmod(filename,mode). Example 1: To change mode of myfile to 'rw-rw-r--' (ie. read, write permission for user read,write permission for group - only read permission for others) we give the args as: chmod(myfile,0664) . Each operation is represented by discrete values 'r' is 4 'w' is 2 'x' is 1 Therefore, for 'rw' the value is 6(4+2). Example 2: To change mode of myfile to 'rwxr--r--' we give the args as: chmod(myfile,0744). 6. What are links and symbolic links in UNIX file system? A link is a second name (not a file) for a file. Links can be used to assign more than one name to a file, but cannot be used to assign a directory more than one name or link filenames on different computers. Symbolic link 'is' a file that only contains the name of another file.Operation on the symbolic link is directed to the file pointed by the it.Both the limitations of links are eliminated in symbolic links. Commands for linking files are: Link ln filename1 filename2 Symbolic link ln -s filename1 filename2 124

7. What is a FIFO? FIFO are otherwise called as 'named pipes'. FIFO (first-in-first-out) is a special file which is said to be data transient. Once data is read from named pipe, it cannot be read again. Also, data can be read only in the order written. It is used in interprocess communication where a process writes to one end of the pipe (producer) and the other reads from the other end (consumer). 8. How do you create special files like named pipes and device files? The system call mknod creates special files in the following sequence. 1. kernel assigns new inode, 2. sets the file type to indicate that the file is a pipe, directory or special file, 3. If it is a device file, it makes the other entries like major, minor device numbers. For example: If the device is a disk, major device number refers to the disk controller and minor device number is the disk. 9. Discuss the mount and unmount system calls The privileged mount system call is used to attach a file system to a directory of another file system; the unmount system call detaches a file system. When you mount another file system on to your directory, you are essentially splicing one directory tree onto a branch in another directory tree. The first argument to mount call is the mount point, that is , a directory in the current file naming system. The second argument is the file system to mount to that point. When you insert a cdrom to your unix system's drive, the file system in the cdrom automatically mounts to /dev/cdrom in your system. 10. How does the inode map to data block of a file? Inode has 13 block addresses. The first 10 are direct block addresses of the first 10 data blocks in the file. The 11th address points to a one-level index block. The 12th address points to a two-level (double in-direction) index block. The 13th address points to a three-level(triple in-direction)index block. This provides a very large maximum file size with efficient access to large files, but also small files are accessed directly in one disk read. 11. What is a shell? A shell is an interactive user interface to an operating system services that allows an user to enter commands as character strings or through a graphical user interface. The shell converts them to system calls to the OS or forks off a process to execute the command. System call results and other information from the OS are presented to the user through an interactive interface. Commonly used shells are sh,csh,ks etc. SECTION - II PROCESS MODEL and IPC 1. Brief about the initial process sequence while the system boots up. While booting, special process called the 'swapper' or 'scheduler' is created with 125

Process-ID 0. The swapper manages memory allocation for processes and influences CPU allocation. The swapper inturn creates 3 children:  the process dispatcher,  vhand and  dbflush with IDs 1,2 and 3 respectively. This is done by executing the file /etc/init. Process dispatcher gives birth to the shell. Unix keeps track of all the processes in an internal data structure called the Process Table (listing command is ps -el). 2. What are various IDs associated with a process? Unix identifies each process with a unique integer called ProcessID. The process that executes the request for creation of a process is called the 'parent process' whose PID is 'Parent Process ID'. Every process is associated with a particular user called the 'owner' who has privileges over the process. The identification for the user is 'UserID'. Owner is the user who executes the process. Process also has 'Effective User ID' which determines the access privileges for accessing resources like files. getpid() -process id getppid() -parent process id getuid() -user id geteuid() -effective user id 3. Explain fork() system call. The `fork()' used to create a new process from an existing process. The new process is called the child process, and the existing process is called the parent. We can tell which is which by checking the return value from `fork()'. The parent gets the child's pid returned to him, but the child gets 0 returned to him. 4. Predict the output of the following program code main() { fork(); printf("Hello World!"); } Answer: Hello World!Hello World! Explanation: The fork creates a child that is a duplicate of the parent process. The child begins from the fork().All the statements after the call to fork() will be executed twice.(once by the parent process and other by child). The statement before fork() is executed only by the parent process. 5. Predict the output of the following program code main() { fork(); fork(); fork(); 126

printf("Hello World!"); } Answer: "Hello World" will be printed 8 times. Explanation: 2^n times where n is the number of calls to fork() 6. List the system calls used for process management: System calls Description fork() To create a new process exec() To execute a new program in a process wait() To wait until a created process completes its execution exit() To exit from a process execution getpid() To get a process identifier of the current process getppid() To get parent process identifier nice() To bias the existing priority of a process brk() To increase/decrease the data segment size of a process 7. How can you get/set an environment variable from a program? Getting the value of an environment variable is done by using `getenv()'. Setting the value of an environment variable is done by using `putenv()'. 8. How can a parent and child process communicate? A parent and child can communicate through any of the normal inter-process communication schemes (pipes, sockets, message queues, shared memory), but also have some special ways to communicate that take advantage of their relationship as a parent and child. One of the most obvious is that the parent can get the exit status of the child. 9. What is a zombie? When a program forks and the child finishes before the parent, the kernel still keeps some of its information about the child in case the parent might need it - for example, the parent may need to check the child's exit status. To be able to get this information, the parent calls `wait()'; In the interval between the child terminating and the parent calling `wait()', the child is said to be a `zombie' (If you do `ps', the child will have a `Z' in its status field to indicate this.) 10. What are the process states in Unix? As a process executes it changes state according to its circumstances. Unix processes have the following states: Running : The process is either running or it is ready to run . Waiting : The process is waiting for an event or for a resource. Stopped : The process has been stopped, usually by receiving a signal. Zombie : The process is dead but have not been removed from the process table. 11. What Happens when you execute a program? When you execute a program on your UNIX system, the system creates a special 127

environment for that program. This environment contains everything needed for the system to run the program as if no other program were running on the system. Each process has process context, which is everything that is unique about the state of the program you are currently running. Every time you execute a program the UNIX system does a fork, which performs a series of operations to create a process context and then execute your program in that context. The steps include the following:  Allocate a slot in the process table, a list of currently running programs kept by UNIX.  Assign a unique process identifier (PID) to the process.  iCopy the context of the parent, the process that requested the spawning of the new process.  Return the new PID to the parent process. This enables the parent process to examine or control the process directly. After the fork is complete, UNIX runs your program. 12. What Happens when you execute a command? When you enter 'ls' command to look at the contents of your current working directory, UNIX does a series of things to create an environment for ls and the run it: The shell has UNIX perform a fork. This creates a new process that the shell will use to run the ls program. The shell has UNIX perform an exec of the ls program. This replaces the shell program and data with the program and data for ls and then starts running that new program. The ls program is loaded into the new process context, replacing the text and data of the shell. The ls program performs its task, listing the contents of the current directory. 13. What is a Daemon? A daemon is a process that detaches itself from the terminal and runs, disconnected, in the background, waiting for requests and responding to them. It can also be defined as the background process that does not belong to a terminal session. Many system functions are commonly performed by daemons, including the sendmail daemon, which handles mail, and the NNTP daemon, which handles USENET news. Many other daemons may exist. Some of the most common daemons are:  init: Takes over the basic running of the system when the kernel has finished the boot process.  inetd: Responsible for starting network services that do not have their own standalone daemons. For example, inetd usually takes care of incoming rlogin, telnet, and ftp connections.  cron: Responsible for running repetitive tasks on a regular schedule. 14. What is 'ps' command for? The ps command prints the process status for some or all of the running processes. The information given are the process identification number (PID),the amount of time that the process has taken to execute so far etc. 15. How would you kill a process? The kill command takes the PID as one argument; this identifies which process to 128

terminate. The PID of a process can be got using 'ps' command. 16. What is an advantage of executing a process in background? The most common reason to put a process in the background is to allow you to do something else interactively without waiting for the process to complete. At the end of the command you add the special background symbol, &. This symbol tells your shell to execute the given command in the background. Example: cp *.* ../backup& (cp is for copy) 17. How do you execute one program from within another? The system calls used for low-level process creation are execlp() and execvp(). The execlp call overlays the existing program with the new one , runs that and exits. The original program gets back control only when an error occurs. execlp(path,file_name,arguments..); //last argument must be NULL A variant of execlp called execvp is used when the number of arguments is not known in advance. execvp(path,argument_array); //argument array should be terminated by NULL 18. What is IPC? What are the various schemes available? The term IPC (Inter-Process Communication) describes various ways by which different process running on some operating system communicate between each other. Various schemes available are as follows: Pipes: One-way communication scheme through which different process can communicate. The problem is that the two processes should have a common ancestor (parent-child relationship). However this problem was fixed with the introduction of named-pipes (FIFO). Message Queues : Message queues can be used between related and unrelated processes running on a machine. Shared Memory: This is the fastest of all IPC schemes. The memory to be shared is mapped into the address space of the processes (that are sharing). The speed achieved is attributed to the fact that there is no kernel involvement. But this scheme needs synchronization. Various forms of synchronisation are mutexes, condition-variables, read-write locks, record-locks, and semaphores. SECTION - III MEMORY MANAGEMENT 1. What is the difference between Swapping and Paging? Swapping: 129

Whole process is moved from the swap device to the main memory for execution. Process size must be less than or equal to the available main memory. It is easier to implementation and overhead to the system. Swapping systems does not handle the memory more flexibly as compared to the paging systems. Paging: Only the required memory pages are moved to main memory from the swap device for execution. Process size does not matter. Gives the concept of the virtual memory. It provides greater flexibility in mapping the virtual address space into the physical memory of the machine. Allows more number of processes to fit in the main memory simultaneously. Allows the greater process size than the available physical memory. Demand paging systems handle the memory more flexibly. 2. What is major difference between the Historic Unix and the new BSD release of Unix System V in terms of Memory Management? Historic Unix uses Swapping – entire process is transferred to the main memory from the swap device, whereas the Unix System V uses Demand Paging – only the part of the process is moved to the main memory. Historic Unix uses one Swap Device and Unix System V allow multiple Swap Devices. 3. What is the main goal of the Memory Management?  It decides which process should reside in the main memory,  Manages the parts of the virtual address space of a process which is non-core resident,  Monitors the available main memory and periodically write the processes into the swap device to provide more processes fit in the main memory simultaneously. 4. What is a Map? A Map is an Array, which contains the addresses of the free space in the swap device that are allocatable resources, and the number of the resource units available there. Address

Units

1

10,000

This allows First-Fit allocation of contiguous blocks of a resource. Initially the Map contains one entry – address (block offset from the starting of the swap area) and the total number of resources. Kernel treats each unit of Map as a group of disk blocks. On the allocation and freeing of the resources Kernel updates the Map for accurate information. 5. What scheme does the Kernel in Unix System V follow while choosing a swap device among the multiple swap devices? Kernel follows Round Robin scheme choosing a swap device among the multiple swap devices in Unix System V. 130

6. What is a Region? A Region is a continuous area of a process’s address space (such as text, data and stack). The kernel in a ‘Region Table’ that is local to the process maintains region. Regions are sharable among the process. 7. What are the events done by the Kernel after a process is being swapped out from the main memory? When Kernel swaps the process out of the primary memory, it performs the following:  Kernel decrements the Reference Count of each region of the process. If the reference count becomes zero, swaps the region out of the main memory,  Kernel allocates the space for the swapping process in the swap device,  Kernel locks the other swapping process while the current swapping operation is going on,  The Kernel saves the swap address of the region in the region table. 8. Is the Process before and after the swap are the same? Give reason. Process before swapping is residing in the primary memory in its original form. The regions (text, data and stack) may not be occupied fully by the process, there may be few empty slots in any of the regions and while swapping Kernel do not bother about the empty slots while swapping the process out. After swapping the process resides in the swap (secondary memory) device. The regions swapped out will be present but only the occupied region slots but not the empty slots that were present before assigning. While swapping the process once again into the main memory, the Kernel referring to the Process Memory Map, it assigns the main memory accordingly taking care of the empty slots in the regions. 9. What do you mean by u-area (user area) or u-block? This contains the private data that is manipulated only by the Kernel. This is local to the Process, i.e. each process is allocated a u-area. 10. What are the entities that are swapped out of the main memory while swapping the process out of the main memory? All memory space occupied by the process, process’s u-area, and Kernel stack are swapped out, theoretically. Practically, if the process’s u-area contains the Address Translation Tables for the process then Kernel implementations do not swap the u-area. 11. What is Fork swap? fork() is a system call to create a child process. When the parent process calls fork() system call, the child process is created and if there is short of memory then the child process is sent to the read-to-run state in the swap device, and return to the user state without swapping the parent process. When the memory will be available the child process will be swapped into the main memory. 131

12. What is Expansion swap? At the time when any process requires more memory than it is currently allocated, the Kernel performs Expansion swap. To do this Kernel reserves enough space in the swap device. Then the address translation mapping is adjusted for the new virtual address space but the physical memory is not allocated. At last Kernel swaps the process into the assigned space in the swap device. Later when the Kernel swaps the process into the main memory this assigns memory according to the new address translation mapping. 13. How the Swapper works? The swapper is the only process that swaps the processes. The Swapper operates only in the Kernel mode and it does not uses System calls instead it uses internal Kernel functions for swapping. It is the archetype of all kernel process. 14. What are the processes that are not bothered by the swapper? Give Reason.  Zombie process: They do not take any up physical memory.  Processes locked in memories that are updating the region of the process.  Kernel swaps only the sleeping processes rather than the ‘ready-to-run’ processes, as they have the higher probability of being scheduled than the Sleeping processes. 15. What are the requirements for a swapper to work? The swapper works on the highest scheduling priority. Firstly it will look for any sleeping process, if not found then it will look for the ready-to-run process for swapping. But the major requirement for the swapper to work the ready-to-run process must be core-resident for at least 2 seconds before swapping out. And for swapping in the process must have been resided in the swap device for at least 2 seconds. If the requirement is not satisfied then the swapper will go into the wait state on that event and it is awaken once in a second by the Kernel. 16. What are the criteria for choosing a process for swapping into memory from the swap device? The resident time of the processes in the swap device, the priority of the processes and the amount of time the processes had been swapped out. 17. What are the criteria for choosing a process for swapping out of the memory to the swap device?  The process’s memory resident time,  Priority of the process and  The nice value. 18. What do you mean by nice value? Nice value is the value that controls {increments or decrements} the priority of the process. This value that is returned by the nice () system call. The equation for using nice value is: Priority = (“recent CPU usage”/constant) + (base- priority) + (nice value) 132

Only the administrator can supply the nice value. The nice () system call works for the running process only. Nice value of one process cannot affect the nice value of the other process. 19. What are conditions on which deadlock can occur while swapping the processes?  All processes in the main memory are asleep.  All ‘ready-to-run’ processes are swapped out.  There is no space in the swap device for the new incoming process that are swapped out of the main memory.  There is no space in the main memory for the new incoming process. 20. What are conditions for a machine to support Demand Paging?  Memory architecture must based on Pages,  The machine must support the ‘restartable’ instructions. 21. What is ‘the principle of locality’? It’s the nature of the processes that they refer only to the small subset of the total data space of the process. i.e. the process frequently calls the same subroutines or executes the loop instructions. 22. What is the working set of a process? The set of pages that are referred by the process in the last ‘n’, references, where ‘n’ is called the window of the working set of the process. 23. What is the window of the working set of a process? The window of the working set of a process is the total number in which the process had referred the set of pages in the working set of the process. 24. What is called a page fault? Page fault is referred to the situation when the process addresses a page in the working set of the process but the process fails to locate the page in the working set. And on a page fault the kernel updates the working set by reading the page from the secondary device. 25. What are data structures that are used for Demand Paging? Kernel contains 4 data structures for Demand paging. They are,  Page table entries,  Disk block descriptors,  Page frame data table (pfdata),  Swap-use table. 26.What are the bits that support the demand paging? Valid, Reference, Modify, Copy on write, Age. These bits are the part of the page table entry, which includes physical address of the page and protection bits. 133

Page address

Age Copy on write

Modify Reference

Valid

Protection

27.How the Kernel handles the fork() system call in traditional Unix and in the System V Unix, while swapping? Kernel in traditional Unix, makes the duplicate copy of the parent’s address space and attaches it to the child’s process, while swapping. Kernel in System V Unix, manipulates the region tables, page table, and pfdata table entries, by incrementing the reference count of the region table of shared regions. 28.Difference between the fork() and vfork() system call? During the fork() system call the Kernel makes a copy of the parent process’s address space and attaches it to the child process. But the vfork() system call do not makes any copy of the parent’s address space, so it is faster than the fork() system call. The child process as a result of the vfork() system call executes exec() system call. The child process from vfork() system call executes in the parent’s address space (this can overwrite the parent’s data and stack ) which suspends the parent process until the child process exits. 29.What is BSS(Block Started by Symbol)? A data representation at the machine level, that has initial values when a program starts and tells about how much space the kernel allocates for the un-initialized data. Kernel initializes it to zero at run-time. 30.What is Page-Stealer process? This is the Kernel process that makes rooms for the incoming pages, by swapping the memory pages that are not the part of the working set of a process. Page-Stealer is created by the Kernel at the system initialization and invokes it throughout the lifetime of the system. Kernel locks a region when a process faults on a page in the region, so that page stealer cannot steal the page, which is being faulted in. 31.Name two paging states for a page in memory? The two paging states are:  The page is aging and is not yet eligible for swapping,  The page is eligible for swapping but not yet eligible for reassignment to other virtual address space. 32.What are the phases of swapping a page from the memory?  Page stealer finds the page eligible for swapping and places the page number in the list of pages to be swapped.  Kernel copies the page to a swap device when necessary and clears the valid bit in the page table entry, decrements the pfdata reference count, and places the pfdata table entry at the end of the free list if its reference count is 0. 33.What is page fault? Its types? 134

Page fault refers to the situation of not having a page in the main memory when any process references it. There are two types of page fault :  Validity fault,  Protection fault. 34.In what way the Fault Handlers and the Interrupt handlers are different? Fault handlers are also an interrupt handler with an exception that the interrupt handlers cannot sleep. Fault handlers sleep in the context of the process that caused the memory fault. The fault refers to the running process and no arbitrary processes are put to sleep. 35.What is validity fault? If a process referring a page in the main memory whose valid bit is not set, it results in validity fault. The valid bit is not set for those pages:  that are outside the virtual address space of a process,  that are the part of the virtual address space of the process but no physical address is assigned to it. 36.What does the swapping system do if it identifies the illegal page for swapping? If the disk block descriptor does not contain any record of the faulted page, then this causes the attempted memory reference is invalid and the kernel sends a “Segmentation violation” signal to the offending process. This happens when the swapping system identifies any invalid memory reference. 37.What are states that the page can be in, after causing a page fault?  On a swap device and not in memory,  On the free page list in the main memory,  In an executable file,  Marked “demand zero”,  Marked “demand fill”. 38.In what way the validity fault handler concludes?  It sets the valid bit of the page by clearing the modify bit.  It recalculates the process priority. 39.At what mode the fault handler executes? At the Kernel Mode. 40.What do you mean by the protection fault? Protection fault refers to the process accessing the pages, which do not have the access permission. A process also incur the protection fault when it attempts to write a page whose copy on write bit was set during the fork() system call. 41.How the Kernel handles the copy on write bit of a page, when the bit is set? 135

In situations like, where the copy on write bit of a page is set and that page is shared by more than one process, the Kernel allocates new page and copies the content to the new page and the other processes retain their references to the old page. After copying the Kernel updates the page table entry with the new page number. Then Kernel decrements the reference count of the old pfdata table entry. In cases like, where the copy on write bit is set and no processes are sharing the page, the Kernel allows the physical page to be reused by the processes. By doing so, it clears the copy on write bit and disassociates the page from its disk copy (if one exists), because other process may share the disk copy. Then it removes the pfdata table entry from the page-queue as the new copy of the virtual page is not on the swap device. It decrements the swap-use count for the page and if count drops to 0, frees the swap space. 42.For which kind of fault the page is checked first? The page is first checked for the validity fault, as soon as it is found that the page is invalid (valid bit is clear), the validity fault handler returns immediately, and the process incur the validity page fault. Kernel handles the validity fault and the process will incur the protection fault if any one is present. 43.In what way the protection fault handler concludes? After finishing the execution of the fault handler, it sets the modify and protection bits and clears the copy on write bit. It recalculates the process-priority and checks for signals. 44.How the Kernel handles both the page stealer and the fault handler? The page stealer and the fault handler thrash because of the shortage of the memory. If the sum of the working sets of all processes is greater that the physical memory then the fault handler will usually sleep because it cannot allocate pages for a process. This results in the reduction of the system throughput because Kernel spends too much time in overhead, rearranging the memory in the frantic pace.

136

RDBMS Concepts RDBMS Concepts 1. What is database? A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. 2. What is DBMS? It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. 3. What is a Database system? The database and DBMS software together is called as Database system. 4.     

Advantages of DBMS? Redundancy is controlled. Unauthorised access is restricted. Providing multiple user interfaces. Enforcing integrity constraints. Providing backup and recovery.

5.      

Disadvantage in File Processing System? Data redundancy & inconsistency. Difficult in accessing data. Data isolation. Data integrity. Concurrent access is not possible. Security Problems.

6. Describe the three levels of data abstraction? The are three levels of abstraction:  Physical level: The lowest level of abstraction describes how data are stored.  Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.  View level: The highest level of abstraction describes only part of entire database. 7. Define the "integrity rules" 137

There are two Integrity rules.  Entity Integrity: States that “Primary key cannot have NULL value”  Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation. 8. What is extension and intension? Extension It is the number of tuples present in a table at any instance. This is time dependent. Intension It is a constant value that gives the name, structure of table and the constraints laid on it. 9. What is System R? What are its two major subsystems? System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. Its two subsystems are  Research Storage  System Relational Data System. 10. How is the data structure of System R different from the relational structure? Unlike Relational systems in System R  Domains are not supported  Enforcement of candidate key uniqueness is optional  Enforcement of entity integrity is optional  Referential integrity is not enforced 11. What is Data Independence? Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Two types of Data Independence:  Physical Data Independence: Modification in physical level should not affect the logical level.  Logical Data Independence: Modification in logical level should affect the view level. NOTE: Logical Data Independence is more difficult to achieve 12. What is a view? How it is related to data independence? A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. 138

Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. 13. What is Data Model? A collection of conceptual tools for describing data, data relationships data semantics and constraints. 14. What is E-R model? This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes. 15. What is Object Oriented model? This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes. 16. What is an Entity? It is a 'thing' in the real world with an independent existence. 17. What is an Entity type? It is a collection (set) of entities that have same attributes. 18. What is an Entity set? It is a collection of all entities of particular entity type in the database. 19. What is an Extension of entity type? The collections of entities of a particular entity type are grouped together into an entity set. 20. What is Weak Entity set? An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. 21. What is an attribute? It is a particular property, which describes the entity. 22. What is a Relation Schema and a Relation? A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn). 139

23. What is degree of a Relation? It is the number of attribute of its relation schema. 24. What is Relationship? It is an association among two or more entities. 25. What is Relationship set? The collection (or set) of similar relationships. 26. What is Relationship type? Relationship type defines a set of associations or a relationship set among a given set of entity types. 27. What is degree of Relationship type? It is the number of entity type participating. 25. What is DDL (Data Definition Language)? A data base schema is specifies by a set of definitions expressed by a special language called DDL. 26. What is VDL (View Definition Language)? It specifies user views and their mappings to the conceptual schema. 27. What is SDL (Storage Definition Language)? This language is to specify the internal schema. This language may specify the mapping between two schemas. 28. What is Data Storage - Definition Language? The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language. 29. What is DML (Data Manipulation Language)? This language that enable user to access or manipulate data as organised by appropriate data model.  Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.  Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data. 31. What is DML Compiler? It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand. 32. What is Query evaluation engine? It executes low-level instruction generated by compiler. 140

33. What is DDL Interpreter? It interprets DDL statements and record them in tables containing metadata. 34. What is Record-at-a-time? The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time. 35. What is Set-at-a-time or Set-oriented? The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Setoriented. 36. What is Relational Algebra? It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation. 37. What is Relational Calculus? It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL. 38.How

does Tuple-oriented relational calculus differ from domain-oriented relational calculus The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE. 39. What is normalization? It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties  Minimizing redundancy  Minimizing insertion, deletion and update anomalies. 40. What is Functional Dependency? A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y. 41. When is a functional dependency F said to be minimal?  Every dependency in F has a single attribute for its right hand side.  We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F.  We cannot remove any dependency from F and still have set of dependency that is equivalent to F. 141

42. What is Multivalued dependency? Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following properties  t3[x] = t4[X] = t1[X] = t2[X]  t3[Y] = t1[Y] and t4[Y] = t2[Y]  t3[Z] = t2[Z] and t4[Z] = t1[Z] where [Z = (R-(X U Y)) ] 43. What is Lossless join property? It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition. 44. What is 1 NF (Normal Form)? The domain of attribute must include only atomic (simple, indivisible) values. 45. What is Fully Functional dependency? It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. 46. What is 2NF? A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. 47. What is 3NF? A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true  X is a Super-key of R.  A is a prime attribute of R. In other words, if every non prime attribute is non-transitively dependent on primary key. 48. What is BCNF (Boyce-Codd Normal Form)? A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key. 49. What is 4NF? A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true  X is subset or equal to (or) XY = R.  X is a super key. 50. What is 5NF? 142

A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true  Ri = R for some i.  The join dependency is implied by the set of FD, over R in which the left side is key of R. 51. What is Domain-Key Normal Form? A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. 52. What are partial, alternate,, artificial, compound and natural key? Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys. Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key. Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key. 53. What is indexing and what are the different kinds of indexing? Indexing is a technique for determining how quickly specific data can be found. Types:  Binary search style indexing  B-Tree indexing  Inverted list indexing  Memory resident table  Table indexing 54. What is system catalog or catalog relation? How is better known as? A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary. 55. What is meant by query optimization? The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization. 143

56. What is join dependency and inclusion dependency? Join Dependency: A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a losslessjoin decomposition of R . There is no set of sound and complete inference rules for JD. Inclusion Dependency: An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency. 57. What is durability in DBMS? Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability. 58. What do you mean by atomicity and aggregation? Atomicity: Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions. Aggregation: A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships. 59. What is a Phantom Deadlock? In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts. 60. What is a checkpoint and When does it occur? A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes. 61. What are the different phases of transaction? Different phases are  Analysis phase  Redo Phase  Undo phase 62. What do you mean by flat file database? It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides user-interface management. 144

63. What is "transparent DBMS"? It is one, which keeps its Physical Structure hidden from user. 64. Brief theory of Network, Hierarchical schemas and their properties Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS. 65. What is a query? A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. 66. What do you mean by Correlated subquery? Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery. A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a noncorrelated subquery. E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM) 67. What are the primitive operations common to all record management systems? Addition, deletion and modification. 68. Name the buffer in which all the commands that are typed in are stored ‘Edit’ Buffer 69. What are the unary operations in Relational Algebra? PROJECTION and SELECTION. 70. Are the resulting relations of PRODUCT and JOIN operation the same? No. PRODUCT: Concatenation of every row in one relation with every row in another. JOIN: Concatenation of rows from one relation and related rows from another. 71. What is RDBMS KERNEL? Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, 145

retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures . 72. Name the sub-systems of a RDBMS I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management 73. Which part of the RDBMS takes care of the data dictionary? How Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel. 74. What is the job of the information stored in data-dictionary? The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location. 75. Not only RDBMS takes care of locating data it also determines an optimal access path to store or retrieve the data 76. How do you communicate with an RDBMS? You communicate with an RDBMS using Structured Query Language (SQL) 77. Define SQL and state the differences between SQL and other conventional programming Languages SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 78. Name the three major set of files on disk that compose a database in Oracle There are three major sets of files on disk that compose a database. All the files are binary. These are  Database files  Control files  Redo logs The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself. All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one. 79. What is an Oracle Instance? 146

The Oracle system processes, also known as Oracle background processes, provide functions for the user processes—functions that would otherwise be done by the user processes themselves Oracle database-wide system memory is known as the SGA, the system global area or shared global area. The data and control structures in the SGA are shareable, and all the Oracle background processes and user processes can use them.

The combination of the SGA and the Oracle background processes is known as an Oracle instance 80. What are the four Oracle system processes that must always be up and running for the database to be useable The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor). 81. What are database files, control files and log files. How many of these files should a database have at least? Why? Database Files The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the database. You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the tables and other objects, the number (or location) of the files is immaterial. The database files are fixed in size and never grow bigger than the size at which they were created Control Files The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time you add a new database or redo log file to the database, the information is recorded in the control files. Redo Logs 147

Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs automatically without intervention from the DBA. The redo log files are fixed in size and never grow dynamically from the size at which they were created. 82. What is ROWID? The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted into the database), it never changes until the row is deleted or the table is dropped. The ROWID consists of the following three components, the combination of which uniquely identifies the physical storage location of the row.  Oracle database file number, which contains the block with the rows  Oracle block address, which contains the row  The row within the block (because each block can hold many rows) The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID 83. What is Oracle Block? Can two Oracle Blocks have the same address? Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS software to manage the files and easier to read data into the memory areas. The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow. These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only when the database is first created. Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in different database files. 84. What is database Trigger? A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 85. Name two utilities that Oracle provides, which are use for backup and recovery. Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import. 148

The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed. 86. What are stored-procedures? And what are the advantages of using them. Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. 87. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination. The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller. User-Defined Exceptions PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example: ot_failure EXCEPTION; In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows: EXCEPTION when OT_FAILURE then out_status_code := g_out_status_code; out_msg := g_out_msg; The following is an example of a subprogram exception: EXCEPTION when NO_DATA_FOUND then g_out_status_code := 'FAIL'; RAISE ot_failure; Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all userdefined exceptions. System-Defined Exceptions Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions. 149

PL/SQL internal exceptions. Exception Name CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX INVALID_CURSOR INVALID_NUMBER LOGIN_DENIED NO_DATA_FOUND NOT_LOGGED_ON PROGRAM_ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE TOO_MANY_ROWS TRANSACTION_BACKED_OUT VALUE_ERROR ZERO_DIVIDE

Oracle Error ORA-06511 ORA-00001 ORA-01001 ORA-01722 ORA-01017 ORA-01403 ORA-01012 ORA-06501 ORA-06500 ORA-00051 ORA-01422 ORA-00061 ORA-06502 ORA-01476

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established. 88. Does PL/SQL support "overloading"? Explain The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered. PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference. 89. Tables derived from the ERD a) Are totally unnormalised b) Are always in 1NF c) Can be further denormalised d) May have multi-valued attributes (b) Are always in 1NF 90. Spurious tuples may occur due to i. Bad normalization ii. Theta joins iii. Updating tables from join a) i & ii b) ii & iii 150

c) i & iii

d) ii & iii

(a) i & iii because theta joins are joins made on keys that are not primary keys. 91. A B C is a set of attributes. The functional dependency is as follows AB -> B AC -> C C -> B a) is in 1NF b) is in 2NF c) is in 3NF d) is in BCNF (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF. 92. In mapping of ERD to DFD a) entities in ERD should correspond to an existing entity/store in DFD b) entity in DFD is converted to attributes of an entity in ERD c) relations in ERD has 1 to 1 correspondence to processes in DFD d) relationships in ERD has 1 to 1 correspondence to flows in DFD (a) entities in ERD should correspond to an existing entity/store in DFD 93. A dominant entity is the entity a) on the N side in a 1 : N relationship b) on the 1 side in a 1 : N relationship c) on either side in a 1 : 1 relationship d) nothing to do with 1 : 1 or 1 : N relationship (b) on the 1 side in a 1 : N relationship 94. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER The above is a) Not an error b) Error - the string in single quotes 'NORTH' and 'SOUTH' c) Error - the string should be in double quotes d) Error - ORDER BY clause (d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS 151

95. What is Storage Manager? It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system. 96. What is Buffer Manager? It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory. 97. What is Transaction Manager? It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. 98. What is File Manager? It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk. 99. What is Authorization and Integrity manager? It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data. 100.What are stand-alone procedures? Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution. 101.What are cursors give different types of cursors. PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors  Implicit  Explicit 102.What is cold backup and hot backup (in case of Oracle)?  Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.  Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option. 152

So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination. The database must be running in ARCHIVELOG mode for the hot backup option. If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions. 103.What are Armstrong rules? How do we say that they are complete and/or sound The well-known inference rules for FDs  Reflexive rule : If Y is subset or equal to X then X Y.  Augmentation rule: If X Y then XZ YZ.  Transitive rule: If {X Y, Y Z} then X Z.  Decomposition rule : If X YZ then X Y.  Union or Additive rule: If {X Y, X Z} then X YZ.  Pseudo Transitive rule : If {X Y, WY Z} then WX Z. Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules. 104.How can you find the minimal key of relational schema? Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency. Algo. I Determining X+, closure for X, given set of FDs F 1. Set X+ = X 2. Set Old X+ = X+ 3. For each FD Y Z in F and if Y belongs to X + then add Z + to X 4. Repeat steps 2 and 3 until Old X+ = X+ Algo.II Determining minimal K for relation schema R, given set of FDs F 1. Set K to R that is make K a set of all attributes in R 2. For each attribute A in K 153

a. b.

Compute (K – A)+ with respect to F If (K – A)+ = R then set K = (K – A)+

105.What do you understand by dependency preservation? Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e., ((ΠR1(F)) U … U (ΠRn(F)))+ = F+ if decomposition is not dependency preserving, then some dependency is lost in the decomposition. 106.What is meant by Proactive, Retroactive and Simultaneous Update. Proactive Update: The updates that are applied to database before it becomes effective in real world . Retroactive Update: The updates that are applied to database after it becomes effective in real world . Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world . 107.What are the different types of JOIN operations? Equi Join: This is the most common type of join which involves only equality comparisions. The disadvantage in this type of join is that there

154

SQL SQL 1.Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL) 2.What operator performs pattern matching? LIKE operator 3.What operator tests column for the absence of data? IS NULL operator 4.Which command executes the contents of a specified file? START or @ 5.What is the parameter substitution symbol used with INSERT INTO command? & 6.Which command displays the SQL command in the SQL buffer, and then executes it? RUN 7.What are the wildcards used for pattern matching? _ for single character substitution and % for multi-character substitution 8.State true or false. EXISTS, SOME, ANY are operators in SQL. True 9.State true or false. !=, <>, ^= all denote the same operation. True 10.What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all 11.What command is used to get back the privileges offered by the GRANT command? REVOKE 12.Which system tables contain information on privileges granted and privileges obtained? 155

USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 13.Which system table contains information on constraints on all the tables created? USER_CONSTRAINTS 14.

TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ? Both will result in deleting all the rows in the table EMP. 15.What is the difference between TRUNCATE and DELETE commands? TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE. 16.What command is used to create a table by copying the structure of another table? Answer : CREATE TABLE .. AS SELECT command Explanation : To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following. CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2; If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table. 17.What will be the output of the following query?

SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL; TROUBLETHETROUBLE 18.What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' ); Answer : NO Explanation : The query checks whether a given string is a numerical digit. 19.What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP; This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary. 20.Which date function is used to find the difference between two dates? MONTHS_BETWEEN 156

21.Why does the following command give a compilation error? DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol. 22.What is the advantage of specifying WITH GRANT OPTION in the GRANT command? The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user. 23.What is the use of the DROP option in the ALTER TABLE command? It is used to drop constraints specified on the table. 24.What is the value of ‘comm’ and ‘sal’ after executing the following query if the initial value of ‘sal’ is 10000? UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1; sal = 11000, comm = 1000 25.What is the use of DESC in SQL? Answer : DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order. Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order. 26.What is the use of CASCADE CONSTRAINTS? When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. 27.Which function is used to find the largest integer less than or equal to a specific value? FLOOR 28.What is the output of the following query? SELECT TRUNC(1234.5678,-2) FROM DUAL; 1200

SQL – QUERIES 157

I. SCHEMAS Table 1 : STUDIES PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER) Table 2 : SOFTWARE PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (NUMBER), DCOST (NUMBER), SOLD (NUMBER)

(VARCHAR),

SCOST

Table 3 : PROGRAMMER PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL (NUMBER) LEGEND : PNAME – Programmer Name, SPLACE – Study Place, CCOST – Course Cost, DEVIN – Developed in, SCOST – Software Cost, DCOST – Development Cost, PROF1 – Proficiency 1 QUERIES : 1. Find out the selling cost average for packages developed in Oracle. 2. Display the names, ages and experience of all programmers. 3. Display the names of those who have done the PGDCA course. 4. What is the highest number of copies sold by a package? 5. Display the names and date of birth of all programmers born in April. 6. Display the lowest course fee. 7. How many programmers have done the DCA course. 8. How much revenue has been earned through the sale of packages developed in C. 9. Display the details of software developed by Rakesh. 10. How many programmers studied at Pentafour. 11. Display the details of packages whose sales crossed the 5000 mark. 12. Find out the number of copies which should be sold in order to recover the development cost of each package. 13. Display the details of packages for which the development cost has been recovered. 14. What is the price of costliest software developed in VB? 15. How many packages were developed in Oracle ? 16. How many programmers studied at PRAGATHI? 17. How many programmers paid 10000 to 15000 for the course? 18. What is the average course fee? 19. Display the details of programmers knowing C. 158

20. How many programmers know either C or Pascal? 21. How many programmers don’t know C and C++? 22. How old is the oldest male programmer? 23. What is the average age of female programmers? 24. Calculate the experience in years for each programmer and display along with their names in descending order. 25. Who are the programmers who celebrate their birthdays during the current month? 26. How many female programmers are there? 27. What are the languages known by the male programmers? 28. What is the average salary? 29. How many people draw 5000 to 7500? 30. Display the details of those who don’t know C, C++ or Pascal. 31. Display the costliest package developed by each programmer. 32. Produce the following output for all the male programmers Programmer Mr. Arvind – has 15 years of experience KEYS: 1. SELECT AVG(SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 2. SELECT PNAME,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12) "AGE", TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) "EXPERIENCE" FROM PROGRAMMER; 3. SELECT PNAME FROM STUDIES WHERE COURSE = 'PGDCA'; 4. SELECT MAX(SOLD) FROM SOFTWARE; 5. SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '%APR%'; 6. SELECT MIN(CCOST) FROM STUDIES; 7. SELECT COUNT(*) FROM STUDIES WHERE COURSE = 'DCA'; 8. SELECT SUM(SCOST*SOLD-DCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C'; 9. SELECT * FROM SOFTWARE WHERE PNAME = 'RAKESH'; 10. SELECT * FROM STUDIES WHERE SPLACE = 'PENTAFOUR'; 11. SELECT * FROM SOFTWARE WHERE SCOST*SOLD-DCOST > 5000; 12. SELECT CEIL(DCOST/SCOST) FROM SOFTWARE; 13. SELECT * FROM SOFTWARE WHERE SCOST*SOLD >= DCOST; 14. SELECT MAX(SCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'VB'; 15. SELECT COUNT(*) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 16. SELECT COUNT(*) FROM STUDIES WHERE SPLACE = 'PRAGATHI'; 17. SELECT COUNT(*) FROM STUDIES WHERE CCOST BETWEEN 10000 AND 15000; 18. SELECT AVG(CCOST) FROM STUDIES; 19. SELECT * FROM PROGRAMMER WHERE PROF1 = 'C' OR PROF2 = 'C'; 159

20. SELECT * FROM PROGRAMMER WHERE PROF1 IN ('C','PASCAL') OR PROF2 IN ('C','PASCAL'); 21. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++'); 22. SELECT TRUNC(MAX(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'M'; 23. SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'F'; 24. SELECT PNAME, TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) FROM PROGRAMMER ORDER BY PNAME DESC; 25. SELECT PNAME FROM PROGRAMMER WHERE TO_CHAR(DOB,'MON') = TO_CHAR(SYSDATE,'MON'); 26. SELECT COUNT(*) FROM PROGRAMMER WHERE SEX = 'F'; 27. SELECT DISTINCT(PROF1) FROM PROGRAMMER WHERE SEX = 'M'; 28. SELECT AVG(SAL) FROM PROGRAMMER; 29. SELECT COUNT(*) FROM PROGRAMMER WHERE SAL BETWEEN 5000 AND 7500; 30. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++','PASCAL') AND PROF2 NOT IN ('C','C++','PASCAL'); 31. SELECT PNAME,TITLE,SCOST FROM SOFTWARE WHERE SCOST IN (SELECT MAX(SCOST) FROM SOFTWARE GROUP BY PNAME); 32.SELECT 'Mr.' || PNAME || ' has ' || TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) || ' years of experience' “Programmer” FROM PROGRAMMER WHERE SEX = 'M' UNION SELECT 'Ms.' || PNAME || ' - has ' || TRUNC (MONTHS_BETWEEN (SYSDATE,DOJ)/12) || ' years of experience' “Programmer” FROM PROGRAMMER WHERE SEX = 'F';

II . SCHEMA : Table 1 : DEPT DEPTNO (NOT NULL , NUMBER(2)), DNAME (VARCHAR2(14)), LOC (VARCHAR2(13) Table 2 : EMP EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR2(10)), JOB (VARCHAR2(9)), MGR (NUMBER(4)), HIREDATE (DATE), SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2)) MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key. QUERIES 160

1.List all the employees who have at least one person reporting to them. 2.List the employee details if and only if more than 10 employees are present in department no 10. 3.List the name of the employees with their immediate higher authority. 4.List all the employees who do not manage any one. 5.List the employee details whose salary is greater than the lowest salary of an employee belonging to deptno 20. 6.List the details of the employee earning more than the highest paid manager. 7.List the highest salary paid for each job. 8.Find the most recently hired employee in each department. 9.In which year did most people join the company? Display the year and the number of employees. 10.Which department has the highest annual remuneration bill? 11.Write a query to display a ‘*’ against the row of the most recently hired employee. 12.Write a correlated sub-query to list out the employees who earn more than the average salary of their department. 13.Find the nth maximum salary. 14.Select the duplicate records (Records, which are inserted, that already exist) in the EMP table. 15.Write a query to list the length of service of the employees (of the form n years and m months). KEYS: 1.SELECT DISTINCT(A.ENAME) FROM EMP A, EMP B WHERE A.EMPNO = B.MGR; or SELECT ENAME FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP); 2.SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND DEPTNO=10); 3.SELECT A.ENAME "EMPLOYEE", B.ENAME "REPORTS TO" FROM EMP A, EMP B WHERE A.MGR=B.EMPNO; 4.SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP MINUS SELECT MGR FROM EMP); 5.SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO HAVING DEPTNO=20); 6.SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP GROUP BY JOB HAVING JOB = 'MANAGER' ); 7.SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB; 8.SELECT * FROM EMP WHERE (DEPTNO, HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE) FROM EMP GROUP BY DEPTNO); 9.SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY') HAVING COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO)) FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY')); 161

10.SELECT DEPTNO, LPAD(SUM(12*(SAL+NVL(COMM,0))),15) "COMPENSATION" FROM EMP GROUP BY DEPTNO HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP GROUP BY DEPTNO); 11.SELECT ENAME, HIREDATE, LPAD('*',8) "RECENTLY HIRED" FROM EMP WHERE HIREDATE = (SELECT MAX(HIREDATE) FROM EMP) UNION SELECT ENAME NAME, HIREDATE, LPAD(' ',15) "RECENTLY HIRED" FROM EMP WHERE HIREDATE != (SELECT MAX(HIREDATE) FROM EMP); 12.SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL) FROM EMP F WHERE E.DEPTNO = F.DEPTNO); 13.SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT(SAL)) FROM EMP B WHERE A.SAL<=B.SAL); 14.SELECT * FROM EMP A WHERE A.EMPNO IN (SELECT EMPNO FROM EMP GROUP BY EMPNO HAVING COUNT(EMPNO)>1) AND A.ROWID!=MIN (ROWID)); 15.SELECT ENAME "EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/1 2))||' YEARS '|| TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN (SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE" FROM EMP;

162

Computer Networks Computer Networks 1. What are the two types of transmission technology available? (i) Broadcast and (ii) point-to-point 2. What is subnet? A generic term for section of a large networks usually separated by a bridge or router. 3. Difference between the communication and transmission. Transmission is a physical movement of information and concern issues like bit polarity, synchronisation, clock etc. Communication means the meaning full exchange of information between two communication media. 4. What are the possible ways of data exchange? (i) Simplex (ii) Half-duplex (iii) Full-duplex. 5. What is SAP? Series of interface points that allow other computers to communicate with the other layers of network protocol stack. 6. What do you meant by "triple X" in Networks? The function of PAD (Packet Assembler Disassembler) is described in a document known as X.3. The standard protocol has been defined between the terminal and the PAD, called X.28; another standard protocol exists between hte PAD and the network, called X.29. Together, these three recommendations are often called "triple X" 7. What is frame relay, in which layer it comes? Frame relay is a packet switching technology. It will operate in the data link layer. 8. What is terminal emulation, in which layer it comes? Telnet is also called as terminal emulation. It belongs to application layer. 9. What is Beaconing? The process that allows a network to self-repair networks problems. The stations on the network notify the other stations on the ring when they are not receiving the transmissions. Beaconing is used in Token ring and FDDI networks. 163

10. What is redirector? Redirector is software that intercepts file or prints I/O requests and translates them into network requests. This comes under presentation layer. 11. What is NETBIOS and NETBEUI? NETBIOS is a programming interface that allows I/O requests to be sent to and received from a remote computer and it hides the networking hardware from applications. NETBEUI is NetBIOS extended user interface. A transport protocol designed by microsoft and IBM for the use on small subnets. 12. What is RAID? A method for providing fault tolerance by using multiple hard disk drives. 13. What is passive topology? When the computers on the network simply listen and receive the signal, they are referred to as passive because they don’t amplify the signal in any way. Example for passive topology - linear bus. 14. What is Brouter? Hybrid devices that combine the features of both bridges and routers. 15. What is cladding? A layer of a glass surrounding the center fiber of glass inside a fiber-optic cable. 16. What is point-to-point protocol A communications protocol used to connect computers to remote networking services including Internet service providers. 17. How Gateway is different from Routers? A gateway operates at the upper levels of the OSI model and translates information between two completely different network architectures or data formats 18. What is attenuation? The degeneration of a signal over distance on a network cable is called attenuation. 19. What is MAC address? The address for a device as it is identified at the Media Access Control (MAC) layer in the network architecture. MAC address is usually stored in ROM on the network adapter card and is unique. 20. Difference between bit rate and baud rate. Bit rate is the number of bits transmitted during one second whereas baud rate refers to the number of signal units per second that are required to represent those bits. baud rate = bit rate / N 164

where N is no-of-bits represented by each signal shift. 21. What is Bandwidth? Every line has an upper limit and a lower limit on the frequency of signals it can carry. This limited range is called the bandwidth. 22. What are the types of Transmission media? Signals are usually transmitted over some transmission media that are broadly classified in to two categories. a) Guided Media: These are those that provide a conduit from one device to another that include twisted-pair, coaxial cable and fiber-optic cable. A signal traveling along any of these media is directed and is contained by the physical limits of the medium. Twistedpair and coaxial cable use metallic that accept and transport signals in the form of electrical current. Optical fiber is a glass or plastic cable that accepts and transports signals in the form of light. b) Unguided Media: This is the wireless media that transport electromagnetic waves without using a physical conductor. Signals are broadcast either through air. This is done through radio communication, satellite communication and cellular telephony. 23. What is Project 802? It is a project started by IEEE to set standards to enable intercommunication between equipment from a variety of manufacturers. It is a way for specifying functions of the physical layer, the data link layer and to some extent the network layer to allow for interconnectivity of major LAN protocols. It consists of the following:  802.1 is an internetworking standard for compatibility of different LANs and MANs across protocols.  802.2 Logical link control (LLC) is the upper sublayer of the data link layer which is non-architecture-specific, that is remains the same for all IEEE-defined LANs.  Media access control (MAC) is the lower sublayer of the data link layer that contains some distinct modules each carrying proprietary information specific to the LAN product being used. The modules are Ethernet LAN (802.3), Token ring LAN (802.4), Token bus LAN (802.5).  802.6 is distributed queue dual bus (DQDB) designed to be used in MANs. 24. What is Protocol Data Unit? The data unit in the LLC level is called the protocol data unit (PDU). The PDU contains of four fields a destination service access point (DSAP), a source service access point (SSAP), a control field and an information field. DSAP, SSAP are addresses used by the LLC to identify the protocol stacks on the receiving and sending machines that are generating and using the data. The control field specifies whether the PDU frame is a information frame (I - frame) or a supervisory frame (S - frame) or a unnumbered frame (U - frame). 165

25. What are the different type of networking / internetworking devices? Repeater: Also called a regenerator, it is an electronic device that operates only at physical layer. It receives the signal in the network before it becomes weak, regenerates the original bit pattern and puts the refreshed copy back in to the link. Bridges: These operate both in the physical and data link layers of LANs of same type. They divide a larger network in to smaller segments. They contain logic that allow them to keep the traffic for each segment separate and thus are repeaters that relay a frame only the side of the segment containing the intended recipent and control congestion. Routers: They relay packets among multiple interconnected networks (i.e. LANs of different type). They operate in the physical, data link and network layers. They contain software that enable them to determine which of the several possible paths is the best for a particular transmission. Gateways: They relay packets among networks that have different protocols (e.g. between a LAN and a WAN). They accept a packet formatted for one protocol and convert it to a packet formatted for another protocol before forwarding it. They operate in all seven layers of the OSI model. 26. What is ICMP? ICMP is Internet Control Message Protocol, a network layer protocol of the TCP/IP suite used by hosts and gateways to send notification of datagram problems back to the sender. It uses the echo test / reply to test whether a destination is reachable and responding. It also handles both control and error messages. 27. What are the data units at different layers of the TCP / IP protocol suite? The data unit created at the application layer is called a message, at the transport layer the data unit created is called either a segment or an user datagram, at the network layer the data unit created is called the datagram, at the data link layer the datagram is encapsulated in to a frame and finally transmitted as signals along the transmission media. 28. What is difference between ARP and RARP? The address resolution protocol (ARP) is used to associate the 32 bit IP address with the 48 bit physical address, used by a host or a router to find the physical address of another host on its network by sending a ARP query packet that includes the IP address of the receiver. The reverse address resolution protocol (RARP) allows a host to discover its Internet address when it knows only its physical address. 29. What is the minimum and maximum length of the header in the TCP segment and IP datagram? 166

The header should have a minimum length of 20 bytes and can have a maximum length of 60 bytes. 30. What is the range of addresses in the classes of internet addresses? Class A 0.0.0.0 127.255.255.255 Class B 128.0.0.0 191.255.255.255 Class C 192.0.0.0 223.255.255.255 Class D 224.0.0.0 239.255.255.255 Class E 240.0.0.0 247.255.255.255 31. What is the difference between TFTP and FTP application layer protocols? The Trivial File Transfer Protocol (TFTP) allows a local host to obtain files from a remote host but does not provide reliability or security. It uses the fundamental packet delivery services offered by UDP. The File Transfer Protocol (FTP) is the standard mechanism provided by TCP / IP for copying a file from one host to another. It uses the services offer by TCP and so is reliable and secure. It establishes two connections (virtual circuits) between the hosts, one for data transfer and another for control information. 32. What are major types of networks and explain?  Server-based network  Peer-to-peer network Peer-to-peer network, computers can act as both servers sharing resources and as clients using the resources. Server-based networks provide centralized control of network resources and rely on server computers to provide security and network administration 33. What are the important topologies for networks?  BUS topology: In this each computer is directly connected to primary network cable in a single line. Advantages: Inexpensive, easy to install, simple to understand, easy to extend.  STAR topology: In this all computers are connected using a central hub. Advantages: Can be inexpensive, easy to install and reconfigure and easy to trouble shoot physical problems.  RING topology: In this all computers are connected in loop. Advantages: All computers have equal access to network media, installation can be simple, and signal does not degrade as much as in other topologies because each computer regenerates it. 167

34. What is mesh network? A network in which there are multiple network links between computers to provide multiple paths for data to travel. 35. What is difference between baseband and broadband transmission? In a baseband transmission, the entire bandwidth of the cable is consumed by a single signal. In broadband transmission, signals are sent on multiple frequencies, allowing multiple signals to be sent simultaneously. 36. Explain 5-4-3 rule? In a Ethernet network, between any two points on the network ,there can be no more than five network segments or four repeaters, and of those five segments only three of segments can be populated. 37. What MAU? In token Ring , hub is called Multistation Access Unit(MAU). 38. What is the difference between routable and non- routable protocols? Routable protocols can work with a router and can be used to build large networks. Non-Routable protocols are designed to work on small, local networks and cannot be used with a router 39. Why should you care about the OSI Reference Model? It provides a framework for discussing network operations and design. 40. What is logical link control? One of two sublayers of the data link layer of OSI reference model, as defined by the IEEE 802 standard. This sublayer is responsible for maintaining the link between computers when they are sending data across the physical network connection. 41. What is virtual channel? Virtual channel is normally a connection from one source to one destination, although multicast connections are also permitted. The other name for virtual channel is virtual circuit. 42. What is virtual path? Along any transmission path from a given source to a given destination, a group of virtual circuits can be grouped together into what is called path. 43. What is packet filter? Packet filter is a standard router equipped with some extra functionality. The extra functionality allows every incoming or outgoing packet to be inspected. Packets meeting some criterion are forwarded normally. Those that fail the test are dropped. 44. What is traffic shaping? 168

One of the main causes of congestion is that traffic is often busy. If hosts could be made to transmit at a uniform rate, congestion would be less common. Another open loop method to help manage congestion is forcing the packet to be transmitted at a more predictable rate. This is called traffic shaping. 45. What is multicast routing? Sending a message to a group is called multicasting, and its routing algorithm is called multicast routing. 46. What is region? When hierarchical routing is used, the routers are divided into what we will call regions, with each router knowing all the details about how to route packets to destinations within its own region, but knowing nothing about the internal structure of other regions. 47. What is silly window syndrome? It is a problem that can ruin TCP performance. This problem occurs when data are passed to the sending TCP entity in large blocks, but an interactive application on the receiving side reads 1 byte at a time. 48. What are Digrams and Trigrams? The most common two letter combinations are called as digrams. e.g. th, in, er, re and an. The most common three letter combinations are called as trigrams. e.g. the, ing, and, and ion. 49. Expand IDEA. IDEA stands for International Data Encryption Algorithm. 50. What is wide-mouth frog? Wide-mouth frog is the simplest known key distribution center (KDC) authentication protocol. 51. What is Mail Gateway? It is a system that performs a protocol translation between different electronic mail delivery protocols. 52. What is IGP (Interior Gateway Protocol)? It is any routing protocol used within an autonomous system. 53. What is EGP (Exterior Gateway Protocol)? It is the protocol the routers in neighboring autonomous systems use to identify the set of networks that can be reached within or via each autonomous system. 54. What is autonomous system? It is a collection of routers under the control of a single administrative authority and that uses a common Interior Gateway Protocol. 169

55. What is BGP (Border Gateway Protocol)? It is a protocol used to advertise the set of networks that can be reached with in an autonomous system. BGP enables this information to be shared with the autonomous system. This is newer than EGP (Exterior Gateway Protocol). 56. What is Gateway-to-Gateway protocol? It is a protocol formerly used to exchange routing information between Internet core routers. 57. What is NVT (Network Virtual Terminal)? It is a set of rules defining a very simple virtual terminal interaction. The NVT is used in the start of a Telnet session. 58. What is a Multi-homed Host? It is a host that has a multiple network interfaces and that requires multiple IP addresses is called as a Multi-homed Host. 59. What is Kerberos? It is an authentication service developed at the Massachusetts Institute of Technology. Kerberos uses encryption to prevent intruders from discovering passwords and gaining unauthorized access to files. 60. What is OSPF? It is an Internet routing protocol that scales well, can route traffic along multiple paths, and uses knowledge of an Internet's topology to make accurate routing decisions. 61. What is Proxy ARP? It is using a router to answer ARP requests. This will be done when the originating host believes that a destination is local, when in fact is lies beyond router. 62. What is SLIP (Serial Line Interface Protocol)? It is a very simple protocol used for transmission of IP datagrams across a serial line. 63. What is RIP (Routing Information Protocol)? It is a simple protocol used to exchange information between the routers. 64. What is source route? It is a sequence of IP addresses identifying the route a datagram must follow. A source route may optionally be included in an IP datagram header.

170

Operating Systems Operating Systems Following are a few basic questions that cover the essentials of OS: 1. Explain the concept of Reentrancy. It is a useful, memory-saving technique for multiprogrammed timesharing systems. A Reentrant Procedure is one in which multiple users can share a single copy of a program during the same period. Reentrancy has 2 key aspects: The program code cannot modify itself, and the local data for each user process must be stored separately. Thus, the permanent part is the code, and the temporary part is the pointer back to the calling program and local variables used by that program. Each execution instance is called activation. It executes the code in the permanent part, but has its own copy of local variables/parameters. The temporary part associated with each activation is the activation record. Generally, the activation record is kept on the stack. Note: A reentrant procedure can be interrupted and called by an interrupting program, and still execute correctly on returning to the procedure. 2. Explain Belady's Anomaly. Also called FIFO anomaly. Usually, on increasing the number of frames allocated to a process' virtual memory, the process execution is faster, because fewer page faults occur. Sometimes, the reverse happens, i.e., the execution time increases even when more frames are allocated to the process. This is Belady's Anomaly. This is true for certain page reference patterns. 3. What is a binary semaphore? What is its use? A binary semaphore is one, which takes only 0 and 1 as values. They are used to implement mutual exclusion and synchronize concurrent processes. 4. What is thrashing? It is a phenomenon in virtual memory schemes when the processor spends most of its time swapping pages, rather than executing instructions. This is due to an inordinate number of page faults. 5.   

List the Coffman's conditions that lead to a deadlock. Mutual Exclusion: Only one process may use a critical resource at a time. Hold & Wait: A process may be allocated some resources while waiting for others. No Pre-emption: No resource can be forcible removed from a process holding it.

171

 Circular Wait: A closed chain of processes exist such that each process holds at least one resource needed by another process in the chain. 6. What are short-, long- and medium-term scheduling? Long term scheduler determines which programs are admitted to the system for processing. It controls the degree of multiprogramming. Once admitted, a job becomes a process. Medium term scheduling is part of the swapping function. This relates to processes that are in a blocked or suspended state. They are swapped out of real-memory until they are ready to execute. The swapping-in decision is based on memorymanagement criteria. Short term scheduler, also know as a dispatcher executes most frequently, and makes the finest-grained decision of which process should execute next. This scheduler is invoked whenever an event occurs. It may lead to interruption of one process by preemption. 7. What are turnaround time and response time? Turnaround time is the interval between the submission of a job and its completion. Response time is the interval between submission of a request, and the first response to that request. 8. What are the typical elements of a process image?  User data: Modifiable part of user space. May include program data, user stack area, and programs that may be modified.  User program: The instructions to be executed.  System Stack: Each process has one or more LIFO stacks associated with it. Used to store parameters and calling addresses for procedure and system calls.  Process control Block (PCB): Info needed by the OS to control processes. 9. What is the Translation Lookaside Buffer (TLB)? In a cached system, the base addresses of the last few referenced pages is maintained in registers called the TLB that aids in faster lookup. TLB contains those page-table entries that have been most recently used. Normally, each virtual memory reference causes 2 physical memory accesses-- one to fetch appropriate page-table entry, and one to fetch the desired data. Using TLB in-between, this is reduced to just one physical memory access in cases of TLB-hit. 10. What is the resident set and working set of a process? Resident set is that portion of the process image that is actually in real-memory at a particular instant. Working set is that subset of resident set that is actually needed for execution. (Relate this to the variable-window size method for swapping techniques.) 11. When is a system in safe state?

172

The set of dispatchable processes is in a safe state if there exists at least one temporal order in which all processes can be run to completion without resulting in a deadlock. 12. What is cycle stealing? We encounter cycle stealing in the context of Direct Memory Access (DMA). Either the DMA controller can use the data bus when the CPU does not need it, or it may force the CPU to temporarily suspend operation. The latter technique is called cycle stealing. Note that cycle stealing can be done only at specific break points in an instruction cycle. 13. What is meant by arm-stickiness? If one or a few processes have a high access rate to data on one track of a storage disk, then they may monopolize the device by repeated requests to that track. This generally happens with most common device scheduling algorithms (LIFO, SSTF, CSCAN, etc). High-density multisurface disks are more likely to be affected by this than low density ones. 14. What are the stipulations of C2 level security? C2 level security provides for:  Discretionary Access Control  Identification and Authentication  Auditing  Resource reuse 15. What is busy waiting? The repeated execution of a loop of code while waiting for an event to occur is called busy-waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion. 16. Explain the popular multiprocessor thread-scheduling strategies.  Load Sharing: Processes are not assigned to a particular processor. A global queue of threads is maintained. Each processor, when idle, selects a thread from this queue. Note that load balancing refers to a scheme where work is allocated to processors on a more permanent basis.  Gang Scheduling: A set of related threads is scheduled to run on a set of processors at the same time, on a 1-to-1 basis. Closely related threads / processes may be scheduled this way to reduce synchronization blocking, and minimize process switching. Group scheduling predated this strategy.  Dedicated processor assignment: Provides implicit scheduling defined by assignment of threads to processors. For the duration of program execution, each program is allocated a set of processors equal in number to the number of threads in the program. Processors are chosen from the available pool.  Dynamic scheduling: The number of thread in a program can be altered during the course of execution. 173

17. When does the condition 'rendezvous' arise? In message passing, it is the condition in which, both, the sender and receiver are blocked until the message is delivered. 18. What is a trap and trapdoor? Trapdoor is a secret undocumented entry point into a program used to grant access without normal methods of access authentication. A trap is a software interrupt, usually the result of an error condition. 19. What are local and global page replacements? Local replacement means that an incoming page is brought in only to the relevant process' address space. Global replacement policy allows any page frame from any process to be replaced. The latter is applicable to variable partitions model only. 20. Define latency, transfer and seek time with respect to disk I/O. Seek time is the time required to move the disk arm to the required track. Rotational delay or latency is the time it takes for the beginning of the required sector to reach the head. Sum of seek time (if any) and latency is the access time. Time taken to actually transfer a span of data is transfer time. 21. Describe the Buddy system of memory allocation. Free memory is maintained in linked lists, each of equal sized blocks. Any such block is of size 2^k. When some memory is required by a process, the block size of next higher order is chosen, and broken into two. Note that the two such pieces differ in address only in their kth bit. Such pieces are called buddies. When any used block is freed, the OS checks to see if its buddy is also free. If so, it is rejoined, and put into the original free-block linked-list. 22. What is time-stamping? It is a technique proposed by Lamport, used to order events in a distributed system without the use of clocks. This scheme is intended to order events consisting of the transmission of messages. Each system 'i' in the network maintains a counter Ci. Every time a system transmits a message, it increments its counter by 1 and attaches the time-stamp Ti to the message. When a message is received, the receiving system 'j' sets its counter Cj to 1 more than the maximum of its current value and the incoming timestamp Ti. At each site, the ordering of messages is determined by the following rules: For messages x from site i and y from site j, x precedes y if one of the following conditions holds....(a) if Ti
174

24. In the context of memory management, what are placement and replacement algorithms? Placement algorithms determine where in available real-memory to load a program. Common methods are first-fit, next-fit, best-fit. Replacement algorithms are used when memory is full, and one process (or part of a process) needs to be swapped out to accommodate a new program. The replacement algorithm determines which are the partitions to be swapped out. 25. In loading programs into memory, what is the difference between load-time dynamic linking and run-time dynamic linking? For load-time dynamic linking: Load module to be loaded is read into memory. Any reference to a target external module causes that module to be loaded and the references are updated to a relative address from the start base address of the application module. With run-time dynamic loading: Some of the linking is postponed until actual reference during execution. Then the correct module is loaded and linked. 26. What are demand- and pre-paging? With demand paging, a page is brought into memory only when a location on that page is actually referenced during execution. With pre-paging, pages other than the one demanded by a page fault are brought in. The selection of such pages is done based on common access patterns, especially for secondary memory devices. 27. Paging a memory management function, while multiprogramming a processor management function, are the two interdependent? Yes. 28. What is page cannibalizing? Page swapping or page replacements are called page cannibalizing. 29. What has triggered the need for multitasking in PCs?  Increased speed and memory capacity of microprocessors together with the support fir virtual memory and  Growth of client server computing 30. What are the four layers that Windows NT have in order to achieve independence?  Hardware abstraction layer  Kernel  Subsystems  System Services. 31. What is SMP? To achieve maximum efficiency and reliability a mode of operation known as symmetric multiprocessing is used. In essence, with SMP any process or threads can be assigned to any processor. 175

32. What are the key object oriented concepts used by Windows NT?  Encapsulation  Object class and instance 33. Is Windows NT a full blown object oriented operating system? Give reasons. No Windows NT is not so, because its not implemented in object oriented language and the data structures reside within one executive component and are not represented as objects and it does not support object oriented capabilities . 34. What is a drawback of MVT? It does not have the features like  ability to support multiple processors  virtual storage  source level debugging 35. What is process spawning? When the OS at the explicit request of another process creates a process, this action is called process spawning. 36. How many jobs can be run concurrently on MVT? 15 jobs 37. List out some reasons for process termination.  Normal completion  Time limit exceeded  Memory unavailable  Bounds violation  Protection error  Arithmetic error  Time overrun  I/O failure  Invalid instruction  Privileged instruction  Data misuse  Operator or OS intervention  Parent termination. 38. What are the reasons for process suspension?  swapping  interactive user request  timing  parent process request 39. What is process migration? It is the transfer of sufficient amount of the state of process from one machine to 176

the target machine 40. What is mutant? In Windows NT a mutant provides kernel mode or user mode mutual exclusion with the notion of ownership. 41. What is an idle thread? The special thread a dispatcher will execute when no ready thread is found. 42. What is FtDisk? It is a fault tolerance disk driver for Windows NT. 43. What are the possible threads a thread can have?  Ready  Standby  Running  Waiting  Transition  Terminated. 44. What are rings in Windows NT? Windows NT uses protection mechanism called rings provides by the process to implement separation between the user mode and kernel mode. 45. What is Executive in Windows NT? In Windows NT, executive refers to the operating system code that runs in kernel mode. 46. What are the sub-components of I/O manager in Windows NT?  Network redirector/ Server  Cache manager.  File systems  Network driver  Device driver 47. What are DDks? Name an operating system that includes this feature. DDks are device driver kits, which are equivalent to SDKs for writing device drivers. Windows NT includes DDks. 48. What level of security does Windows NT meets? C2 level security.

177

178

Visual Basic 6.0 1. How long have you programmed in VB and how would you rate yourself (1-10)? 2. What does the statement DIM bManager as ... tell you? Declaring Variables To declare a variable is to tell the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable: Dim variablename [As type] Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a variable in a procedure is local to that procedure — that is, you can't access a variable in one procedure from another procedure. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes. 3. What is the difference between Exec and ExecSQL? (wouldnt this be dependent on data access? Ie ADO use different method than DAO) Executes a system procedure, a user-defined stored procedure, or an extended stored procedure. Also supports the execution of a character string within a Transact-SQL batch. 4.What must the last statement in an exception handler be? Statement Description Resume [0] Program execution resumes with the statement that caused the error or the most recently executed call out of the procedure containing the error-handling routine. Use it to repeat an operation after correcting the condition that caused the error. Resume Next Resumes program execution at the statement immediately following the one that caused the error. If the error occurred outside the procedure that contains the error handler, execution resumes at the statement immediately following the call to the 179

procedure wherein the error occurred, if the called procedure does not have an enabled error handler. Resume line Resumes program execution at the label specified by line, where line is a line label (or nonzero line number) that must be in the same procedure as the error handler. Err.Raise Number:= number Triggers a run-time error. When this statement is executed within the error-handling routine, Visual Basic searches the calls list for another error-handling routine. (The calls list is the chain of procedures invoked to arrive at the current point of execution. See the section, "Error-Handling Hierarchy," later in this chapter.) 5. What is the difference between a property a method and an event? Give an example of each. 1. Text1.color ------ is a property (Mostly to change the appearance ) 2. Text1.text ------- is Method (Mostly to set values which r not graphical) 3. button 1. Click -- is event (Event is the result of user interaction with application) 6. What is a variant data type and when would you use it? Variant will store all the different possible VB data received at one place 7. Why is it not good to use a variant data type? Using variant rather than a specific data type is slower because of conversions needed and takes up more memory because additional over head 8. What is the difference between a Dynaset and Snapshot and how would you create one? (we dont use snapshot in VB5+) A dynaset-type Recordset object is a dynamic set of records that can contain fields from one or more tables or queries in a database and may be updatable. In an ODBCDirect database, a dynaset-type Recordset object corresponds to an ODBC keyset cursor. Remarks A dynaset-type Recordset object is a type of Recordset object you can use to manipulate data in an underlying database table or tables. It differs from a snapshot-type Recordset object because the dynaset stores only the primary key for each record, instead of actual data. As a result, a dynaset is updated with changes made to the source data, while the snapshot is not. Like the table-type Recordset object, a dynaset retrieves the full record only when it's needed for editing or display purposes. A snapshot-type Recordset object is a static set of records that you can use to examine data in an underlying table or tables. In an ODBCDirect database, a snapshot-type Recordset object corresponds to a static cursor. Remarks 180

To create a snapshot-type Recordset object, use the OpenRecordset method on an open database, on another dynaset- or snapshot-type Recordset object, or on a QueryDef object. 10.How would you define and use a Boolean in VB? (Integer in VB3 Boolean in VB6+) Dim [Private][Public] x as Boolean Default is false 11. What is the difference between Dim nCount as Integer vs Dim nCount% and when would you use each? No difference 12.What is the difference between and <Shift-F8> when debugging? F8- will take u through all the executable statements <SHIFT> f8 – will skip the calls to subroutines 13.What is the statement to extract 4 characters from the middle of a string? Mid(string, start [, length] ) 14. What is the error message that you would get if you try to assign "Null" to an integer variable? Invalid use if null 16. What is "Option Explicit"? It mandates the programmer to declare the variables before using 17. What other options are there is VB? Option private Option compare text,binary Option base 0,1 18. What is the difference between Single and Double in VB? Single: can hold numbers that r approximations Accuracy up to 7 digits only Double : can hold up to 300 digits with 16 plcess of accuracy 19. How do you clear the current selected item from a drop down combo box? Combo1.Remove Item(Combo1.ListIndex) 22.What is the difference between early binding and late binding? Early-Bound Declarations Early binding allows you to declare an object variable as a programmatic identifier, or class name, rather than as an Object or a Variant data type. The programmatic identifier of an application is stored in the Windows registry as a subkey below the \HKEY_CLASSES_ROOT subtree. For example, the programmatic identifier for Access is "Access.Application"; for Excel it is "Excel.Application." When you are using early binding, you can initialize the object variable by using the CreateObject or GetObject function or by using the New keyword if the application supports it. All Office 2000 applications can be initialized by using the New keyword. Because 181

the Outlook 2000 programming environment for Outlook items supports only scripting, you can't use early binding declarations of any sort in its VBScript programming environment; however, you can use early binding in VBA code in a local Outlook VBA project or COM add-in, or in Automation code that works with Outlook from another host application. Early binding is the friendly name for what C programmers call virtual function table binding, or vtable binding. In order to use early binding, the host application must establish a reference to a type library (.tlb) or an object library (.olb), or an .exe, .dll, or .ocx file that contains type information about the objects, methods, properties, and events of the application or service you want to automate. In the following code fragment, an Application variable is declared by using the programmatic identifier for Word (Word.Application) and a new instance of Word is created by using the Set statement with the New keyword: Dim wdApp As Word.Application Set wdApp = New Word.Application If the code following these lines doesn't set the Application object's Visible property to True, the new instance of Word will be hidden. All Office applications are hidden by default when they are automated from another application. Use early binding whenever possible. Early binding has the following advantages: Syntax checking When you use early binding, VBA checks the syntax of your statements against the syntax stored in the object library during compilation rather than checking it at run time, so that you can catch and address errors at design time. For example, VBA can determine if you are using valid properties or methods of an object, and if you are passing valid arguments to those properties and methods. Support for statement-building tools When you use early binding, the Visual Basic Editor supports features that make writing code much easier and less prone to errors, such as automatic listing of an object's properties and methods, and pop-up tips for named arguments. Support for built-in constants When you use early binding, your code can refer to the built-in constants for method arguments and property settings because this information is available from the type library at design time. If you use late binding, you must define these constants in your code by looking up the values in the application's documentation. Better performance Performance is significantly faster with early binding than with late binding. Late-Bound Declarations Late binding allows you to declare a variable as an Object or a Variant data type. The variable is initialized by calling the GetObject or CreateObject 182

function and specifying the application's programmatic identifier. For example, in the following code fragment, an Object variable is declared and then set to an instance of Access by using the CreateObject function: Dim objApp As Object Set objApp = CreateObject("Access.Application") Late binding is the friendly name for what C programmers used to call IDispatch binding, and was the first method of binding implemented in applications that can control other applications through Automation. For this reason, you can use late binding to maintain backward compatibility with older applications. However, late binding uses a lot of overhead; it is faster than dynamic data exchange (DDE), but slower than early binding. Tip DDE is a protocol that was established before OLE for exchanging data between Windows applications. There is no need to use DDE to exchange data between Office applications because of their support for Automation. However, you may have to use DDE from some other application that doesn't support Automation code in order to work with data from an Office application. For more information about using DDE, search the Visual Basic Reference Help for the Office application you want to work with. The CreateObject function must also be used to work with objects from any Automation component from script. This is because scripting has no method of establishing references to type libraries to support early binding.

23 .Difference between ByRef and ByVal? Only a copy of a variable is passed when an argument is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. Use the ByVal keyword to indicate an argument passed by value. For example: Sub PostAccounts(ByVal intAcctNum as Integer) . . ' Place statements here. . End Sub Passing Arguments By Reference Passing arguments by reference gives the procedure access to the actual variable contents in its memory address location. As a result, the variable's value can be permanently changed by the procedure to which it is passed. Passing by reference is the default in Visual Basic. If you specify a data type for an argument passed by reference, you must pass a value of that type for the argument. You can work around this by passing an expression, rather than a data type, for an argument. 183

Visual Basic evaluates an expression and passes it as the required type if it can. The simplest way to turn a variable into an expression is to enclose it in parentheses. For example, to pass a variable declared as an integer to a procedure expecting a string as an argument, you would do the following: Sub CallingProcedure() Dim intX As Integer intX = 12 * 3 Foo(intX) End Sub Sub Foo(Bar As String) MsgBox Bar 'The value of Bar is the string "36". End Sub Using Optional Arguments You can specify arguments to a procedure as optional by placing the Optional keyword in the argument list. If you specify an optional argument, all subsequent arguments in the argument list must also be optional and declared with the Optional keyword. The two pieces of sample code below assume there is a form with a command button and list box. For example, this code provides all optional arguments: Dim strName As String Dim strAddress As String Sub ListText(Optional x As String, Optional y _ As String) List1.AddItem x List1.AddItem y End Sub Private Sub Command1_Click() strName = "yourname" strAddress = 12345 ' Both arguments are provided. Call ListText(strName, strAddress) End Sub This code, however, does not provide all optional arguments: Dim strName As String Dim varAddress As Variant Sub ListText(x As String, Optional y As Variant) List1.AddItem x If Not IsMissing(y) Then List1.AddItem y End If End Sub Private Sub Command1_Click() strName = "yourname" ' Second argument is not ' provided. Call ListText(strName) End Sub 184

In the case where an optional argument is not provided, the argument is actually assigned as a variant with the value of Empty. The example above shows how to test for missing optional arguments using the IsMissing function. Providing a Default for an Optional Argument It's also possible to specify a default value for an optional argument. The following example returns a default value if the optional argument isn't passed to the function procedure: Sub ListText(x As String, Optional y As _ Integer = 12345) List1.AddItem x List1.AddItem y End Sub Private Sub Command1_Click() strName = "yourname" ' Second argument is not ' provided. Call ListText(strName) ' Adds "yourname" and ' "12345". End Sub Using an Indefinite Number of Arguments Generally, the number of arguments in the procedure call must be the same as in the procedure specification. Using the ParamArray keyword allows you to specify that a procedure will accept an arbitrary number of arguments. This allows you to write functions like Sum: Dim x As Integer Dim y As Integer Dim intSum As Integer Sub Sum(ParamArray intNums()) For Each x In intNums y = y + x Next x intSum = y End Sub Private Sub Command1_Click() Sum 1, 3, 5, 7, 8 List1.AddItem intSum End Sub Creating Simpler Statements with Named Arguments For many built-in functions, statements, and methods, Visual Basic provides the option of using named arguments as a shortcut for typing argument values. With named arguments, you can provide any or all of the arguments, in any order, by assigning a value to the named argument. You do this by typing the argument name plus a colon followed by an equal sign and the value ( MyArgument:= "SomeValue") and placing that assignment in any sequence delimited by commas. Notice that the arguments in the following example are in the reverse order of the expected arguments: Function ListText(strName As String, Optional 185

strAddress As String) List1.AddItem strName List2.AddItem strAddress End Sub Private Sub Command1_Click() ListText strAddress:=”12345”, strName:="Your Name" End Sub This is especially useful if your procedures have several optional arguments that you do not always need to specify. Determining Support for Named Arguments To determine which functions, statements, and methods support named arguments, use the AutoQuickInfo feature in the Code window, check the Object Browser, or see the Language Reference. Consider the following when working with named arguments: · Named arguments are not supported by methods on objects in the Visual Basic (VB) object library. They are supported by all language keywords in the Visual Basic for applications (VBA) object library. · In syntax, named arguments are shown as bold and italic. All other arguments are shown in italic only. Important You cannot use named arguments to avoid entering required arguments. You can omit only the optional arguments. For Visual Basic (VB) and Visual Basic for applications (VBA) object libraries, the Object Browser encloses optional arguments with square brackets [ ]. For More Information See "ByVal," "ByRef," "Optional," and "ParamArray" in the Language Reference

22. How does VB Pass arguments to a function by default? By Ref 23. Can a subroutine pass back values? How? Yes By passing the values BYREF 24. What does Addressof operator do? Using the AddressOf Keyword Any code you write to call a function pointer from Visual Basic must be placed in a standard .BAS module — you can't put the code in a class module or attach it to a form. When you call a declared function using the AddressOf keyword, you should be aware of the following conditions: · AddressOf can only be used immediately preceding an argument in an argument list; that argument can be the name of a user-defined sub, function, or property. · The sub, function, or property you call with AddressOf must be in the same project as the related declarations and procedures. · You can only use AddressOf with user-defined subs, functions, or properties — you cannot use it with external functions declared with the Declare 186

statement, or with functions referenced from type libraries. · You can pass a function pointer to an argument that is typed As Any or As Long in a declared Sub, Function, or user-defined type definition. Note You can create your own call-back function prototypes in DLLs compiled with Visual C++ (or similar tools). To work with AddressOf, your prototype must use the __stdcall calling convention. The default calling convention (_cdecl) will not work with AddressOf

25. What is the difference between a Sub and a Function? Sub won’t return values Fuction return values

26. How will you retain the values of existing elements in a dynamic array when you want to alter the array size? Redim with preserve keyword 27. How will you define a function to accept variable number of arguments ? USING PARAMARRAY 28. How will you define a function to accept optional arguments? Using optional key word 29. How does the following statements work? On Error Goto Err_Handler control switches to err handler 30. How does the following statements work? On Error Resume Next control switches to next executable statement 31 .How does the following statements work? On Error Goto 0 ---control switches to same statement again 32 .What will happen if you issue a Resume statement after handling an error? control switches to same statement again 34. Sequence of events when a form is loaded in VB? Load .Active, Paint 36.Difference between Modal and Modaless forms? Visual Basic Concepts How Modal and Modeless Forms Behave Out of Process As mentioned in "Showing Forms from the CoffeeManager Class," modal and modeless forms displayed by an out-of-process component have a different relationship to a client application’s forms than they would if 187

displayed by an in-process component. Running CoffeeWatch will demonstrate this. Note This topic is part of a series that walks you through creating a sample ActiveX EXE. It begins with the topic Creating an ActiveX EXE Component. To demonstrate modal and modeless form behavior with the out-of-process Coffee component 1. Press F5 to run the CoffeeWatch test program. 2. Click Show Modal Form to display a modal form from the Coffee component. Depending on your system configuration, the order programs were started, and so on, the modal form may come up in front of CoffeeWatch — or you may see something like this: 3. TestForm is not really modal with respect to the CoffeeWatch form. To see this, click anywhere on the CoffeeWatch form. The Component Request Pending dialog box appears, as shown here: The dialog box appears because CoffeeWatch is waiting on its call to CoffeeMonitor.ShowForm, which is waiting on the modal TestForm. However, if TestForm were truly modal with respect to Form1, clicking on Form1 would generate a system sound indicating that Form1 was disabled. 4. Click Switch To, to bring TestForm to the front. Note Depending on your system configuration and the order in which programs are loaded, the copy of Visual Basic in which Coffee is running may come to the front along with TestForm, obscuring CoffeeWatch. 5. Click on CoffeeWatch again, to bring it to the front and display the Component Request Pending dialog box again. Note If you can’t see CoffeeWatch (the form, not the project), use the task bar (or press ALT+TAB) to bring it to the front. In the strict sense of the word, TestForm is modal to CoffeeWatch. That is, you can’t do anything with CoffeeWatch until TestForm is dismissed. However, because the two forms are in different processes, CoffeeWatch can appear on top of TestForm. 6. Click Switch To, to bring TestForm to the front, and then click TestForm’s close box to dismiss the modal form. 7. Click Show Modeless Form to show TestForm as a modeless form. TestForm behaves like a modeless form that’s not owned by CoffeeWatch. That is, it doesn’t stay on top of CoffeeWatch. You can verify this by clicking on each of the two forms, to bring them alternately to the front. Important Because TestForm is in a different process from CoffeeWatch, you cannot make CoffeeWatch the owner of TestForm as you would if the forms were in the same process — that is, by passing a reference to CoffeeWatch in the OwnerForm argument of TestForm. For details see "Displaying Forms from Code Components," in Chapter 8, "Building Code Components."For details 188

see "Displaying Forms from Code Components," in "Building Code Components." 8. DO NOT dismiss the modeless TestForm. Instead, close CoffeeWatch by clicking its close box. TestForm doesn’t close. (It may be hidden behind the instance of Visual Basic containing the CoffeeWatch project — use the task bar or ALT+TAB to bring it to the front.) This illustrates two important points: First, a form displayed by an out-of-process component is not dependent on the client application. Nor is its lifetime limited by the client’s lifetime. Second, a loaded form can keep an out-of-process component’s executable from unloading. For details, see "Starting and Ending a Component" in Chapter 6, "General Principles of Component Design."For details, see "Starting and Ending a Component" in "General Principles of Component Design." In its Terminate event, CoffeeMonitor should unload any forms it has shown. 9. Dismiss TestForm by clicking its close box. The Coffee component remains in run mode. To return Coffee to design mode, click the End button, or select End from the Run menu. Once you put an ActiveX EXE project in run mode, it remains in run mode. This is convenient for testing, but it’s different from the behavior of the made .exe. The executable for an out-of-process component unloads when the last client releases its last reference to an object provided by the component, as discussed in "Starting and Ending a Component." Note The only way to test the shutdown behavior of an out-of-process component is to test with the made executable. The lesson to take away from all this is that out-of-process code components are generally not the best way to show forms. Step by Step This topic is part of a series that walks you through creating a sample ActiveX EXE. To See Go to the next step Providing an Asynchronous Notification Event Start from the beginning Creating an ActiveX EXE Component

Send feedback to MSDN. Look here for MSDN Online resources.

189

37. What are the different cursor types that create using ADO Recordset? Difference between these cursor types? Visual Basic Concepts ADO, DAO and RDO in Visual Basic

can we

In Visual Basic, three data access interfaces are available to you: ActiveX Data Objects (ADO), Remote Data Objects (RDO), and Data Access Objects (DAO). A data access interface is an object model that represents various facets of accessing data. Using Visual Basic, you can programmatically control the connection, statement builders, and returned data for use in any application. Why are there three data access interfaces in Visual Basic? Data access technology is constantly evolving, and each of the three interfaces represent a different state of the art. The latest is ADO, which features a simpler — yet more flexible — object model than either RDO or DAO. For new projects, you should use ADO as your data access interface. Why Use ADO? ADO is designed as an easy-to-use application level interface to Microsoft's newest and most powerful data access paradigm, OLE DB. OLE DB provides high-performance access to any data source, including relational and non-relational databases, email and file systems, text and graphics, custom business objects, and more. ADO is implemented for minimal network traffic in key Internet scenarios, and a minimal number of layers between the front-end and data source — all to provide a lightweight, high-performance interface. ADO is called using a familiar metaphor — the OLE Automation interface. And ADO uses conventions and features similar to DAO and RDO, with simplified semantics that make it easy to learn. For a brief overview, see OLE DB Providers. For detailed information about ADO, see Getting Started with ADO. DAO and RDO For backward compatibility, Visual Basic continues to support DAO and RDO for existing projects. For More Information For more information on RDO programming, see Using Remote Data Objects and the RemoteData Control. For information on DAO programming, see Using Data Access Objects with Remote Databases. Complete DAO reference can also be found at Microsoft DAO 3.6. Upgrading from RDO to ADO Consider upgrading if you decide ADO offers benefits your RDO-based application can use. See ADO Compared with RDO and DAO for a discussion of the differences among the platforms and for guidance on changing an RDO-based project to an ADO project. See Converting from RDO 2.0 to ADO 2.0 for upgrade guidance. Send feedback to MSDN. Look here for MSDN Online 190

resources. ADO Cursor Library The ActiveX Data Objects (ADO) cursor provider, part of the Remote Data Service (RDS) technology, provides several types of cursors as shown in the following table. Cursor type Constant Forward-only cursor adOpenForwardOnly Keyset-driven cursor adOpenKeyset Dynamic cursor adOpenDynamic Static cursor adOpenStatic You can control how the data source and the chosen ADO cursor library manage concurrency with the locking options in the following table. Locking type Constant Pessimistic concurrency. adLockPessimistic Optimistic concurrency using row values. adLockOptimistic Read-only. Changes are not permitted. adLockReadOnly All updates are deferred until the batch update is finished. To do batch updating, you should select either a keyset or static cursor. adLockBatchOptimistic For More Information For more information on ADO cursor options, search online for "CursorType Property" in MSDN Library Visual Studio 6.0. For more information on Remote Data Service (RDS) and how it provides cursor support with ActiveX Data Objects, search online for "Remote Data Service Developer's Guide" and "Understanding Remote Data Service Applications" in MSDN Library Visual Studio 6.0. For more information on using locks to handle multiuser concurrency situations, see Managing Concurrency with Cursor Locks in this chapter. Send feedback to MSDN. Look here for MSDN Online resources.

39. What is the difference between a ActiveX DLL and a ActiveX EXE? ActivexDLL is executes in in process ActivexExe executes in outprocess 40. What are the types of Instancing property that can be set for a Class in a ActiveX DLL and ActiveX EXE? Visual Basic Concepts Instancing for Classes Provided by ActiveX Components The value of the Instancing property determines 191

whether your class is private — that is, for use only within your component — or available for other applications to use. As its name suggests, the Instancing property also determines how other applications create instances of the class. The property values have the following meanings. · Private means that other applications aren’t allowed access to type library information about the class, and cannot create instances of it. Private objects are only for use within your component. · PublicNotCreatable means that other applications can use objects of this class only if your component creates the objects first. Other applications cannot use the CreateObject function or the New operator to create objects from the class. · MultiUse allows other applications to create objects from the class. One instance of your component can provide any number of objects created in this fashion. An out-of-process component can supply multiple objects to multiple clients; an in-process component can supply multiple objects to the client and to any other components in its process. · GlobalMultiUse is like MultiUse, with one addition: properties and methods of the class can be invoked as if they were simply global functions. It’s not necessary to explicitly create an instance of the class first, because one will automatically be created. · SingleUse allows other applications to create objects from the class, but every object of this class that a client creates starts a new instance of your component. Not allowed in ActiveX DLL projects. · GlobalSingleUse is like SingleUse, except that properties and methods of the class can be invoked as if they were simply global functions. Not allowed in ActiveX DLL projects. Class Modules and Project Types The value of the Instancing property is restricted in certain project types. Allowed values are shown in the following table: Instancing Value ActiveX EXE ActiveX DLL ActiveX Control Private Yes Yes Yes PublicNotCreatable Yes Yes Yes MultiUse Yes Yes GlobalMultiUse Yes Yes SingleUse Yes GlobalSingleUse Yes Dependent Objects (PublicNotCreatable) The value of the Instancing property determines the part an object plays in your component’s object model, as discussed in "Organizing Objects: The Object Model." If the Instancing property of a class is 192

PublicNotCreatable, objects of that class are called dependent objects. Dependent objects are typically parts of more complex objects. For example, you might allow a client application to create multiple Library objects, but you might want Book objects to exist only as parts of a Library. You can make the Book class PublicNotCreatable, and let the user add new books to a Library object by giving the Library class a Books collection with an Add method that creates new books only within the collection. Your component can support as many dependent objects as necessary. You can write code in the Add method of a collection class to limit the number of objects in the collection, or you can allow the number to be limited by available memory. For More Information Dependent objects are discussed in detail in "Dependent Objects," later in this chapter. Externally Creatable Objects All values of the Instancing property besides PublicNotCreatable and Private define externally creatable objects — that is, objects that clients can create using the New operator or the CreateObject function. MultiUse vs. SingleUse In ActiveX DLLs, Instancing for an externally creatable class will most commonly be MultiUse. This setting allows an in-process component to supply any number of instances of the class to the client executable, and to any other in-process component. For ActiveX EXEs, the Instancing values SingleUse and MultiUse define very different behaviors for a class. MultiUse makes the most efficient use of memory, because it allows one instance of your component to provide multiple objects to multiple client applications without duplication of resources or global data. For example, suppose the SmallMechanicals component provides a Widget class, and the Instancing property of the class is set to MultiUse. If one client application creates two Widget objects, or if two client applications each create a Widget object, all the Widgets will be supplied from one instance of your component. If the Instancing property of the Widget class is set to SingleUse, the result of both scenarios above is that a separate copy of your component will be loaded into memory for each Widget created. The uses and limitations of this behavior are discussed in Chapter 8, "Building Code Components," and in Appendix A, "ActiveX Component Standards and Guidelines."The uses and limitations of this behavior are discussed in "Building Code Components," and in "ActiveX Component Standards and Guidelines." MultiUse and Multithreading If your component is an ActiveX EXE marked for 193

unattended execution (that is, it has no user interaction whatever), and the Instancing property of the Widget class is set to MultiUse, the result of both scenarios above is that two Widget objects are created in same copy of SmallMechanicals, each on its own thread of execution. Apartment Model threading is used, meaning that each thread is like an apartment, and objects in different apartments are unaware of each other’s existence. This is accomplished by giving each Widget its own copy of the SmallMechanicals component’s global data. For More Information The use of multithreading or SingleUse instancing to avoid blocked execution is discussed in Chapter 8, "Building Code Components."The use of multithreading or SingleUse instancing to avoid blocked execution is discussed in "Building Code Components." Global Objects Frequently it’s useful to have utility functions that users of your component can employ without first creating an instance of one of your objects. In out-of-process components, such functions are frequently implemented as properties or methods of the Application object. If the Instancing property for a class is marked GlobalMultiUse or GlobalSingleUse, then properties and methods of the class can be invoked without explicitly creating an instance of the object. For example, suppose you want your SmallMechanicals component to provide a GlobalUtility object whose methods are general-purpose functions. You can add a class module to the SmallMechanicals project, set the Name property to GlobalUtility, and set the Instancing property to GlobalMultiUse. Now you can add properties and methods to the class module. For example, you might implement a ReversePolarity method and a read-only WidgetCount property: Public Sub ReversePolarity() ' (Code to reverse polarity on all Widgets.) End Sub In the client application, the ReversePolarity method can be invoked without first creating a GlobalUtility object: Private Sub Command1_Click() ' No object variable is required. ReversePolarity End Sub Note The properties and methods of a GlobalMultiUse object are not part of the global name space of the component that provides the object. For example, within a project that contains the GlobalUtility class, you must explicitly create an instance of GlobalUtility in order to use the object's properties and methods. Other limitations of global objects are listed in "Global Objects and Code Libraries," in Chapter 8, "Building Code Components."Other 194

limitations of global objects are listed in "Global Objects and Code Libraries," in "Building Code Components." Be careful when choosing names for the properties and methods of global objects. Using common or obvious names may result in name collisions with other components. Name conflicts must be resolved by qualifying the property or method with the type library name: Private Sub Command1_Click() SmallMechanicals.ReversePolarity Esalen.ReversePolarity End Sub Important The "global" in global objects refers to the fact that all of the object’s properties and methods are available in the global name space of your project. It does not mean that one object is automatically shared by all clients. Each client that uses your component gets its own global object. For More Information "Providing Named Constants for Your Component," later in this chapter, discusses the use of global objects to provide string constants and non-integer constants. Code components are discussed in depth in Chapter 8, "Building Code Components."Code components are discussed in depth in "Building Code Components." Send feedback to MSDN. Look here for MSDN Online resources.

41. What are the different levels of compatibilty that can be set for a ActiveX component in VB and what do they imply? Visual Basic Concepts Levels of Binary Version Compatibility Visual Basic defines three levels of version compatibility for the interfaces you describe in your class modules. · Version identical means that the interfaces are all the same, so the new version of the type library is exactly the same as the old one. The code inside methods or Property procedures may have been changed or enhanced, but this is transparent to client applications. · Version compatible means that objects and/or methods have been added to the type library, but no changes were made to existing properties or methods. Both old and new client applications can use the component. · Version incompatible means that at least one property or method that existed in the old type library has been changed or removed. Existing client applications that have references to the component cannot use the new version. Version-Identical Interfaces 195

Once your component has been distributed as part of an application, there are several situations that might cause you to release an update. You might want to optimize the performance of a method that had turned out to be a bottleneck for users. You might also need to change the internal implementation of an object’s method to reflect changes in the business rule on which the method was based. You can change the code in existing Property procedures or methods, and still have a version-identical interface, as long as you do not change the names or data types of their parameters, the order of the parameters, the name of the property or method, or the data type of the return value. When you create the executable for a version-identical upgrade, you can use the same file name for the executable. Visual Basic uses the same version number for the type library. Important When you release a new version of your component with a version-identical or version-compatible interface, and retain the same file name for the executable, you should always use the Make tab of the Project Properties dialog box to increment the file version number. This ensures that the setup programs for applications that use your component will replace old versions during setup. Version-Compatible Interfaces When you enhance your component by adding new classes, or new properties and methods to existing classes, you can continue to use the same name for your executable. As long as you make no changes to existing properties and methods, Visual Basic updates the version number of the type library but keeps it compatible with the old version number. Client applications that are built using the new version of your component will compile with the new version number, and can make use of all the new features. They cannot be used with earlier versions of your component, however, because type library versions are only upward-compatible. As with version-identical releases, remember to increment the file version number of the executable. Version-Incompatible Interfaces Sometimes design decisions made in an earlier version of a component fail to anticipate future needs. If you want the code in the component to be useful in new development projects, you have to change the interface. For example, the CupsPerAnnum parameter of the Coffee method might be implemented as an Integer in the first version of a component. It may become apparent, after the component has been in use for some time, that some clients need to pass a larger value than can be contained in an Integer. Changing the declaration of a method is only one of several actions that will cause Visual Basic to make the version number of the type library incompatible, 196

rendering the new version unusable with client applications compiled with earlier versions. The following changes will cause a version incompatibility: · Changing the Project Name field on the General tab of the Project Properties dialog box. · Changing the Name property of any class module whose Public property is True (controls), or whose Instancing property is not Private (class modules). · Deleting a public class module, or setting its Instancing property to Private. · Deleting a public variable, procedure, or Property procedure from a public class module or control, or changing it to Private or Friend. · Changing the name or data type of a public variable, procedure, or Property procedure in a public class module or control. · Changing the names, data types, or order of the parameters of a public procedure or Property procedure in a public class module or control. · Changing the Procedure ID (DispID) or other parameters in the Procedure Attributes dialog box. Time to Take Stock When you’ve identified a necessary change that will cause your component to be incompatible with earlier versions, it’s a good idea to take the time to evaluate the entire set of interfaces, before plunging ahead and creating an incompatible version of your component. Consider Multiple Interfaces Remember that there are alternatives to using Version Compatibility. Consider enhancing your component by adding new interfaces with the Implements statement, as described in "Providing Polymorphism by Implementing Interfaces," in Chapter 6, "General Principles of Component Design."Consider enhancing your component by adding new interfaces with the Implements statement, as described in "Providing Polymorphism by Implementing Interfaces" in "General Principles of Component Design." Multiple interfaces, a key feature of the Component Object Model (COM) — on which the ActiveX specification is based — provide a more flexible way to enhance software components. They allow you to evolve your systems over time, without breaking existing components. You don’t have to tackle the daunting task factoring your existing class module interfaces into small interfaces more suitable for use with Implements — one of the benefits of using multiple interfaces is that you can start small, adding new interfaces to the system only where new functionality is required. Going Ahead with Incompatibility If you decide to go ahead with an incompatible version, you can minimize future problems for the users of your component by concentrating in one release all the changes you can anticipate that might 197

break compatibility again if they have to be made in later releases. In planning for an incompatible change, treat the project as a fresh start. Devote as much care to planning as you would if you were creating a brand new component. Creating an incompatible version requires three steps: changing the project name, changing the file name, and compiling with No Compatibility selected. Changing the Project Name The key change you must make, when you need to distribute an incompatible version of your component, is the project name. The project name, which is set on the General tab of the Project Properties dialog box, is the first part of the programmatic ID of each class your component provides. For example, the SmallMechanicals component might provide a Widgets class. A client application would create a variable to contain a reference to a Widget object as follows: Private wdgDriver As SmallMechanicals.Widget The programmatic ID is the combination of project name and class name, and it must be unique. If you create a new version of this component, you might give it the project name SmallMechanicals200. Both versions of the Widget object could then be registered in the same Windows Registry without confusion. Changing the File Name You must change the file name of an incompatible component. If you use the old file name without incrementing the file version number, the incompatible component may not install on computers where the old file exists. If you increment the file version, the new file will over-write the old, and applications that used the old version will fail. Compiling with No Compatibility Before you compile the incompatible component for the first time, open the Project Properties dialog box (accessible from the Project menu), select the Component tab, then select No Compatibility in the Version Compatibility box. Do not omit this step. Compiling with No Compatibility ensures that the new executable will not contain any GUIDs (for example, class IDs or interface IDs) that belong to the previous version. This is necessary for applications that use the original version to continue working correctly. Tip After compiling once with No Compatibility, switch to Project Compatibility to simplify your development tasks. Alternatives to Version-Incompatible Changes If you prefer not to make the change to multiple interfaces, as described above, you can take a similar approach with classes. That is, you can avoid changes that cause version incompatibility by adding new objects, properties, and methods, instead of changing existing ones. Existing 198

applications continue using the old methods and objects, while developers of new applications can use the new objects. For example, you might discover that to take advantage of enhancements to your General Ledger system, you need to add a SubAccount parameter to several business rules in your FinanceRules component. If each rule is implemented as a method of the GL object, you could avoid creating an incompatible version of the component by adding a new object named GL97. This object would have the same methods as the GL object, but with a SubAccount parameter where appropriate. If you need to add new versions of existing methods to an object, you can give the new methods the same name with a version or sequence number added — for example, ‘Execute2.’ This approach is not as flexible or efficient as implementing multiple interfaces. You may end up replicating entire classes, and class interfaces may become large and unwieldy — for example, you might find yourself using a Query class with an Execute method, an Execute2 method, an Execute3 method, and so on. However, it’s a step in the right direction. For More Information "Providing a Reference Point for Binary Version Compatibility" describes when and how to specify a version of your component as a reference point for version compatibility. See "Version Compatibility" for a list of topics related to this feature. Software evolution using multiple interfaces is discussed in "Providing Polymorphism by Implementing Interfaces," in Chapter 6, "General Principles of Component Design."Software evolution using multiple interfaces is discussed in "Providing Polymorphism by Implementing Interfaces," in "General Principles of Component Design." Send feedback to MSDN. Look here for MSDN Online resources. Version Compatibility in ActiveX Components A component can be part of another application because it provides Automation interfaces that the other application can manipulate. Each public class module has a default interface that includes all the properties and methods you added to the class module, plus any secondary interfaces implemented using the Implements feature. Once your component has been used in an application — or, in the case of ActiveX controls, embedded in a document or on a Web page — you can change its interfaces only at the risk of breaking the client application. Suppose, for example, that the Spin method of your Widget object has one argument, Speed. If you distribute a new version of your component, in which you redefine the Spin method so that it also requires 199

a Direction argument, you could cause run-time errors in existing applications. At the same time, a successful component will inevitably spark requests for enhancements. You will want to provide new objects, or add new properties and methods to existing objects. Occasionally you will even want to change the arguments of existing methods of existing objects. The following topics describe the Version Compatibility feature of Visual Basic, which is designed to allow components to be enhanced without causing existing applications to fail. · When Should I Use Version Compatibility? Describes the Version Compatibility options and when to use them. Describes an alternative technique for enhancing software components. · Maintaining Binary Compatibility Describes the versioning system Visual Basic uses to prevent compatibility problems. · Levels of Binary Version Compatibility Describes the degrees of binary compatibility Visual Basic measures. · Providing a Reference Point for Binary Version Compatibility Describes when and how to specify a version of your component as a reference point for version compatibility. · Using Binary Version Compatibility Describes when and how to use the feature, problems you may encounter, and messages you may get from Visual Basic. For More Information See "Polymorphism, Interfaces, Type Libraries, and GUIDs," in Chapter 6, "General Principles of Component Design" for background information and concepts.See "Polymorphism, Interfaces, Type Libraries, and GUIDs" in "General Principles of Component Design" for background information and concepts.

42. What does DoEvents do? Although Timer events are the best tool for background processing, particularly for very long tasks, the DoEvents function provides a convenient way to allow a task to be canceled. For example, the following code shows a "Process" button that changes to a "Cancel" button when it is clicked. Clicking it again interrupts the task it is performing (go through MSDN) 43. will you use WithEvents? Handling an Object's Events An object that raises events is called an event 200

source. To handle the events raised by an event source, you can declare a variable of the object's class using the WithEvents keyword. This topic continues the Widget object example begun in "Declaring and Raising Events." To handle the PercentDone event of a Widget, place the following code in the Declarations section of Form1: To handle the PercentDone event of a Widget, place the following code in the Declarations section of Form1: Option Explicit Private WithEvents mWidget As Widget Private mblnCancel As Boolean The WithEvents keyword specifies that the variable mWidget will be used to handle an object's events. You specify the kind of object by supplying the name of the class from which the object will be created. The variable mWidget is declared in the Declarations section of Form1 because WithEvents variables must be module-level variables. This is true regardless of the type of module you place them in. The variable mblnCancel will be used to cancel the LongTask method. Limitations on WithEvents Variables You should be aware of the following limitations on the use of WithEvents variables: · A WithEvents variable cannot be a generic object variable. That is, you cannot declare it As Object — you must specify the class name when you declare the variable. · You cannot declare a WithEvents variable As New. The event source object must be explicitly created and assigned to the WithEvents variable. · You cannot declare WithEvents variables in a standard module. You can declare them only in class modules, form modules, and other modules that define classes. · You cannot create arrays of WithEvents variables. Writing Code to Handle an Event As soon as you declare a variable WithEvents, the variable name appears in the left-hand drop down of the module's code window. When you select mWidget, the Widget class's events will appear in the right-hand drop down, as shown in Figure 9.9. Figure 9.9 An event associated with a WithEvents variable Selecting an event will display the corresponding event procedure, with the prefix mWidget_. All the event procedures associated with a WithEvents variable will have the variable name as a prefix. Add the following code to the mWidget_PercentDone event procedure. Private Sub mWidget_PercentDone(ByVal Percent As _ Single, Cancel As Boolean) lblPercentDone.Caption = CInt(100 * Percent) & "%" DoEvents If mblnCancel Then Cancel = True End Sub 201

Whenever the PercentDone event is raised, the event procedure displays the percent complete in a Label control. The DoEvents statement allows the label to repaint, and also gives the user the opportunity to click the Cancel button. Add the following code for the Click event of the button whose caption is Cancel. Private Sub Command2_Click() mblnCancel = True End Sub If the user clicks the Cancel button while LongTask is running, the Command2_Click event will be executed as soon as the DoEvents statement allows event processing to occur. The module-level variable mblnCancel is set to True, and the mWidget_PercentDone event then tests it and sets the ByRef Cancel argument to True. Connecting a WithEvents Variable to an Object Form1 is all set up to handle a Widget object's events. All that remains is to find a Widget somewhere. When you declare a variable WithEvents at design time, there is no object associated with it. A WithEvents variable is just like any other object variable. You have to create an object and assign a reference to the object to the WithEvents variable. Add the following code to the Form_Load event procedure to create the Widget. Private Sub Form_Load() Set mWidget = New Widget End Sub When the code above is executed, Visual Basic creates a Widget and connects its events to the event procedures associated with mWidget. From that point on, whenever the Widget raises its PercentDone event, the mWidget_PercentDone event procedure will be executed. To call the LongTask method, add the following code to the Click event of the button whose caption is Start Task. ' Start Task button. Private Sub Command1_Click() mblnCancel = False lblPercentDone.Caption = "0%" lblPercentDone.Refresh Call mWidget.LongTask(14.4, 0.66) If Not mblnCancel Then lblPercentDone.Caption = 100 End Sub Before the LongTask method is called, the label that displays the percent complete must be initialized, and the module-level Boolean flag for canceling the method must be set to False. LongTask is called with a task duration of 14.4 seconds. The PercentDone event is to be raised once every two-thirds of a second. Each time the event is raised, the mWidget_PercentDone event procedure will be executed. 202

When LongTask is done, mblnCancel is tested to see if LongTask ended normally, or if it stopped because mblnCancel was set to True. The percent complete is updated only for the former case. Running the Program Press F5 to put the project in Run mode. Click the Start Task button. Each time the PercentDone event is raised, the label is updated with the percentage of the task that's complete. Click the Cancel button to stop the task. Notice that the appearance of the Cancel button doesn't change immediately when you click it. The Click event can't happen until the DoEvents statement allows event processing. You may find it instructive to run the program with F8, and step through the code a line at a time. You can clearly see how execution enters LongTask, and then re-enters Form1 briefly each time the PercentDone event is raised. What would happen if, while execution was back in Form1's code, the LongTask method was called again? Confusion, chaos, and eventually (if it happened every time the event was raised) a stack overflow. Handling Events for a Different Widget You can cause the variable mWidget to handle events for a different Widget object by assigning a reference to the new Widget to mWidget. In fact, you can make the code in Command1 do this every time you click the button, by adding two lines of code: Set mWidget = New Widget '<- New line. Call mWidget.LongTask(14.4, 0.66) Set mWidget = Nothing '<- New line. The code above creates a new Widget each time the button is pressed. As soon as the LongTask method completes, the reference to the Widget is released by setting mWidget to Nothing, and the Widget is destroyed. A WithEvents variable can only contain one object reference at a time, so if you assign a different Widget object to mWidget, the previous Widget object's events will no longer be handled. If mWidget is the only object variable containing a reference to the old Widget, the object will be destroyed. Note You can declare as many WithEvents variables as you need, but arrays of WithEvents variables are not supported. Terminating Event Handling for a WithEvents Variable As long as there is a Widget object assigned to the variable mWidget, the event procedures associated with mWidget will be called whenever the Widget raises an event. To terminate event handling, you can set mWidget to Nothing, as shown in the following code fragment. ' Terminate event handling for mWidget. Set mWidget = Nothing When a WithEvents variable is set to Nothing, Visual Basic disconnects the object's events from the event procedures associated with the variable. 203

Important A WithEvents variable contains an object reference, just like any other object variable. This object reference counts toward keeping the object alive. When you are setting all references to an object to Nothing in order to destroy it, don't forget the variables you declared WithEvents. For More Information The event procedures associated with WithEvents variables look a lot like event procedures for controls on forms. "Comparing WithEvents to Control Events on Forms" discusses the similarities and differences. 44. Which datatypes in VB are capable of accepting Nulls? Variant 45. Is Visual Basic case sensitive in general? No 46. Is Visual Basic case sensitive in String Comparison? I.e. "STRINGVAL1" = "stringval1" ? Yes 10. How do you call a function in a DLL? Ref Doc 15 .What is the error message that you would get if you try to use a recordset that is not initialized to anything? 20. What is a datacontrol? Ref Doc 21.Whats the advantages/disadvantages of using datacontrol vs DAO/ADO/RDO? Ref Doc 33. Difference between variables defined as public in a standard module (.bas) file and a Class file? 35. Sequence of events when a MDI form open with two child forms is closed? 1. Unload event of Active child form 2. Unload event of remain child forms 3. Unload event of MDI Form 4. Terminate Event of unloaded child forms in the order of their unload 5. Finally Terminate event of MDI Form 6. dataquery To be check 38. What is the difference between COM and DCOM? PE DOC 41. What is the difference between creating a object using New and CreateObject in Visual Basic? PE DOC

204

Puzzles Three friends divided some bullets equally. After all of them shot 4 bullets the total number of bullets remaining is equal to the bullets each had after division. Find the original number divided. Answer 18 Assume that initial there were 3*X bullets. So they got X bullets each after division. All of them shot 4 bullets. So now they have (X - 4) bullets each. But it is given that,after they shot 4 bullets each, total number of bullets remaining is equal to the bullets each had after division i.e. X Therefore, the equation is 3 * (X - 4) = X 3 * X - 12 = X 2 * X = 12 X=6 Therefore the total bullets before division is = 3 * X = 18

Find sum of digits of D. Let A= 19991999 B = sum of digits of A C = sum of digits of B D = sum of digits of C (HINT : A = B = C = D (mod 9)) Answer The sum of the digits od D is 1. Let E = sum of digits of D. It follows from the hint that A = E (mod 9) Consider, A = 19991999 < 20002000 = 22000 * 10002000

205

= 1024200 * 106000 < 10800 * 106000 = 106800

i.e. A < 106800 i.e. B < 6800 * 9 = 61200 i.e. C < 5 * 9 = 45 i.e. D < 2 * 9 = 18 i.e. E <= 9 i.e. E is a single digit number.

Also, 1999 = 1 (mod 9) so 19991999 = 1 (mod 9) Therefore we conclude that E=1. There is a 50m long army platoon marching ahead. The last person in the platoon wants to give a letter to the first person leading the platoon. So while the platoon is marching he runs ahead, reaches the first person and hands over the letter to him and without stopping he runs and comes back to his original position. In the mean time the whole platoon has moved ahead by 50m. The question is how much distance did the last person cover in that time. Assuming that he ran the whole distance with uniform speed. Submitted Answer The last person covered 120.71 meters. It is given that the platoon and the last person moved with uniform speed. Also, they both moved for the identical amount of time. Hence, the ratio of the distance they covered - while person moving forward and backword - are equal. Let's assume that when the last person reached the first person, the platoon moved X meters forward. Thus, while moving forward the last person moved (50+X) meters whereas the platoon moved X meters. Similarly, while moving back the last person moved [50-(50-X)] X meters whereas the platoon moved (50-X) meters. Now, as the ratios are equal, (50+X)/X = X/(50-X) (50+X)*(50-X) = X*X Solving, X=35.355 meters Thus, total distance covered by the last person = (50+X) + X = 2*X + 50 = 2*(35.355) + 50 = 120.71 meters Note that at first glance, one might think that the total distance covered by the last person is 100 meters, as he ran the total lenght of the platoon (50 meters) twice. TRUE, but that's the relative distance covered by the last person i.e. assuming that the platoon is stationary.

206

If you take a marker & start from a corner on a cube, what is the maximum number of edges you can trace across if you never trace across the same edge twice, never remove the marker from the cube, & never trace anywhere on the cube, except for the corners & edges? Answer 9 To verify this, you can make a drawing of a cube, & number each of its 12 edges. Then, always starting from 1 corner & 1 edge, you can determine all of the possible combinations for tracing along the edges of a cube. There is no need to start from other corners or edges of the cube, as you will only be repeating the same combinations. The process is a little more involved than this, but is useful for solving many types of spatial puzzles. One of Mr. Bajaj, his wife, their son and Mr. Bajaj's mother is an Engineer and another is a Doctor.

• • •

If the Doctor is a male, then the Engineer is a male. If the Engineer is younger than the Doctor, then the Engineer and the Doctor are not blood relatives. If the Engineer is a female, then she and the Doctor are blood relatives.

Can you tell who is the Doctor and the Engineer? Answer Mr. Bajaj is the Engineer and either his wife or his son is the Doctor. Mr. Bajaj's wife and mother are not blood relatives. So from 3, if the Engineer is a female, the Doctor is a male. But from 1, if the Doctor is a male, then the Engineer is a male. Thus, there is a contradiction, if the Engineer is a female. Hence, either Mr. Bajaj or his son is the Engineer. Mr. Bajaj's son is the youngest of all four and is blood relative of each of them. So from 2, Mr. Bajaj's son is not the Engineer. Hence, Mr. Bajaj is the Engineer. Now from 2, Mr. Bajaj's mother can not be the Doctor. So the Doctor is either his wife or his son . It is not possible to determine anything further.

Three men - Sam, Cam and Laurie - are married to Carrie, Billy and Tina, but not necessarily in the same order. Sam's wife and Billy's Husband play Carrie and Tina's husband at bridge. No wife partners her husband and Cam does not play bridge. Who is married to Cam?

Answer Carrie is married to Cam. "Sam's wife and Billy's Husband play Carrie and Tina's husband at bridge." It means that Sam is not married to either Billy or Carrie. Thus, Sam is married to Tina. As Cam does not play bridge, Billy's husband must be Laurie. Hence, Carrie is married to Cam.

There are 3 persons X, Y and Z. On some day, X lent tractors to Y and Z as many as they had. After a month Y gave as many tractors to X and Z as many as they have. After a month Z did the same thing. At the end of this transaction each one of them had 24. Find the tractors each originally had? Answer

207

One way to solve it is by making 3 equations and solve them simultaneously. But there is rather easier way to solve it using Backtracing. It's given that at the end, each had 24 tractors (24, 24, 24) i.e. after Z gave tractors to X & Y as many as they had. It means that after getting tractors from Z their tractors got doubled. So before Z gave them tractors, they had 12 tractors each and Z had 48 tractors. (12, 12, 48) Similarly, before Y gave tractors to X & Z, they had 6 & 24 tractors respectively and Y had 42 tractors i.e. (6, 42, 24) Again, before X gave tractors to Y & Z, they had 21 & 12 tractors respectively and X had 39 tractors i.e. (39, 21, 12) Hence, initially X had 39 tractors, Y had 21 tractors and Z had 12 tractors. A certain street has 1000 buildings. A sign-maker is contracted to number the houses from 1 to 1000. How many zeroes will he need? Answer The sign-maker will need 192 zeroes. Divide 1000 building numbers into groups of 100 each as follow: (1..100), (101..200), (201..300), ....... (901..1000) For the first group, sign-maker will need 11 zeroes. For group numbers 2 to 9, he will require 20 zeroes each. And for group number 10, he will require 21 zeroes. The total numbers of zeroes required are = 11 + 8*20 + 21 = 11 + 160 + 21 = 192

There are 9 coins. Out of which one is odd one i.e weight is less or more. How many iterations of weighing are required to find odd coin? Answer It is always possible to find odd coin in 3 weighings and to tell whether the odd coin is heavier or lighter. 1. Take 8 coins and weigh 4 against 4. o If both are not equal, goto step 2 o If both are equal, goto step 3

2. One of these 8 coins is the odd one. Name the coins on heavier side of the scale as H1, H2, H3 and H4. Similarly, name the coins on the lighter side of the scale as L1, L2, L3 and L4. Either one of H's is heavier or one of L's is lighter. Weigh (H1, H2, L1) against (H3, H4, X) where X is one coin remaining in intial weighing. o

208

If both are equal, one of L2, L3, L4 is lighter. Weigh L2 against L3.  If both are equal, L4 is the odd coin and is lighter.  If L2 is light, L2 is the odd coin and is lighter.  If L3 is light, L3 is the odd coin and is lighter.

o

If (H1, H2, L1) is heavier side on the scale, either H1 or H2 is heavier. Weight H1 against H2  If both are equal, there is some error.  If H1 is heavy, H1 is the odd coin and is heavier.  If H2 is heavy, H2 is the odd coin and is heavier.

o

If (H3, H4, X) is heavier side on the scale, either H3 or H4 is heavier or L1 is lighter. Weight H3 against H4  If both are equal, L1 is the odd coin and is lighter.  If H3 is heavy, H3 is the odd coin and is heavier.  If H4 is heavy, H4 is the odd coin and is heavier.

3. The remaining coin X is the odd one. Weigh X against the anyone coin used in initial weighing. o If both are equal, there is some error. o If X is heavy, X is the odd coin and is heavier. o If X is light, X is the odd coin and is lighter. In a sports contest there were m medals awarded on n successive days (n > 1). 1. On the first day 1 medal and 1/7 of the remaining m - 1 medals were awarded. 2. On the second day 2 medals and 1/7 of the now remaining medals was awarded; and so on. 3. On the nth and last day, the remaining n medals were awarded. How many days did the contest last, and how many medals were awarded altogether? Answer Total 36 medals were awarded and the contest was for 6 days. On day 1: Medals awarded = (1 + 35/7) = 6 : Remaining 30 medals On day 2: Medals awarded = (2 + 28/7) = 6 : Remaining 24 medals On day 3: Medals awarded = (3 + 21/7) = 6 : Remaining 18 medals On day 4: Medals awarded = (4 + 14/7) = 6 : Remaining 12 medals On day 5: Medals awarded = (5 +7/7) = 6 : Remaining 6 medals On day 6: Medals awarded 6 I got this answer by writing small program. If anyone know any other simpler method, do submit it. A number of 9 digits has the following properties: •

• • 209

The number comprising the leftmost two digits is divisible by 2, that comprising the leftmost three digits is divisible by 3, the leftmost four by 4, the leftmost five by 5, and so on for the nine digits of the number i.e. the number formed from the first n digits is divisible by n, 2<=n<=9. Each digit in the number is different i.e. no digits are repeated. The digit 0 does not occur in the number i.e. it is comprised only of the digits 1-9 in some order.

Find the number. Answer The answer is 381654729 One way to solve it is Trial-&-Error. You can make it bit easier as odd positions will always occupy ODD numbers and even positions will always occupy EVEN numbers. Further 5th position will contain 5 as 0 does not occur. The other way to solve this problem is by writing a computer program that systematically tries all possibilities 1/3 rd of the contents of a container evaporated on the 1st day. 3/4th of the remaining contents of the container evaporated on the second day. What part of the contents of the container is left at the end of the second day? Answer Assume that contents of the container is X On the first day 1/3rd is evaporated. (1 - 1/3) of X is remaining i.e. (2/3)X On the Second day 3/4th is evaporated. Hence, (1- 3/4) of (2/3)X is remaining i.e. (1/4)(2/3)X = (1/6) X Hence 1/6th of the contents of the container is remaining

Vipul was studying for his examinations and the lights went off. It was around 1:00 AM. He lighted two uniform candles of equal length but one thicker than the other. The thick candle is supposed to last six hours and the thin one two hours less. When he finally went to sleep, the thick candle was twice as long as the thin one. For how long did Vipul study in candle light? Answer Vipul studied for 3 hours in candle light. Assume that the initial lenght of both the candle was L and Vipul studied for X hours. In X hours, total thick candle burnt = XL/6 In X hours, total thin candle burnt = XL/4 After X hours, total thick candle remaining = L - XL/6 After X hours, total thin candle remaining = L - XL/4 Also, it is given that the thick candle was twice as long as the thin one when he finally went to sleep. (L - XL/6) = 2(L - XL/4) 210

(6 - X)/6 = (4 - X)/2 (6 - X) = 3*(4 - X) 6 - X = 12 - 3X 2X = 6 X=3 Hence, Vipul studied for 3 hours i.e. 180 minutes in candle light.

If you started a business in which you earned Rs.1 on the first day, Rs.3 on the second day, Rs.5 on the third day, Rs.7 on the fourth day, & so on. How much would you have earned with this business after 50 years (assuming there are exactly 365 days in every year)? Answer Rs.333,062,500 To begin with, you want to know the total number of days: 365 x 50 = 18250. By experimentation, the following formula can be discovered, & used to determine the amount earned for any particular day: 1 + 2(x-1), with x being the number of the day. Take half of the 18250 days, & pair them up with the other half in the following way: day 1 with day 18250, day 2 with day 18249, & so on, & you will see that if you add these pairs together, they always equal Rs.36500. Multiply this number by the total number of pairs (9125), & you have the amount you would have earned in 50 years. Math gurus may use series formula to solve it.(series: 1,3,5,7,9,11.....upto 18250 terms) A worker earns a 5% raise. A year later, the worker receives a 2.5% cut in pay, & now his salary is Rs. 22702.68 What was his salary to begin with? Answer Rs.22176 Assume his salary was Rs. X He earns 5% raise. So his salary is (105*X)/100 A year later he receives 2.5% cut. So his salary is ((105*X)/100)*(97.5/100) which is Rs. 22702.68 Hence, solving equation ((105*X)/100)*(97.5/100) = 22702.68 X = 22176 At 6'o a clock ticks 6 times. The time between first and last ticks is 30 seconds. How long does it tick at 12'o. Answer 66 seconds 211

It is given that the time between first and last ticks at 6'o is 30 seconds. Total time gaps between first and last ticks at 6'o = 5 (i.e. between 1 & 2, 2 & 3, 3 & 4, 4 & 5 and 5 & 6) So time gap between two ticks = 30/5 = 6 seconds. Now, total time gaps between first and last ticks at 12'o = 11 Therefore time taken for 12 ticks = 11 * 6 = 66 seconds (and not 60 seconds) 500 men are arranged in an array of 10 rows and 50 columns according to their heights. Tallest among each row of all are asked to come out. And the shortest among them is A. Similarly after resuming them to their original positions, the shortest among each column are asked to come out. And the tallest among them is B. Now who is taller A or B ? Answer

No one is taller, both are same as A and B are the same person. As it is mentioned that 500 men are arranged in an array of 10 rows and 50 columns according to their heights. Let's assume that position numbers represent their heights. Hence, the shortest among the 50, 100, 150, ... 450, 500 is person with height 50 i.e. A. Similarly the tallest among 1, 2, 3, 4, 5, ..... 48, 48, 50 is person with height 50 i.e. B Now, both A and B are the person with height 50. Hence both are same. In Mr. Mehta's family, there are one grandfather, one grandmother, two fathers, two mothers, one father-in-law, one mother-in-law, four children, three grandchildren, one brother, two sisters, two sons, two daughters and one daughter-in-law. How many members are there in Mr. Mehta's family? Give minimal possible answer. Answer There are 7 members in Mr. Mehta's family. Mother & Father of Mr. Mehta, Mr. & Mrs. Mehta, his son and two daughters. Mother & Father of Mr. Mehta | | Mr. & Mrs. Mehta | | One Son & Two Daughters When Alexander the Great attacked the forces of Porus, an Indian soldier was captured by the Greeks. He had displayed such bravery in battle, however, that the enemy offered to let him choose how he wanted to be killed. They told him, "If you tell a lie, you will put to the sword, and if you tell the truth you will be hanged."

212

The soldier could make only one statement. He made that statement and went free. What did he say? Answer The soldier said, "You will put me to the sword." The soldier has to say a Paradox to save himself. If his statement is true, he will be hanged, which is not the sword and hence false. If his statement is false, he will be put to the sword, which will make it true. A Paradox !!! A person wanted to withdraw X rupees and Y paise from the bank. But cashier made a mistake and gave him Y rupees and X paise. Neither the person nor the cashier noticed that. After spending 20 paise, the person counts the money. And to his surprise, he has double the amount he wanted to withdraw. Find X and Y. (1 Rupee = 100 Paise) Answer As given, the person wanted to withdraw 100X + Y paise. But he got 100Y + X paise. After spending 20 paise, he has double the amount he wanted to withdraw. Hence, the equation is 2 * (100X + Y) = 100Y + X - 20 200X + 2Y = 100Y +X - 20 199X - 98Y = -20 98Y - 199X = 20 Now, we got one equation; but there are 2 variables. We have to apply little bit of logic over here. We know that if we interchange X & Y, amount gets double. So Y should be twice of X or one more than twice of X i.e. Y = 2X or Y = 2X+1 Case I : Y=2X Solving two equations simultaneously 98Y - 199X = 20 Y - 2X = 0 We get X = - 20/3 & Y = - 40/2 Case II : Y=2X+1 Solving two equations simultaneously 98Y - 199X = 20 Y - 2X = 1 We get X = 26 & Y = 53 Now, its obvious that he wanted to withdraw Rs. 26.53

213

Submit Answer

Users Answer (2)

BrainVista Answer

The game of Tic-Tac-Toe is being played between two players. Only the last mark to be placed in the game as shown. Who will win the game, O or X? Can you tell which was the sixth mark and at which position? Do explain your answer. At the Party: 1. There were 9 men and children. 2. There were 2 more women than children. 3. The number of different man-woman couples possible was 24. Note that if there were 7 men and 5 women, then there would have been 35 man-woman couples possible. Also, of the three groups - men, women and children - at the party: 4. There were 4 of one group. 5. There were 6 of one group. 6. There were 8 of one group. Exactly one of the above 6 statements is false. Can you tell which one is false? Also, how many men, women and children are there at the party

Assume that both the players are intelligent enough.

Answer O will win the game. The sixth mark was X in square 9. The 7th mark must be placed in square 5 which is the win situation for both X and O. Hence, the 6th mark must be placed in a line already containing two of the opponents marks. There are two such possibilities - the 6th mark would have been either O in square 7 or X in square 9. As we know both the players are intelligent enough, the 6th mark could not be O in square 7. Instead, he would have placed O in square 5 and would have won. Hence, the sixth mark must be X placed in square 9. And the seventh mark will be O. Thus O will win the game. Answer Statement (4) is false. There are 3 men, 8 women and 6 children. Assume that Statements (4), (5) and (6) are all true. Then, Statement (1) is false. But then Statement (2) and (3) both can not be true. Thus, contradictory to the fact that exactly one statement is false. So Statement (4) or Statement (5) or Statement (6) is false. Also, Statements (1), (2) and (3) all are true. 214

From (1) and (2), there are 11 men and women. Then from (3), there are 2 possible cases - either there are 8 men and 3 women or there are 3 men and 8 women. If there are 8 men and 3 women, then there is 1 child. Then Statements (4) and (5) both are false, which is not possible. Hence, there are 3 men, 8 women and 6 children. Statement (4) is false. There is a shortage of tubelights, bulbs and fans in a village - Kharghar. It is found that • • • • •

All houses do not have either tubelight or bulb or fan. exactly 19% of houses do not have just one of these. atleast 67% of houses do not have tubelights. atleast 83% of houses do not have bulbs. atleast 73% of houses do not have fans.

What percentage of houses do not have tubelight, bulb and fan? Answer 42% houses do not have tubelight, bulb and fan. Let's assume that there are 100 houses. Hence, there should be total 300 items i.e. 100 tubelights, 100 bulbs and 100 fans. From the given data, we know that there is shortage of atleast (67+83+73) 223 items in every 100 houses. Also, exactly 19 houses do not have just one item. It means that remaining 81 houses should account for the shortage of remaining (223-19) 204 items. If those remaining 81 houses do not have 2 items each, there would be a shortage of 162 items. But total of 204 items are short. Hence, atleast (204-162) 42 houses do not have all 3 items - tubelight, bulb and fan. Thus, 42% houses do not have tubelight, bulb and fan. Mr. Subramaniam rents a private car for Andheri-Colaba-Andheri trip. It costs him Rs. 300 everyday. One day the car driver informed Mr. Subramaniam that there were two students from Bandra who wished to go from Bandra to Colaba and back to Bandra. Bandra is halfway between Andheri and Colaba. Mr. Subramaniam asked the driver to let the students travel with him. On the first day when they came, Mr. Subramaniam said, "If you tell me the mathematically correct price you should pay individually for your portion of the trip, I will let you travel for free." How much should the individual student pay for their journey? Answer The individual student should pay Rs. 50 for their journey. Note that 3 persons are travelling between Bandra and Colaba. The entire trip costs Rs. 300 to Mr. Subramanian. Hence, half of the trip costs Rs. 150. For Andheri-Bandra-Andheri, only one person i.e. Mr. Subramaniam is travelling. Hence, he would pay Rs. 150. 215

For Bandra-Colaba-Bandra, three persons i.e Mr. Subramaniam and two students, are travelling. Hence, each student would pay Rs. 50. Substitute digits for the letters to make the following Division true O U T ------------S T E M | D E M I S E | D M O C ------------T U I S S T E M ---------Z Z Z E Z U M M -------I S T Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter M, no other letter can be 3 and all other M in the puzzle must be Answer C=0, U=1, S=2, T=3, O=4, M=5, I=6, Z=7, E=8, D=9 It is obvious that U=1 (as U*STEM=STEM) and C=0 (as I-C=I). S*O is a single digit and also S*T is a single digit. Hence, their values (O, S, T) must be 2, 3 or 4 (as they can not be 0 or 1 or greater than 4). Consider, STEM*O=DMOC, where C=0. It means that M must be 5. Now, its simple. O=4, S=2, T=3, E=8, Z=7, I=6 and D=9. O U T 4 1 3 -------------

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

S T E M | D E M I S E

2 3 8 5 | 9 8 5 6 2 8

216

| D M O C

| 9 5 4 0

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

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

T U I S

3 1 6 2

S T E M

2 3 8 5

----------

----------

Z Z Z E

7 7 7 8

Z U M M

7 1 5 5

--------

--------

I S T 6 2 3 Also, when arranged from 0 to 9, it spells CUSTOMIZED. At what time after 4.00 p.m. is the minutes hand of a clock exactly aligned with the hour hand? Answer 4:21:49.5 Assume that X minutes after 4.00 PM minute hand exactly aligns with and hour hand. For every minute, minute hand travels 6 degrees. Hence, for X minutes it will travel 6 * X degrees. For every minute, hour hand travels 1/2 degrees. Hence, for X minutes it will travel X/2 degrees. At 4.00 PM, the angle between minute hand and hour hand is 120 degrees. Also, after X minutes, minute hand and hour hand are exactly aligned. So the angle with respect to 12 i.e. Vertical Plane will be same. Therefore, 6 * X = 120 + X/2 12 * X = 240 + X 11 * X = 240 X = 21.8182 X = 21 minutes 49.5 seconds Hence, at 4:21:49.5 minute hand is exactly aligned with the hour hand. A soldier looses his way in a thick jungle. At random he walks from his camp but mathematically in an interesting fashion. First he walks one mile East then half mile to North. Then 1/4 mile to West, then 1/8 mile to South and so on making a loop. Finally how far he is from his camp and in which direction? Answer The soldier is 0.8944 miles away from his camp towards East-North. It is obvious that he is in East-North direction. Distance travelled in North and South directions = 1/2 - 1/8 + 1/32 - 1/128 + 1/512 - 1/2048 + and so on... (a geometric series with r = (-1/4) ) (1/2) * ( 1 - (-1/4)n ) = --------------------------( 1 - (-1/4) ) 217

= 1 / ( 2 * ( 1 - (-1/4) ) ) = 2/5 Similarly in East and West directions = 1 - 1/4 + 1/16 - 1/64 + 1/256 - and so on... (a geometric series with r = (-1/4) ) (1) * ( 1 - (-1/4)n ) = --------------------------( 1 - (-1/4) ) = 1 / ( ( 1- (-1/4) ) = 4/5 So the soldier is 4/5 miles away towards East and 2/5 miles away towards North. So using right angled triangle, soldier is 0.8944 miles away from his camp. Raj has a jewel chest containing Rings, Pins and Ear-rings. The chest contains 26 pieces. Raj has 2 1/2 times as many rings as pins, and the number of pairs of earrings is 4 less than the number of rings. How many earrings does Raj have? Answer 12 earrings Assume that there are R rings, P pins and E pair of ear-rings. It is given that, he has 2 1/2 times as many rings as pins. R = (5/2) * P or P = (2*R)/5 And, the number of pairs of earrings is 4 less than the number of rings. E = R - 4 or R = E + 4 Also, there are total 26 pieces. R + P + 2*E = 26 R + (2*R)/5 + 2*E = 26 5*R + 2*R + 10*E = 130 7*R + 10*E = 130 7*(E + 4) + 10*E = 130 7*E + 28 + 10*E = 130 17*E = 102 E=6 Hence, there are 6 pairs of Ear-rings i.e. total 12 Ear-rings How many ways are there of arranging the sixteen black or white pieces of a standard international chess set on the first two rows of the board? Given that each pawn is identical and each rook, knight and bishop is identical to its pair. Submitted

Answer 6,48,64,800 ways There are total 16 pieces which can be arranged on 16 places in 16P16 = 16! ways. 218

(16! = 16 * 15 * 14 * 13 * 12 * ..... * 3 * 2 * 1) But, there are some duplicate combinations because of identical pieces. • •

There are 8 identical pawn, which can be arranged in 8P8 = 8! ways. Similarly there are 2 identical rooks, 2 identical knights and 2 identical bishops. Each can be arranged in 2P2 = 2! ways.

Hence, the require answer is = (16!) / (8! * 2! * 2! * 2!) = 6,48,64,800 A person with some money spends 1/3 for cloths, 1/5 of the remaining for food and 1/4 of the remaining for travel. He is left with Rs 100/How much did he have with him in the begining? Answer Rs. 250/Assume that initially he had Rs. X He spent 1/3 for cloths =. (1/3) * X Remaining money = (2/3) * X He spent 1/5 of remaining money for food = (1/5) * (2/3) * X = (2/15) * X Remaining money = (2/3) * X - (2/15) * X = (8/15) * X Again, he spent 1/4 of remaining maoney for travel = (1/4) * (8/15) * X = (2/15) * X Remaining money = (8/15) * X - (2/15) * X = (6/15) * X But after spending for travel he is left with Rs. 100/- So (6/15) * X = 100 X = 250 Grass in lawn grows equally thick and in a uniform rate. It takes 24 days for 70 cows and 60 days for 30 cows to eat the whole of the grass. How many cows are needed to eat the grass in 96 days? Answer 20 cows g - grass at the beginning r - rate at which grass grows, per day y - rate at which one cow eats grass, per day n - no of cows to eat the grass in 96 days From given data, g + 24*r = 70 * 24 * y ---------- A g + 60*r = 30 * 60 * y ---------- B g + 96*r = n * 96 * y ---------- C Solving for (B-A), 219

(60 * r) - (24 * r) = (30 * 60 * y) - (70 * 24 * y) 36 * r = 120 * y ---------- D Solving for (C-B), (96 * r) - (60 * r) = (n * 96 * y) - (30 * 60 * y) 36 * r = (n * 96 - 30 * 60) * y 120 * y = (n * 96 - 30 * 60) * y [From D] 120 = (n * 96 - 1800) n = 20 Hence, 20 cows are needed to eat the grass in 96 days. There is a safe with a 5 digit number as the key. The 4th digit is 4 greater than the second digit, while the 3rd digit is 3 less than the 2nd digit. The 1st digit is thrice the last digit. There are 3 pairs whose sum is 11. Find the number. Answer 65292 As per given conditions, there are three possible combinations for 2nd, 3rd and 4th digits. They are (3, 0, 7) or (4, 1, 8) or (5, 2, 9) It is given that there are 3 pairs whose sum is 11. All possible pairs are (2, 9), (3, 8), (4, 7), (5, 6). Now required number is 5 digit number and it contains 3 pairs of 11. So it must not be having 0 and 1 in it. Hence, the only possible combination for 2nd, 3rd and 4th digits is (5, 2, 9) Also, 1st digit is thrice the last digit. The possible combinations are (3, 1), (6, 2) and (9, 3), out of which only (6, 2) with (5, 2, 9) gives 3 pairs of 11. Hence, the answer is 65292. Four friends - Arjan, Bhuvan, Guran and Lakha were comparing the number of sheep that they owned. It was found that Guran had ten more sheep than Lakha. If Arjan gave one-third to Bhuvan, and Bhuvan gave a quarter of what he then held to Guran, who then passed on a fifth of his holding to Lakha, they would all have an equal number of sheep. How many sheep did each of them possess? Give the minimal possible answer Answer

220

Arjan, Bhuvan, Guran and Lakha had 90, 50, 55 and 45 sheep respectively. Assume that Arjan, Bhuvan, Guran and Lakha had A, B, G and L sheep respectively. As it is given that at the end each would have an equal number of sheep, comparing the final numbers from the above table. Arjan's sheep = Bhuvan's sheep 2A/3 = A/4 + 3B/4 8A = 3A + 9B 5A = 9B Arjan's sheep = Guran's sheep 2A/3 = A/15 + B/5 + 4G/5 2A/3 = A/15 + A/9 + 4G/5 (as B=5A/9) 30A = 3A + 5A + 36G 22A = 36G 11A = 18G Arjan's sheep = Lakha's sheep 2A/3 = A/60 + B/20 + G/5 + L 2A/3 = A/60 + A/36 + 11A/90 + L (as B=5A/9 and G=11A/18) 2A/3 = A/6 + L A/2 = L A = 2L Also, it is given that Guran had ten more sheep than Lakha. G = L + 10 11A/18 = A/2 + 10 A/9 = 10 A = 90 sheep Thus, Arjan had 90 sheep, Bhuvan had 5A/9 i.e. 50 sheep, Guran had 11A/18 i.e. 55 sheep and Lakha had A/2 i.e. 45 sheep. Consider a number 235, where last digit is the sum of first two digits i.e. 2 + 3 = 5. How many such 3-digit numbers are there? Answer There are 45 different 3-digit numbers. The last digit can not be 0. If the last digit is 1, the only possible number is 101. (Note that 011 is not a 3-digit number) If the last digit is 2, the possible numbers are 202 and 112. If the last digit is 3, the possible numbers are 303, 213 and 123. If the last digit is 4, the possible numbers are 404, 314, 224 and 134. If the last digit is 5, the possible numbers are 505, 415, 325, 235 and 145. Note the pattern here - If the last digit is 1, there is only one number. If the last digit is 2, there are two numbers. If the last digit is 3, there are three numbers. If the last digit is 4, there are four 221

numbers. If the last digit is 5, there are five numbers. And so on..... Thus, total numbers are 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45 Altogether then, there are 45 different 3-digit numbers, where last digit is the sum of first two digits. Find the smallest number such that if its rightmost digit is placed at its left end, the new number so formed is precisely 50% larger than the original number. Answer The answer is 285714. If its rightmost digit is placed at its left end, then new number is 428571 which is 50% larger than the original number 285714. The simplest way is to write a small program. And the other way is trial and error !!! Two identical pack of cards A and B are shuffled throughly. One card is picked from A and shuffled with B. The top card from pack A is turned up. If this is the Queen of Hearts, what are the chances that the top card in B will be the King of Hearts? Answer 52 / 2703 There are two cases to be considered. CASE 1 : King of Hearts is drawn from Pack A and shuffled with Pack B Probability of drawing King of Hearts from Pack A = 1/51 (as Queen of Hearts is not to be drawn) Probability of having King of Hearts on the top of the Pack B = 2/53 So total probability of case 1 = (1/51) * (2/53) = 2 / (51 * 53) CASE 2 : King of Hearts is not drawn from Pack A Probability of not drawing King of Hearts from Pack A = 50/51 (as Queen of Hearts is not to be drawn) Probability of having King of Hearts on the top of the Pack B = 1/53 So total probability of case 2 = (50/51) * (1/53) = 50 / (51 * 53) Now adding both the probability, the required probability is = 2 / (51 * 53) + 50 / (51 * 53) = 52 / (51 * 53) = 52 / 2703 = 0.0192378 There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner. What is the probability that they don't collide? Answer Let's mark the corners of the triangle as A,B,C. There are total 8 ways in which ants can move. 222

1. 2. 3. 4. 5. 6. 7. 8.

A->B, B->C, C->A A->B, B->C, C->B A->B, B->A, C->A A->B, B->A, C->B A->C, C->B, B->A A->C, C->B, B->C A->C, C->A, B->A A->C, C->A, B->C

Out of which, there are only two cases under which the ants won't collide : • •

A->B, B->C, C->A A->C, C->B, B->A

Find all sets of consecutive integers that add up to 1000. Submitted by : James Barberousse

Answer There are total 8 such series: 1. Sum of 2000 numbers starting from -999 i.e. summation of numbers from -999 to 1000. (-999) + (-998) + (-997) + ..... + (-1) + 0 + 1 + 2 + ..... + 997 + 998 + 999 + 1000 = 1000 2. Sum of 400 numbers starting from -197 i.e. summation of numbers from -197 to 202. (-197) + (-196) + (-195) + ..... + (-1) + 0 + 1 + 2 + ..... + 199 + 200 + 201 + 202 = 1000 3. Sum of 125 numbers starting from -54 i.e. summation of numbers from -54 to 70. (-54) + (-53) + (-52) + ..... + (-1) + 0 + 1 + 2 + ..... + 68 + 69 + 70 = 1000 4. Sum of 80 numbers starting from -27 i.e. summation of numbers from -27 to 52. (-27) + (-26) + (-25) + ..... + (-1) + 0 + 1 + 2 + ..... + 50 + 51 + 52 = 1000 5. Sum of 25 numbers starting from 28 i.e. summation of numbers from 28 to 52. 28 + 29 + 30 + 31 + 32 + 33 + 34 + 35 + 36 + 37 + 38 + 39 + 40 + 41 + 42 + 43 + 44 + 45 + 46 + 47 + 48 + 49 + 50 + 51 + 52 = 1000 6. Sum of 16 numbers starting from 55 i.e. summation of numbers from 55 to 70. 55 + 56 + 57 + 58 + 59 +60 + 61 + 62 + 63 + 64 + 65 + 66 + 67 + 68 + 69 + 70 = 1000 7. Sum of 5 numbers starting from 198 i.e. summation of numbers from 198 to 202. 198 + 199 + 200 +201 + 202 = 1000 8. Sum of 1 number starting from 1000. 1000 = 1000

There is a 4-character code, with 2 of them being letters and the other 2 being numbers. How many maximum attempts would be necessary to find the correct code? Note that the code is case-sensitive. Answer The maximum number of attempts required are 16,22,400 There are 52 possible letters - a to z and A to Z, and 10 possible numbers - 0 to 9. Now, 4 223

characters - 2 letters and 2 numbers, can be selected in 52*52*10*10 ways. These 4 characters can be arranged in 4C2 i.e. 6 different ways - the number of unique patterns that can be formed by lining up 4 objects of which 2 are distinguished one way (i.e. they must be letters) and the other 2 are distinguished another way (i.e. they must be numbers). Consider an example : Let's assume that @ represents letter and # represents number. the 6 possible ways of arranging them are : @@##, @#@#, @##@, #@@#, #@#@, ##@@ Hence, the required answer is = 52*52*10*10*6 = 16,22,400 attempts = 1.6 million approx. Thanks to Tim Sanders for opening BrainVista's brain !!! How many possible combinations are there in a 3x3x3 rubics cube? In other words, if you wanted to solve the rubics cube by trying different combinations, how many might it take you (worst case senerio)? How many for a 4x4x4 cube? Submitted

Answer There are 4.3252 * 10^19 possible combinations for 3x3x3 Rubics and 7.4012 * 10^45 possible combinations for 4x4x4 Rubics. Let's consider 3x3x3 Rubics first. There are 8 corner cubes, which can be arranged in 8! ways. Each of these 8 cubes can be turned in 3 different directions, so there are 3^8 orientations altogether. But if you get all but one of the corner cube into chosen positions and orientations, only one of 3 orientations of the final corner cube is possible. Thus, total ways corner cubes can be placed = (8!) * (3^8)/8 = (8!) * (3^7) Similarly, 12 edge cubes can be arranged in 12! ways. Each of these 12 cubes can be turned in 2 different directions, so there are 2^12 orientations altogether. But if you get all but one of the edge cube into chosen positions and orientations, only one of 2 orientations of the final edge cube is possible. Thus, total ways edge cubes can be placed = (12!) * (2^12)/2 = (12!) * (2^11) Here, we have essentially pulled the cubes apart and stuck cubes back in place wherever we please. In reality, we can only move cubes around by turning the faces of the cubes. It turns out that you can't turn the faces in such a way as to switch the positions of two cubes while returning all the others to their original positions. Thus if you get all but two cubes in place, there is only one attainable choice for them (not 2!). Hence, we must divide by 2. Total different possible combinations are = [(8!) * (3^7)] * [(12!) * (2^11)] / 2 = (8!) * (3^7) * (12!) * (2^10) = 4.3252 * 10^19 Similarly, for 4x4x4 Rubics total different possible combinations are = [(8!) * (3^7)] * [(24!)] * [(24!) / (4!^6)] / 24 224

= 7.4011968 * 10^45 Note that there are 24 edge cubes, which you can not turn in 2 orientations (hence no 2^24 / 2). Also, there are 4 center cubes per face i.e. (24!) / (4!^6). You can switch 2 cubes without affecting the rest of the combination as 4*4*4 has even dimensions (hence no division by 2). But pattern on one side is rotated in 4 directions over 6 faces, hence divide by 24. Substitute digits for the letters to make the following relation true. N E V E R L

E

+

A

V

E

M

E

----------------A L O N E Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter M, no other letter can be 3 and all other M in the puzzle must be 3. Answer A tough one!!! Since R + E + E = 10 + E, it is clear that R + E = 10 and neither R nor E is equal to 0 or 5. This is the only entry point to solve it. Now use trial-n-error method. N

E

V

E

R

2

1

4

1

9

L

E

A

V

E

3

1

5

4

1

M

E

6

1

+

----------------A

L

O

N

E

+

----------------5

3

0

2

1

One of the four people - Mr. Clinton, his wife Monika, their son Mandy and their daughter Cindy is a singer and another is a dancer. Mr. Clinton is older than his wife and Mady is older than his sister. 1. If the singer and the dancer are the same sex, then the dancer is older than the singer. 2. If neither the singer nor the dancer is the parent of the other, then the singer is older than the dancer. 3. If the singer is a man, then the singer and the dancer are the same age. 4. If the singer and the dancer are of opposite sex then the man is older than the woman. 5. If the dancer is a woman, then the dancer is older than the singer. Whose occupation do you know? And what is his/her occupation? Answer Cindy is the Singer. Mr. Clinton or Monika is the Dancer. 225

From (1) and (3), the singer and the dancer, both can not be a man. From (3) and (4), if the singer is a man, then the dancer must be a man. Hence, the singer must be a woman. CASE I : Singer is a woman and Dancer is also a woman Then, the dancer is Monika and the singer is Cindy. CASE II : Singer is a woman and Dancer is also a man Then, the dancer is Mr. Clinton and the singer is Cindy. In both the cases, we know that Cindy is the Singer. And either Mr. Clinton or Monika is the Dancer. There are 20 people in your applicant pool, including 5 pairs of identical twins. If you hire 5 people randomly, what are the chances you will hire at least 1 pair of identical twins? (Needless to say, this could cause trouble ;)) Submitted

Answer The probability to hire 5 people with at least 1 pair of identical twins is 25.28% 5 people from the 20 people can be hired in 20C5 = 15504 ways. Now, divide 20 people into two groups of 10 people each : G1 - with all twins G2 - with all people other than twins Let's find out all possible ways to hire 5 people without a single pair of indentical twins. People from G1

People from G2

No of ways to hire G1 without a single pair of indentical twins

No of ways to hire G2

0

5

10C0

10C5

252

1

4

10C1

10C4

2100

2

3

10C2 * 8/9

10C3

4800

3

2

10C3 * 8/9 * 6/8

10C2

3600

4

1

10C4 * 8/9 * 6/8 * 4/7

10C1

800

5

0

10C5 * 8/9 * 6/8 * 4/7 * 2/6

10C0

32 Total

Total ways

11584

Thus, total possible ways to hire 5 people without a single pair of indentical twins = 11584 ways So, total possible ways to hire 5 people with at least a single pair of indentical twins = 15504 11584 = 3920 ways Hence, the probability to hire 5 people with at least a single pair of indentical twins = 3920/15504 = 245/969 = 0.2528 = 25.28% In a hotel, rooms are numbered from 101 to 550. A room is chosen at random. What is the probability that room number starts with 1, 2 or 3 and ends with 4, 5 or 6? 226

Answer There are total 450 rooms. Out of which 299 room number starts with either 1, 2 or 3. (as room number 100 is not there) Now out of those 299 rooms only 90 room numbers end with 4, 5 or 6 So the probability is 90/450 i.e. 1/5 or 0.20 Draw 9 dots on a page, in the shape of three rows of three dots to form a square. Now place your pen on the page, draw 4 straight lines and try and cover all the dots. You're not allowed to lift your pen. Note: Don't be confined by the dimensions of the square. Submitted

There are 3 persons X, Y and Z. On some day, X lent tractors to Y and Z as many as they had. After a month Y gave as many tractors to X and Z as many as they have. After a month Z did the same thing. At the end of this transaction each one of them had 24. Find the tractors each originally had? Answer One way to solve it is by making 3 equations and solve them simultaneously. But there is rather easier way to solve it using Backtracing. It's given that at the end, each had 24 tractors (24, 24, 24) i.e. after Z gave tractors to X & Y as many as they had. It means that after getting tractors from Z their tractors got doubled. So before Z gave them tractors, they had 12 tractors each and Z had 48 tractors. (12, 12, 48) Similarly, before Y gave tractors to X & Z, they had 6 & 24 tractors respectively and Y had 42 tractors i.e. (6, 42, 24) Again, before X gave tractors to Y & Z, they had 21 & 12 tractors respectively and X had 39 tractors i.e. (39, 21, 12) Hence, initially X had 39 tractors, Y had 21 tractors and Z had 12 tractors. There is a 50m long army platoon marching ahead. The last person in the platoon wants to give a letter to the first person leading the platoon. So while the platoon is marching he runs ahead, reaches the first person and hands over the letter to him and without stopping he runs and comes back to his original position. In the mean time the whole platoon has moved ahead by 50m. The question is how much distance did the last person cover in that time. Assuming that he ran the whole distance with uniform speed. Submitted

Answer 227

The last person covered 120.71 meters. It is given that the platoon and the last person moved with uniform speed. Also, they both moved for the identical amount of time. Hence, the ratio of the distance they covered - while person moving forward and backword - are equal. Let's assume that when the last person reached the first person, the platoon moved X meters forward. Thus, while moving forward the last person moved (50+X) meters whereas the platoon moved X meters. Similarly, while moving back the last person moved [50-(50-X)] X meters whereas the platoon moved (50-X) meters. Now, as the ratios are equal, (50+X)/X = X/(50-X) (50+X)*(50-X) = X*X Solving, X=35.355 meters Thus, total distance covered by the last person = (50+X) + X = 2*X + 50 = 2*(35.355) + 50 = 120.71 meters Note that at first glance, one might think that the total distance covered by the last person is 100 meters, as he ran the total lenght of the platoon (50 meters) twice. TRUE, but that's the relative distance covered by the last person i.e. assuming that the platoon is stationary. Assume that you have enough coins of 1, 5, 10, 25 and 50 cents. How many ways are there to make change for a dollar? Do explain your answer.

There are 292 ways to make change for a dollar using coins of 1, 5, 10, 25 and 50 cents. Let's generalised the teaser and make a table as shown above. If you wish to make change for 75 cents using only 1, 5, 10 and 25 cent coins, go to the .25 row and the 75 column to obtain 121 ways to do this. The table can be created from left-to-right and top-to-bottom. Start with the top left i.e. 1 cent row. There is exactly one way to make change for every amount. Then calculate the 5 cents row by adding the number of ways to make change for the amount using 1 cent coins plus the number of ways to make change for 5 cents less using 1 and 5 cent coins. Let's take an example: To get change for 50 cents using 1, 5 and 10 cent coins. 228

* 50 cents change using 1 and 5 cent coins = 11 ways * (50-10) 40 cents change using 1, 5 and 10 cent coins = 25 ways * 50 cents change using 1, 5 and 10 cent coins = 11+25 = 36 ways Let's take another example: To get change for 75 cents using all coins up to 50 cent i.e. 1, 5, 10, 25 and 50 cents coins. * 75 cents change using coins upto 25 cent = 121 ways * (75-50) 25 cents change using coins upto 50 cent = 13 ways * 75 cents change using coins upto 50 cent = 121+13 = 134 ways For people who don't want to tease their brain and love to do computer programming, there is a simple way. Write a small multi-loop program to solve the equation: A + 5B + 10C + 25D + 50E = 100 where, A = 0 to 100 B = 0 to 20 C = 0 to 10 D = 0 to 4 E = 0 to 2 The program should output all the possible values of A, B, C, D and E for which the equation is satisfied. In a Road Race, one of the three bikers was doing 15km less than the first and 3km more than the third. He also finished the race 12 minutes after the first and 3 minutes before the third. Can you find out the speed of each biker, the time taken by each biker to finish the race and the length of the course? Assume that there were no stops in the race and also they were driving with constant speeds through out the Answer

Let us assume that Speed of First biker = V1 km/min Speed of Second biker = V2 km/min 229

Speed of Third biker = V3 km/min Total time take by first biker = T1 min Total distance = S km Now as per the data given in the teaser, at a time T min X1 = V1 * T ----> 1 X1 - 15 = V2 * T

----> 2

X1 - 18 = V3 * T

----> 3

At a Distance S Km. S = V1 * T1

----> 4

S = V2 * (T1 + 12)

----> 5

S = V3 * (T1 + 15)

----> 6

Thus there are 6 equations and 7 unknown data that means it has infinite number of solutions. By solving above 6 equations we get, Time taken by first biker, T1 = 60 Min. Time taken by Second biker, T2 = 72 Min. Time taken by first biker, T3 = 75 Min. Also, we get Speed of first biker, V1 = 90/T km/min Speed of second biker, V2 = (5/6)V1 = 75/T km/min Speed of third biker, V3 = (4/5)V1 = 72/T km/min Also, the length of the course, S = 5400/T km Thus, for the data given, only the time taken by each biker can be found i.e. 60, 72 and 75 minutes. For other quantities, one more independent datum is required i.e. either T or V1 or V2 or V3 Thanks to Theertham Srinivas for the answer !!! What is the four-digit number in which the first digit is 1/3 of the second, the third is the sum of the first and second, and the last is three times the second? Answer The 4 digit number is 1349. It is given that the first digit is 1/3 of the second. There are 3 such possibilities. 1. 1 and 3 2. 2 and 6 3. 3 and 9 Now, the third digit is the sum of the first and second digits. 1. 1 + 3 = 4 2. 2 + 6 = 8 3. 3 + 9 = 12 230

It is clear that option 3 is not possible. So we are left with only two options. Also, the last digit is three times the second, which rules out the second option. Hence, the answer is 1349. Difference between Bholu's and Molu's age is 2 years and the difference between Molu's and Kolu's age is 5 years. What is the maximum possible value of the sum of the difference in their ages, taken two at a time? Answer The maximum possible value of the sum of the difference in their ages - taken two at a time - is 14 years. It is given that "Difference between Bholu's and Molu's age is 2 years" "Difference between Molu's and Kolu's age is 5 years" Now, to get the maximum possible value, the difference between Bholu's and Kolu's age should be maximum i.e. Molu's age should be in between Bholu's and Kolu's age. Then, the difference between Bholu's and Kolu's age is 7 years. Hence, the maximum possible value of the sum of the difference in their ages - taken two at a time - is (2 + 5 + 7) 14 years. If it is given that: 25 - 2 = 3 100 x 2 = 20 36 / 3 = 2 What is 144 - 3 = ? Submitted

Answer There are 3 possible answers to it. Answer 1 : 9 Simply replace the first number by its square root. (25) 5 - 2 = 3 (100) 10 x 2 = 20 (36) 6 / 3 = 2 (144) 12 - 3 = 9 Answer 2 : 11 Drop the digit in the tens position from the first number. (2) 5 - 2 = 3 1 (0) 0 x 2 = 20 (3) 6 / 3 = 2 1 (4) 4 - 3 = 11 You will get the same answer on removing left and right digit alternatively from the first number i.e remove left digit from first (2), right digit from second (0), left digit from third (3) and right digit from forth (4). (2) 5 - 2 = 3 10 (0) x 2 = 20 (3) 6 / 3 = 2 14 (4) - 3 = 11 231

Answer 3 : 14 Drop left and right digit alternatively from the actual answer. 25 - 2 = (2) 3 (drop left digit i.e. 2) 100 * 2 = 20 (0) (drop right digit i.e. 0) 36 / 3 = (1) 2 (drop left digit i.e. 1) 144 - 3 = 14 (1) (drop right digit i.e. 1) A 3 digit number is such that it's unit digit is equal to the product of the other two digits which are prime. Also, the difference between it's reverse and itself is 396. What is the sum of the three digits? Answer The required number is 236 and the sum is 11. It is given that the first two digits of the required number are prime numbers i.e. 2, 3, 5 or 7. Note that 1 is neither prime nor composite. Also, the third digit is the multiplication of the first two digits. Thus, first two digits must be either 2 or 3 i.e. 22, 23, 32 or 33 which means that there are four possible numbers - 224, 236, 326 and 339. Now, it is also given that - the difference between it's reverse and itself is 396. Only 236 satisfies this condition. Hence, the sum of the three digits is 11. There are 4 mugs placed upturned on the table. Each mug have the same number of marbles and a statement about the number of marbles in it. The statements are: Two or Three, One or Four, Three or One, One or Two. Only one of the statement is correct. How many marbles are there under each mug? Answer A simple one. As it is given that only one of the four statement is correct, the correct number can not appear in more than one statement. If it appears in more than one statement, then more than one statement will be correct. Hence, there are 4 marbles under each mug. At University of Probability, there are 375 freshmen, 293 sophomores, 187 juniors, & 126 seniors. One student will randomly be chosen to receive an award. What percent chance is there that it will be a junior? Round to the nearest whole percent Answer 19% This puzzle is easy. Divide the number of juniors (187) by the total number of students (981), & then multiply the number by 100 to convert to a percentage. Hence the answer is (187/981)*100 = 19% If you were to dial any 7 digits on a telephone in random order, what is the probability that you will dial your own phone number? 232

Assume that your telephone number is 7-digits. Answer 1 in 10,000,000 There are 10 digits i.e. 0-9. First digit can be dialed in 10 ways. Second digit can be dialed in 10 ways. Third digit can be dialed in 10 ways. And so on..... Thus, 7-digit can be dialed in 10*10*10*10*10*10*10 (=10,000,000) ways. And, you have just one telephone number. Hence, the possibility that you will dial your own number is 1 in 10,000,000. Note that 0123456 may not be a valid 7-digit telephone number. But while dialing in random order, that is one of the possible 7-digit number which you may dial. An anthropologist discovers an isolated tribe whose written alphabet contains only six letters (call the letters A, B, C, D, E and F). The tribe has a taboo against using the same letter twice in the same word. It's never done. If each different sequence of letters constitues a different word in the language, what is the maximum number of six-letter words that the language can employ? Submitted

Answer The language can employ maximum of 720 six-letter words. It is a simple permutation problem of arranging 6 letters to get different six-letter words. And it can be done in in 6! ways i.e. 720 ways. In otherwords, the first letter can be any of the given 6 letters (A through F). Then, whatever the first letter is, the second letter will always be from the remaining 5 letters (as same letter can not be used twice), and the third letter always be from the remaining 4 letters, and so on. Thus, the different possible six-letter words are 6*5*4*3*2*1 = 720 Kate, Demi, Madona, Sharon, Britney and Nicole decided to lunch together in a restaurant. The waiter led them to a round table with six chairs. How many different ways can they seat? Answer There are 120 different possible seating arrangments. Note that on a round table ABCDEF and BCDEFA is the same. The first person can sit on any one of the seats. Now, for the second person there are 5 options, for the third person there are 4 options, for the forth person there are 3 options, for the fifth person there are 2 options and for the last person there is just one option. Thus, total different possible seating arrangements are =5*4*3*2*1 = 120 3 blocks are chosen randomly on a chessboard. What is the probability that they are in the same diagonal?

233

Answer There are total of 64 blocks on a chessboard. So 3 blocks can be chosen out of 64 in 64C3 ways. So the sample space is = 41664 There are 2 diagonal on chessboard each one having 8 blocks. Consider one of them. 3 blocks out of 8 blocks in diagonal can be chosen in 8C3 ways. But there are 2 such diagonals, hence favourables = 2 * 8C3 = 2 * 56 = 112 The require probability is = 112 / 41664 = 1 / 372 = 0.002688 What is the area of the triangle ABC with A(e,p) B(2e,3p) and C(3e,5p)? where p = PI (3.141592654) Answer A tricky ONE. Given 3 points are colinear. Hence, it is a straight line. Hence area of triangle is 0.

Silu and Meenu were walking on the road. Silu said, "I weigh 51 Kgs. How much do you weigh?" Meenu replied that she wouldn't reveal her weight directly as she is overweight. But she said, "I weigh 29 Kgs plus half of my weight." How much does Meenu weigh? Answer Meenu weighs 58 Kgs. It is given that Meenu weighs 29 Kgs plus half of her own weight. It means that 29 Kgs is the other half. So she weighs 58 Kgs. Solving mathematically, let's assume that her weight is X Kgs. X = 29 + X/2 2*X = 58 + X X = 58 Kgs Consider the sum: ABC + DEF + GHI = JJJ

234

If different letters represent different digits, and there are no leading zeros, what does J represent?

Answer The value of J must be 9. Since there are no leading zeros, J must be 7, 8, or 9. (JJJ = ABC + DEF + GHI = 14? + 25? + 36? = 7??) Now, the remainder left after dividing any number by 9 is the same as the remainder left after dividing the sum of the digits of that number by 9. Also, note that 0 + 1 + ... + 9 has a remainder of 0 after dividing by 9 and JJJ has a remainder of 0, 3, or 6. The number 9 is the only number from 7, 8 and 9 that leaves a remainder of 0, 3, or 6 if you remove it from the sum 0 + 1 + ... + 9. Hence, it follows that J must be 9. A man has Ten Horses and nine stables as shown here. [] [] [] [] [] [] [] [] [] The man wants to fit Ten Horses into nine stables. How can he fit Ten horses into nine stables? Submitted

Answer The answer is simple. It says the man wants to fit "Ten Horses" into nine stables. There are nine letters in the phrase "Ten Horses". So you can put one letter each in all nine stables. [T] [E] [N] [H] [O] [R] [S] [E] [S] A man is at a river with a 9 gallon bucket and a 4 gallon bucket. He needs exactly 6 gallons of water. How can he use both buckets to get exactly 6 gallons of water? Note that he cannot estimate by dumping some of the water out of the 9 gallon bucket or the 4 gallon bucket Answer For the sack of explanation, let's identify 4 gallon bucket as Bucket P and 9 gallon bucket as Bucket Q. 4 gallon bucket (Bucket P)

9 gallon bucket (Bucket Q)

Initially

0

0

Fill the bucket Q with 9 gallon water

0

9

Pour 4 gallon water from bucket Q to bucket P

4

5

Empty bucket P

0

5

Pour 4 gallon water from bucket Q to bucket P

4

1

Empty bucket P

0

1

Pour 1 gallon water from bucket Q to bucket P

1

0

Fill the bucket Q with 9 gallon water

1

9

Operation

235

Pour 3 gallon water from bucket Q to bucket P

4

6

9 gallon bucket contains 6 gallon of water, as required. Each of the five characters in the word BRAIN has a different value between 0 and 9. Using the given grid, can you find out the value of each character? B R A I N 31 B

B

R

B

A

31

N

I

A

B

B

32

N

I

B

A

I

30

I

R

A

A

A

23

37 29 25 27 29 The numbers on the extreme right represent the sum of the values represented by the characters in that row. Also, the numbers on the last raw represent the sum of the values represented by the characters in that column. e.g. B + R + A + I + N = 31 (from first row)

236

Answer B=7, R=6, A=4, I=5 and N=9 Make total 10 equations - 5 for rows and 5 for columns - and sovle them. From Row3 and Row4, N+I+A+B+B=N+I+B+A+I+2 B=I+2 From Row1 and Row3, B+R+A+ I+ N=N+ I+A+B+B-1 R=B-1 From Column2, R + B + I + I + R = 29 B + 2R + 2I = 29 B + 2(B - 1) + 2I = 29 3B + 2I = 31 3(I + 2) + 2I = 31 5I = 25 I=5 Hence, B=7 and R=6 From Row2, B + B + R + B + A = 31 3B + R + A = 31 3(7) + 6 + A = 31 A=4 From Row1, B + R + A + I + N = 31 7 + 6 + 4 + 5 + N = 31 N=9 Thus, B=7, R=6, A=4, I=5 and N=9 Submit Answer

Users Answer (24)

BrainV

There are 9 coins. Out of which one is odd one i.e weight is less or more. How many iterations of weighing are required to find odd coin? Answer It is always possible to find odd coin in 3 weighings and to tell whether the odd coin is heavier or lighter. 1. Take 8 coins and weigh 4 against 4. o If both are not equal, goto step 2 o If both are equal, goto step 3

237

2. One of these 8 coins is the odd one. Name the coins on heavier side of the scale as H1, H2, H3 and H4. Similarly, name the coins on the lighter side of the scale as L1, L2, L3 and L4. Either one of H's is heavier or one of L's is lighter. Weigh (H1, H2, L1) against (H3, H4, X) where X is one coin remaining in intial weighing. o

If both are equal, one of L2, L3, L4 is lighter. Weigh L2 against L3.  If both are equal, L4 is the odd coin and is lighter.  If L2 is light, L2 is the odd coin and is lighter.  If L3 is light, L3 is the odd coin and is lighter.

o

If (H1, H2, L1) is heavier side on the scale, either H1 or H2 is heavier. Weight H1 against H2  If both are equal, there is some error.  If H1 is heavy, H1 is the odd coin and is heavier.  If H2 is heavy, H2 is the odd coin and is heavier.

o

If (H3, H4, X) is heavier side on the scale, either H3 or H4 is heavier or L1 is lighter. Weight H3 against H4  If both are equal, L1 is the odd coin and is lighter.  If H3 is heavy, H3 is the odd coin and is heavier.  If H4 is heavy, H4 is the odd coin and is heavier.

3. The remaining coin X is the odd one. Weigh X against the anyone coin used in initial weighing. o If both are equal, there is some error. o If X is heavy, X is the odd coin and is heavier. o If X is light, X is the odd coin and is lighter. In a sports contest there were m medals awarded on n successive days (n > 1). 1. On the first day 1 medal and 1/7 of the remaining m - 1 medals were awarded. 2. On the second day 2 medals and 1/7 of the now remaining medals was awarded; and so on. 3. On the nth and last day, the remaining n medals were awarded. How many days did the contest last, and how many medals were awarded altogether? Answer Total 36 medals were awarded and the contest was for 6 days. On day 1: Medals awarded = (1 + 35/7) = 6 : Remaining 30 medals On day 2: Medals awarded = (2 + 28/7) = 6 : Remaining 24 medals On day 3: Medals awarded = (3 + 21/7) = 6 : Remaining 18 medals On day 4: Medals awarded = (4 + 14/7) = 6 : Remaining 12 medals On day 5: Medals awarded = (5 +7/7) = 6 : Remaining 6 medals On day 6: Medals awarded 6 238

I got this answer by writing small program. If anyone know any other simpler method, do submit it. A number of 9 digits has the following properties: •

• •

The number comprising the leftmost two digits is divisible by 2, that comprising the leftmost three digits is divisible by 3, the leftmost four by 4, the leftmost five by 5, and so on for the nine digits of the number i.e. the number formed from the first n digits is divisible by n, 2<=n<=9. Each digit in the number is different i.e. no digits are repeated. The digit 0 does not occur in the number i.e. it is comprised only of the digits 1-9 in some order.

Find the number. Answer The answer is 381654729 One way to solve it is Trial-&-Error. You can make it bit easier as odd positions will always occupy ODD numbers and even positions will always occupy EVEN numbers. Further 5th position will contain 5 as 0 does not occur. The other way to solve this problem is by writing a computer program that systematically tries all possibilities. 1/3 rd of the contents of a container evaporated on the 1st day. 3/4th of the remaining contents of the container evaporated on the second day. What part of the contents of the container is left at the end of the second day? Answer Assume that contents of the container is X On the first day 1/3rd is evaporated. (1 - 1/3) of X is remaining i.e. (2/3)X On the Second day 3/4th is evaporated. Hence, (1- 3/4) of (2/3)X is remaining i.e. (1/4)(2/3)X = (1/6) X Hence 1/6th of the contents of the container is remaining There are four people in a room (not including you). Exactly two of these four always tell the truth. The other two always lie. You have to figure out who is who IN ONLY 2 QUESTIONS. Your questions have to be YES or NO questions and can only be answered by one person. (If you ask the same question to two different people then that counts as two questions). Keep in mind that all four know each other's characteristics whether they lie or not. What questions would you ask to figure out who is who? Remember that you can ask only 2 questions. Submitted

239

You have 3 baskets, & each one contains exactly 4 balls, each of which is of the same size. Each ball is either red, black, white, or purple, & there is one of each color in each basket. If you were blindfolded, & lightly shook each basket so that the balls would be randomly distributed, & then took 1 ball from each basket, what chance is there that you would have exactly 2 red balls? Answer There are 64 different possible outcomes, & in 9 of these, exactly 2 of the balls will be red. There is thus a slightly better than 14% chance [(9/64)*100] that exactly 2 balls will be red. A much faster way to solve the problem is to look at it this way. There are 3 scenarios where exactly 3 balls are red: 1

2

3

----------R

R

X

R

X

R

X

R

R

X is any ball that is not red. There is a 4.6875% chance that each of these situations will occur. Take the first one, for example: 25% chance the first ball is red, multiplied by a 25% chance the second ball is red, multiplied by a 75% chance the third ball is not red. Because there are 3 scenarios where this outcome occurs, you multiply the 4.6875% chance of any one occurring by 3, & you get 14.0625% Consider a state lottery where you get to choose 8 numbers from 1 to 80, no repetiton allowed. The Lottery Commission chooses 11 from those 80 numbers, again no repetition. You win the lottery if atleast 7 of your numbers are there in the 11 chosen by the Lottery Commission. What is the probablity of winning the lottery?

240

Answer The probability of winning the lottery is two in one billion i.e. only two person can win from one billion !!! Let's find out sample space first. The Lottery Commission chooses 11 numbers from the 80. Hence, the 11 numbers from the 80 can be selected in 80C11 ways which is very very high and is equal to 1.04776 * 1013 Now, you have to select 8 numbers from 80 which can be selected in 80C8 ways. But we are interested in only those numbers which are in 11 numbers selected by the Lottery Commision. There are 2 cases. • •

You might select 8 numbers which all are there in 11 numbers choosen by the Lottery Commission. So there are 11C8 ways. Another case is you might select 7 lucky numbers and 1 non-lucky number from the remaining 69 numbers. There are ( 11C7 ) * ( 69C1 ) ways to do that.

So total lucky ways are = ( 11C8 ) + ( 11C7 ) * ( 69C1 ) = (165) + (330) * (69) = 165 + 22770 = 22935 Hence, the probability of the winning lottery is = (Total lucky ways) / (Total Sample space) = (22935) / ( 1.04776 * 1013) = 2.1889 * 10-9 i.e. 2 in a billion. Submit Answer

Users Answer (4)

BrainVista Answer

Puzzle

To move a Safe, two cylindrical steel bars 7 inches in diameter are used as rollers. How far will the safe have moved forward when the rollers have made one revolution? Answer The safe must have moved 22 inches forward. If the rollers make one revolution, the safe will move the distance equal to the circumference of the roller. Hence, the distance covered by the safe is = PI * Diameter (or 2 * PI * Radius) = PI * 7 = 3.14159265 * 7 = 21.99115 = 22 inches approx. SubmittIf a rook and a bishop of a standard chess set are randomly placed on a chessboard, what is the probability that one is attacking the other? Note that both are different colored pieces. SubmAnswer The probability of either the Rook or the Bishop attacking the other is 0.3611 241

A Rook and a Bishop on a standard chess-board can be arranged in 64P2 = 64*63 = 4032 ways Now, there are 2 cases - Rook attacking Bishop and Bishop attacking Rook. Note that the Rook and the Bishop never attack each other simultaneously. Let's consider both the cases one by one. Case I - Rook attacking Bishop The Rook can be placed in any of the given 64 positions and it always attacks 14 positions. Hence, total possible ways of the Rook attacking the Bishop = 64*14 = 896 ways Case II - Bishop attacking Rook View the chess-board as a 4 co-centric hollow squares with the outermost square with side 8 units and the innermost square with side 2 units. If the bishop is in one of the outer 28 squares, then it can attack 7 positions. If the bishop is in one of the 20 squares at next inner-level, then it can attack 9 positions. Similarly if the bishop is in one of the 12 squares at next inner-level, then it can attack 11 positions. And if the bishop is in one of the 4 squares at next inner-level (the innermost level), then it can attack 13 positions. Hence, total possible ways of the Bishop attacking the Rook = 28*7 + 20*9 + 12*11 + 4*13 = 560 ways Thus, the required probability is = (896 + 560) / 4032 = 13/36 = 0.3611 itted ed

Here in England McDonald's has just launched a new advertising campaign. The poster shows 8 McDonald's products and underneath claims there are 40312 combinations of the above items. Given that the maximum number of items allowed is 8, and you are allowed to have less than 8 items, and that the order of purchase does not matter (i.e. buying a burger and fries is the same as buying fries and a burger) How many possible combinations are there? Are McDonald's correct in claiming there are 40312 combinations? Answer Total possible combinations are 12869. It is given that you can order maximum of 8 items and you are allowed to have less than 8 items. Also, the order of purchase does not matter. Let's create a table for ordering total N items using X products. Items Ordered (N)

242

Products Used (X) 1

2

3

4

5

6

7

8

1

1

-

-

-

-

-

-

-

2

1

1

-

-

-

-

-

-

3

1

2

1

-

-

-

-

-

4

1

3

3

1

-

-

-

-

5

1

4

6

4

1

-

-

-

6

1

5

10

10

5

1

-

-

7

1

6

15

20

15

6

1

-

8

1

7

21

35

35

21

7

1

Total (T)

8

28

56

70

56

28

8

1

Ways to choose 8C1 8C2 X products from 8 products (W)

8C3

8C4

8C5 8C6 8C7

8C8

Total combinations (T*W)

64

784 3136 4900 3136

784

64

1

Thus, total possible combinations are = 64 + 784 + 3136 + 4900 + 3136 + 784 + 64 + 1 = 12869 What are the chances that at least two out of a group of fifty people share the same birthday? SubmittedAnswer The probability of atleast two out of a group of 50 people share the same birthday is 97% Probability of atleast two share the same birthday = 1 - probability of all 50 have different birthdays Probability of all 50 have different birthday = 365/365 * 364/365 * 363/365 * ... * 317/365 * 316/365 = (365 * 364 * 363 * 362 * ... * 317 * 316)/36550 = 0.0296264 Probability of atleast two share the same birthday = 1 - 0.0296264 = 0.9703735 = 97% approx. Thus, the probability of atleast two out of a group of 50 people share the same birthday is 97% This explains why in a school/college with classrooms of 50 students, there are at least two students with a birthday on the same day of the year. Also, if there are 23 people in the room, then there are 50% chances that atleast two of them have a birthday on the same day of the year!!! A tank can be filled by pipe A in 30 minutes and by pipe B in 24 minutes. Outlet pipe C can empty the full tank in X minutes. If the tank is empty initially and if all the three pipes A, B and C are opened simultaneously, the tank will NEVER be full. Give the maximal possible value of X. Answer The maximum possible value of X is 13 minutes 20 seconds. 243

In one minute, pipe A can fill 1/30 part of the tank. pipe B can fill 1/24 part of the tank. Thus, the net water level increase in one minute is = 1/30 + 1/24 = 3/40 part of the tank In order to keep the tank always empty, outlet pipe C should empty at least 3/40 part of the tank in one minute. Thus, pipe C can empty the full tank in 40/3 i.e. 13 minutes 20 seconds. A worker earns a 5% raise. A year later, the worker receives a 2.5% cut in pay, & now his salary is Rs. 22702.68 What was his salary to begin with? Answer Rs.22176 Assume his salary was Rs. X He earns 5% raise. So his salary is (105*X)/100 A year later he receives 2.5% cut. So his salary is ((105*X)/100)*(97.5/100) which is Rs. 22702.68 Hence, solving equation ((105*X)/100)*(97.5/100) = 22702.68 X = 22176 500 men are arranged in an array of 10 rows and 50 columns according to their heights. Tallest among each row of all are asked to come out. And the shortest among them is A. Similarly after resuming them to their original positions, the shortest among each column are asked to come out. And the tallest among them is B. Now who is taller A or B ? A person wanted to withdraw X rupees and Y paise from the bank. But cashier made a mistake and gave him Y rupees and X paise. Neither the person nor the cashier noticed that. After spending 20 paise, the person counts the money. And to his surprise, he has double the amount he wanted to withdraw. Find X and Y. (1 Rupee = 100 Paise)

244

As given, the person wanted to withdraw 100X + Y paise. But he got 100Y + X paise. After spending 20 paise, he has double the amount he wanted to withdraw. Hence, the equation is 2 * (100X + Y) = 100Y + X - 20 200X + 2Y = 100Y +X - 20 199X - 98Y = -20 98Y - 199X = 20 Now, we got one equation; but there are 2 variables. We have to apply little bit of logic over here. We know that if we interchange X & Y, amount gets double. So Y should be twice of X or one more than twice of X i.e. Y = 2X or Y = 2X+1 Case I : Y=2X Solving two equations simultaneously 98Y - 199X = 20 Y - 2X = 0 We get X = - 20/3 & Y = - 40/2 Case II : Y=2X+1 Solving two equations simultaneously 98Y - 199X = 20 Y - 2X = 1 We get X = 26 & Y = 53 Now, its obvious that he wanted to withdraw Rs. 26.53 Submit Answer

Users Answer (2)

BrainVista Answer

Puzzle

At the Party: 1. There were 9 men and children. 2. There were 2 more women than children. 3. The number of different man-woman couples possible was 24. Note that if there were 7 men and 5 women, then there would have been 35 man-woman couples possible. Also, of the three groups - men, women and children - at the party: 4. There were 4 of one group. 5. There were 6 of one group. 6. There were 8 of one group. Exactly one of the above 6 statements is false. Can you tell which one is false? Also, how many men, women and children are there at the party? Answer Statement (4) is false. There are 3 men, 8 women and 6 children. 245

Assume that Statements (4), (5) and (6) are all true. Then, Statement (1) is false. But then Statement (2) and (3) both can not be true. Thus, contradictory to the fact that exactly one statement is false. So Statement (4) or Statement (5) or Statement (6) is false. Also, Statements (1), (2) and (3) all are true. From (1) and (2), there are 11 men and women. Then from (3), there are 2 possible cases - either there are 8 men and 3 women or there are 3 men and 8 women. If there are 8 men and 3 women, then there is 1 child. Then Statements (4) and (5) both are false, which is not possible. Hence, there are 3 men, 8 women and 6 children. Statement (4) is false. Brain Teaser No : 00242

There is a shortage of tubelights, bulbs and fans in a village - Kharghar. It is found that • • • • •

All houses do not have either tubelight or bulb or fan. exactly 19% of houses do not have just one of these. atleast 67% of houses do not have tubelights. atleast 83% of houses do not have bulbs. atleast 73% of houses do not have fans.

What percentage of houses do not have tubelight, bulb and fan?

Answer 42% houses do not have tubelight, bulb and fan. Let's assume that there are 100 houses. Hence, there should be total 300 items i.e. 100 tubelights, 100 bulbs and 100 fans. From the given data, we know that there is shortage of atleast (67+83+73) 223 items in every 100 houses. Also, exactly 19 houses do not have just one item. It means that remaining 81 houses should account for the shortage of remaining (223-19) 204 items. If those remaining 81 houses do not have 2 items each, there would be a shortage of 162 items. But total of 204 items are short. Hence, atleast (204-162) 42 houses do not have all 3 items - tubelight, bulb and fan. Thus, 42% houses do not have tubelight, bulb and fan. What is the remainder left after dividing 1! + 2! + 3! + … + 100! By 7? Think carefully !!! Answer A tricky one. 246

7! onwards all terms are divisible by 7 as 7 is one of the factor. So there is no remainder left for those terms i.e. remainder left after dividing 7! + 8! + 9! + ... + 100! is 0. The only part to be consider is = 1! + 2! + 3! + 4! + 5! + 6! = 1 + 2 + 6 + 24 + 120 + 720 = 873 The remainder left after dividing 873 by 7 is 5 Hence, the remainder is 5. Imagine that you have 26 constants, labelled A through Z. Each constant is assigned a value in the following way: A = 1; the rest of the values equal their position in the alphabet (B corresponds to the second position so it equals 2, C = 3, etc.) raised to the power of the preceeding constant value. So, B = 2 ^ (A's value), or B = 2^1 = 2. C = 3^2 = 9. D = 4^9, etc. Find the exact numerical value to the following equation: (X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z) Answer (X - A) * (X - B) * (X - C) * ... * (X - Y) * (X - Z) equals 0 since (X - X) is zero If three babies are born every second of the day, then how many babies will be born in the year 2001? SuAnswer 9,46,08,000 babies The total seconds in year 2001 = 365 days/year * 24 hours/day * 60 minutes/hours * 60 seconds/minute = 365 * 24 * 60 * 60 seconds = 3,15,36,000 seconds Thus, there are 3,15,36,000 seconds in the year 2001. Also, three babies born are every second. Hence, total babies born = 3 * 3,15,36,000 seconds = 9,46,08,000bmitted Replace the letters with the correct numbers. T W O X

T W O

--------T H R E E Submitted by : Timmy Chan

Answer T=1, W=3, O=8, H=9, R=2, E=4 1 3 8 x 247

1 3 8

-----------1 9 0 4 4

You can reduce the number of trials. T must be 1 as there is multiplication of T with T in hundred's position. Also, O can not be 0 or 1. Now, you have to find three digit number whose square satisfies above conditions and square of that has same last two digits. Hence, it must be between 102 and 139. Brain Teaser No : 00052

Four words add up to a fifth word numerically: mars venus uranus saturn -------- + neptune Each of the ten letters (m, a, r, s, v, e, n, u, t, and p) represent a unique number from the range 0 .. 9. Furthermore, numbers 1 and 6 are being used most frequently. Answer The easiest way to solve this problem is by writing a computer program that systematically tries all possible mappings from the numbers onto the letters. This will give you only one solution which meets the condition that numbers 1 and 6 are most frequently used. mars

m = 4

venus

a = 5

uranus

r = 9

saturn

s = 3

-------- +

v = 2

4593

neptune

e = 0

20163

n = 1

695163

u = 6

358691

t = 8

-------- +

p = 7

1078610

248

There are 4 army men. They have been captured by a rebel group and have been held at ransom. An army intelligent officer orders them to be burried deep in dirt up to their necks. The format of their burrial are as shown in the figure. Conditions • • • • • •

They each have hats on their heads. either black(b) or white (w) look at diagram above. There are total 2 white hats and 2 black hats. They only look in front of them not behind. They are not allowed to communicate by talking. Between army man 1 and 2, there is a wall. Captive man 4 can see the colour of hats on 2 and 3 3 can only see 2's hat 2 can only see a wall and 1 can see a wall too, but is on the other side

The officer speaks up, "If one of you can correctly tell me the colour of your hat, you will all go scott free back to your contries. If you are wrong, you will all be killed. How can one of them be certain about the hat they are wearing and not risk the lives of their fellow souldiers by taking a 50/50 guess! Submitted

Answer Either soldier 3 or soldier 4 can save the life as soldier 1 and soldier 2 can not see colour of any hat, even not their own.. In our case soldier 3 will tell the colour of his hat. Soldier 4 can see the hat on soldier 2 and soldier 3. If both are white, then he can be sure about colour of his hat which will be black and vice-versa. But if one of them is white and one is black, then soldier 4 can not say anything as he can have either of them. So he will keep mum. If soldier 4 won't say anyhing for a while, then soldier 3 will know that soldier 4 is not in position to tell the colour of hat on his hat. It means that colour of soldier 3's hat is opposite of colour of soldier 2's hat. So soldier 3 can tell correctly the colour of hat on his head which is Black. Here, we are assuming that all the soldiers are intelligent enough. Also, this solution will work for any combination of 2 Black hats and 2 White hats. One side of the bottom layer of a triangular pyramid has 12 balls. How many are there in the whole pyramid? Note that the pyramid is equilateral and solid. Answer There are total 364 balls. As there are 12 balls along one side, it means that there are 12 layers of balls. The top most layer has 1 ball. The second layer has 3 (1+2) balls. The third layer has 6 (1+2+3) balls. The fourth layer has 10 (1+2+3+4) balls. The fifth layer has 15 (1+2+3+4+5) balls. Similarly, there are 21, 28, 36, 45, 55, 66 and 78 balls in the remaining layers. Hence, the total number of balls are = 1 + 3 + 6 + 10 + 15 + 21 + 28 + 36 + 45 + 55 + 66 + 78 = 364 balls A blindfolded man is asked to sit in the front of a carrom board. The holes of the board are shut 249

with lids in random order, i.e. any number of all the four holes can be shut or open. Now the man is supposed to touch any two holes at a time and can do the following. • • •

Open the closed hole. Close the open hole. Let the hole be as it is.

After he has done it, the carrom board is rotated and again brought to some position. The man is again not aware of what are the holes which are open or closed. How many minimum number of turns does the blindfolded man require to either open all the holes or close all the holes? Note that whenever all the holes are either open or close, there will be an alarm so that the blindfolded man will know that he has won. Submitted

Answer The blindfolded man requires 5 turns. 1. Open two adjacent holes. 2. Open two diagonal holes. Now atleast 3 holes are open. If 4th hole is also open, then you are done. If not, the 4th hole is close. 3. Check two diagonal holes. o If one is close, open it and all the holes are open. o If both are close, open any one hole. Now, two holes are open and two are close. The diagonal holes are in the opposite status i.e. in both the diagonals, one hole is open and one is close.

4. Check any two adjacent holes. o If both are open, close both of them. Now, all holes are close. o If both are close, open both of them. Now, all holes are open. o If one is open and one is close, invert them i.e. close the open hole and open the close hole. Now, the diagonal holes are in the same status i.e. two holes in one diagonal are open and in other are close.

5. Check any two diagonal holes. o If both are open, close both of them. Now, all holes are close. o If both are close, open both of them. Now, all holes are open.

In the middle of the confounded desert, there is the lost city of "Ash". To reach it, I will have to travel overland by foot from the coast. On a trek like this, each person can only carry enough rations for five days and the farthest we can travel in one day is 30 miles. Also, the city is 120 miles from the starting point. 250

What I am trying to figure out is the fewest number of persons, including myself, that I will need in our Group so that I can reach the city, stay overnight, and then return to the coast without running out of supplies. How many persons (including myself) will I need to accomplish this mission? Answer Total 4 persons (including you) required. It is given that each person can only carry enough rations for five days. And there are 4 persons. Hence, total of 20 days rations is available.

1. First Day : 4 days of rations are used up. One person goes back using one day of rations 2. 3. 4.

for the return trip. The rations remaining for the further trek is for 15 days. Second Day : The remaining three people use up 3 days of rations. One person goes back using 2 days of rations for the return trip. The rations remaining for the further trek is for 10 days. Third Day : The remaining two people use up 2 days of rations. One person goes back using 3 days of rations for the return trip. The rations remaining for the further trek is for 5 days. Fourth Day : The remaining person uses up one day of rations. He stays overnight. The next day he returns to the coast using 4 days of rations.

Thus, total 4 persons, including you are required. At what time after 4.00 p.m. is the minutes hand of a clock exactly aligned with the hour hand? Answer 4:21:49.5 Assume that X minutes after 4.00 PM minute hand exactly aligns with and hour hand. For every minute, minute hand travels 6 degrees. Hence, for X minutes it will travel 6 * X degrees. For every minute, hour hand travels 1/2 degrees. Hence, for X minutes it will travel X/2 degrees. At 4.00 PM, the angle between minute hand and hour hand is 120 degrees. Also, after X minutes, minute hand and hour hand are exactly aligned. So the angle with respect to 12 i.e. Vertical Plane will be same. Therefore, 6 * X = 120 + X/2 12 * X = 240 + X 11 * X = 240 X = 21.8182 X = 21 minutes 49.5 seconds Hence, at 4:21:49.5 minute hand is exactly aligned with the hour hand. Substitute digits for the letters to make the following Division true O U T ------------251

S T E M | D E M I S E | D M O C ------------T U I S S T E M ---------Z Z Z E Z U M M -------I S T Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter M, no other letter can be 3 and all other M in the puzzle must be 3. Submitted by : Calon

Answer C=0, U=1, S=2, T=3, O=4, M=5, I=6, Z=7, E=8, D=9 It is obvious that U=1 (as U*STEM=STEM) and C=0 (as I-C=I). S*O is a single digit and also S*T is a single digit. Hence, their values (O, S, T) must be 2, 3 or 4 (as they can not be 0 or 1 or greater than 4). Consider, STEM*O=DMOC, where C=0. It means that M must be 5. Now, its simple. O=4, S=2, T=3, E=8, Z=7, I=6 and D=9. O U T 4 1 3 -------------

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

S T E M | D E M I S E

2 3 8 5 | 9 8 5 6 2 8

252

| D M O C

| 9 5 4 0

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

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

T U I S

3 1 6 2

S T E M

2 3 8 5

----------

----------

Z Z Z E

7 7 7 8

Z U M M

7 1 5 5

--------

--------

I S T Also, when arranged from 0 to 9, it spells CUSTOMIZED.

6 2 3

Brain Teaser No : 00015

In the town called Alibaug, the following facts are true: • • •

No two inhabitants have exactly the same number of hairs. No inhabitants has exactly 2025 hairs. There are more inhabitants than there are hairs on the head of any one inhabitants.

What is the largest possible number of the inhabitants of Alibaug? Answer 2025 It is given that no inhabitants have exactly 2025 hairs. Hence there are 2025 inhabitants with 0 to 2024 hairs in the head. Suppose there are more than 2025 inhabitants. But these will violate the condition that "There are more inhabitants than there are hairs on the head of any one inhabitants." As for any number more than 2025, there will be same number of inhabitants as the maximum number of hairs on the head of any inhabitant. There are four groups of Mangoes, Apples and Bananas as follows: Group I : 1 Mango, 1 Apples and 1 Banana Group II : 1 Mango, 5 Apples and 7 Bananas Group III : 1 Mango, 7 Apples and 10 Bananas Group IV : 9 Mango, 23 Apples and 30 Bananas Group II costs Rs 300 and Group III costs Rs 390. Can you tell how much does Group I and Group IV cost? Answer Group I costs Rs 120 and Group IV costs Rs 1710 Assume that the values of one mango, one apple and one banana are M, A and B respectively. From Group II : M + 5A + 7B = 300 From Group III : M + 7A + 10B = 390 Subtracting above to equations : 2A + 3B = 90 For Group I : =M+A+B = (M + 5A + 7B) - (4A + 6B) = (M + 5A + 7B) - 2(2A + 3B) = 300 - 2(90) = 300 - 180 = 120 Similarly, for Group IV : = 9M + 23A + 30B 253

= 9(M + 5A + 7B) - (22A + 33B) = 9(M + 5A + 7B) - 11(2A + 3B) = 9(300) - 11(90) = 2700 - 990 = 1710 Thus, Group I costs Rs 120 and Group IV costs Rs 1710. Tic-Tac-Toe is being played. One 'X' has been placed in one of the corners. No 'O' has been placed yet. Where does the player that is playing 'O' has to put his first 'O' so that 'X' doesn't win? Assume that both players are very intelligent. Explain your answer Answer "O" should be placed in the center. Let's number the positions as: 1 | 2 | 3 --------4 | 5 | 6 --------7 | 8 | 9 It is given that "X" is placed in one of the corner position. Let's assume that its at position 1. Now, let's take each position one by one. • • • • • • •

If "O" is placed in position 2, "X" can always win by choosing position 4, 5 or 7. If "O" is placed in position 3, "X" can always win by choosing position 4, 7 or 9. If "O" is placed in position 4, "X" can always win by choosing position 2, 3 or 5. If "O" is placed in position 6, "X" can always win by choosing position 3, 5 or 7. If "O" is placed in position 7, "X" can always win by choosing position 2, 3 or 9. If "O" is placed in position 8, "X" can always win by choosing position 3, 5 or 7. If "O" is placed in position 9, "X" can always win by choosing position 3, or 7.

If "O" is placed in position 5 i.e. center position, "X" can't win unless "O" does something foolish ;)) Hence, "O" should be placed in the center. Amit, Bhavin, Himanshu and Rakesh are sitting around a table. • • • •

The Electonics Engineer is sitting to the left of the Mechanical Engineer. Amit is sitting opposite to Computer Engineer. Himanshu likes to play Computer Games. Bhavin is sitting to the right of the Chemical Engineer.

Can you figure out everyone's profession? Answer 254

Amit is the Mechanical Engineer. Bhavin is the Computer Engineer. Himanshu and Rakesh are either Chemical Engineer or Elecronics Engineer. Amit and Bhavin are sitting opposite to each other. Whereas Chemical Engineer and Elecronics Engineer are sitting opposite to each other. We cannot find out who is Chemical Engineer and Elecronics Engineer as data provided is not sufficient Five friends with surname Batliwala, Pocketwala, Talawala, Chunawala and Natakwala have their first name and middle name as follow. 1. 2. 3. 4. 5. 6.

Four of them have a first and middle name of Paresh. Three of them have a first and middle name of Kamlesh. Two of them have a first and middle name of Naresh. One of them have a first and middle name of Elesh. Pocketwala and Talawala, either both are named Kamlesh or neither is named Kamlesh. Either Batliwala and Pocketwala both are named Naresh or Talawala and Chunawala both are named Naresh. 7. Chunawala and Natakwala are not both named Paresh. Who is named Elesh? Answer Pocketwala is named Elesh. From (1) and (7), it is clear that Batliwala, Pocketwala and Talawala are named Paresh. From (6) and (5), if Pocketwala or Talawala both are named Kamlesh, then either of them will have three names i.e. Paresh, Kamlesh and Naresh. Hence, Pocketwala and Talawala both are not named Kamlesh. It means that Batliwala, Chunawala and Natakwala are named Kamlesh. Now it is clear that Talawala and Chunawala are named Naresh. Also, Pocketwala is named Elesh. Mr. Wagle goes to work by a bus. One day he falls asleep when the bus still has twice as far to go as it has already gone. Halfway through the trip he wakes up as the bus bounces over some bad potholes. When he finally falls asleep again, the bus still has half the distance to go that it has already travelled. Fortunately, Mr. Wagle wakes up at the end of his trip. What portion of the total trip did Mr. Wagle sleep? Answer Mr. wagle slept through half his trip. Let's draw a timeline. Picture the bus route on a line showen below: ---------------- ________ -------- ________________ Start

255

1/3

1/2

2/3

End

----- shows time for which Mr. Wagle was not sleeping _____ shows time for which Mr. Wagle was sleeping

When Mr. Wagle fell asleep the first time, the bus sill had twice as far to go as it had already gone, that marks the first third of his trip. He wake up halfway through the trip i.e slept from 1/3 mark to the 1/2 mark. He fell sleep again when the bus still had half the distance to go that it had already traveled i.e 2/3 mark. Adding up, all sleeping times, = (1/2 - 1/3) + (1 - 2/3) = 1/6 + 1/3 = 1/2 Hence, Mr. wagle slept through half his trip. Brain Teaser No : 00068

In your sock drawer, you have a ratio of 5 pairs of blue socks, 4 pairs of brown socks, and 6 pairs of black socks. In complete darkness, how many socks would you need to pull out to get a matching pair of the same color? 4 If you don't agree, try it yourself! You have a bucket of jelly beans. Some are red, some are blue, and some green. With your eyes closed, pick out 2 of a like color. How many do you have to grab to be sure you have 2 of the same? You have a bucket of jelly beans. Some are red, some are blue, and some green. With your eyes closed, pick out 2 of a like color. How many do you have to grab to be sure you have 2 of the same? If you select 4 Jelly beans you are guarenteed that you will have 2 that are the same color. There are 70 employees working with BrainVista of which 30 are females. Also, • • • • •

30 employees are married 24 employees are above 25 years of age 19 married employees are above 25 years, of which 7 are males 12 males are above 25 years of age 15 males are married.

How many unmarried females are there and how many of them are above 25? Answer 256

15 unmarried females & none are above 25 years of age. Simply put all given information into the table structure and you will get the answer. Married

Unmarried

Below 25 Above 25 Below 25

Above 25

Female

3

12

15

0

Male

8

7

20

5

There is a safe with a 5 digit number as the key. The 4th digit is 4 greater than the second digit, while the 3rd digit is 3 less than the 2nd digit. The 1st digit is thrice the last digit. There are 3 pairs whose sum is 11. Find the number. Answer 65292 As per given conditions, there are three possible combinations for 2nd, 3rd and 4th digits. They are (3, 0, 7) or (4, 1, 8) or (5, 2, 9) It is given that there are 3 pairs whose sum is 11. All possible pairs are (2, 9), (3, 8), (4, 7), (5, 6). Now required number is 5 digit number and it contains 3 pairs of 11. So it must not be having 0 and 1 in it. Hence, the only possible combination for 2nd, 3rd and 4th digits is (5, 2, 9) Also, 1st digit is thrice the last digit. The possible combinations are (3, 1), (6, 2) and (9, 3), out of which only (6, 2) with (5, 2, 9) gives 3 pairs of 11. Hence, the answer is 65292. My friend collects antique stamps. She purchased two, but found that she needed to raise money urgently. So she sold them for Rs. 8000 each. On one she made 20% and on the other she lost 20%. How much did she gain or lose in the entire transaction? Answer She lost Rs 666.67 Consider the first stamp. She mades 20% on it after selling it for Rs 8000. So the original price of first stamp is = (8000 * 100) / 80 = Rs 6666.67 Similarly, consider second stamp. She lost 20% on it after selling it for Rs 8000 So the original price of second stamp is = (8000 * 100) / 80 = Rs 10000 Total buying price of two stamps = Rs 6666.67 + Rs 10000 = Rs 16666.67 Total selling price of two stamps 257

= Rs 8000 + Rs 8000 = Rs 16000 Hence, she lost Rs 666.67 Assume for a moment that the earth is a perfectly uniform sphere of radius 6400 km. Suppose a thread equal to the length of the circumference of the earth was placed along the equator, and drawn to a tight fit. Now suppose that the length of the thread is increased by 12 cm, and that it is pulled away uniformly in all directions. By how many cm. will the thread be separated from the earth's surface? Answer The cicumference of the earth is = 2 * PI * r = 2 * PI * 6400 km = 2 * PI * 6400 * 1000 m = 2 * PI * 6400 * 1000 * 100 cm = 1280000000 * PI cm where r = radius of the earth, PI = 3.141592654 Hence, the length of the thread is = 1280000000 * PI cm Now length of the thread is increasd by 12 cm. So the new length is = (1280000000 * PI) + 12 cm This thread will make one concentric circle with the earth which is slightly away from the earth. The circumfernce of that circle is nothing but (1280000000 * PI) + 12 cm Assume that radius of the outer circle is R cm Therefore, 2 * PI * R = (1280000000 * PI) + 12 cm Solving above equation, R = 640000001.908 cm Radius of the earth is r = 640000000 cm Hence, the thread will be separatedfrom the earth by = R - r cm = 640000001.908 - 640000000 = 1.908 cm Scientist decided to do a study on the population growth of rabbits. Inside a controlled environment, 1000 rabbits were placed. Six months later, there were 1000Z rabbits. At the beginning of the 3rd year, there were roughly 2828Z rabbits, which was 4 times what the scientists placed in there at the beginning of the 1st year. If Z is a positive variable, how many rabbits would be there at the beginning of the 11th year? SubmiAnswer At the beginning of the 11th year, there would be 1,024,000 rabbits. 258

At the beginning, there were 1000 rabbits. Also, there were 4000 rabbits at the beginning of third year which is equal to 2828Z. Thus, Z = 4000/2828 i.e. 1.414 (the square root of 2) Note that 2828Z can be represented as 2000*Z*Z (Z=1.414), which can be further simplified as 1000*Z*Z*Z*Z Also, it is given that at the end of 6 months, there were 1000Z rabbits. It is clear that the population growth is 1.414 times every six months i.e. 2 times every year. After N years, the population would be 1000*(Z^(2N)) i.e. 1000*(2^N) Thus, at the beginning of the 11th year (i.e. after 10 years), there would be 1000*(2^10) i.e. 1,024,000 rabbits. tted

A class of 100 students. 24 of them are girls and 32 are not. Which base am I using? Answer Let the base be X. Therefore (X*X + X*0 + 0) = (2*X +4) + (3*X + 2) X*X = 5*X + 6 X*X - 5*X -6 = 0 (X-6)(X+1) = 0 Therefore base is 6 A man is stranded on a desert island. All he has to drink is a 20oz bottle of sprite. To conserve his drink he decides that on the first day he will drink one oz and the refill the bottle back up with water. On the 2nd day he will drink 2oz and refill the bottle. On the 3rd day he will drink 3oz and so on... By the time all the sprite is gone, how much water has he drunk? SubmittAnswer The man drunk 190oz of water. It is given that the man has 20oz bottle of sprite. Also, he will drink 1oz on the first day and refill the bottle with water, will drink 2oz on the second day and refill the bottle, will drink 3oz on the third day and refill the bottle, and so on till 20th day. Thus at the end of 20 days, he must have drunk (1 + 2 + 3 + 4 + ..... +18 + 19 + 20) = 210oz of liquid. Out of that 210oz, 20oz is the sprite which he had initially. Hence, he must have drunk 190oz of water.ed You have four 9's and you may use any of the (+, -, /, *) as many times as you like. I want to see a mathematical expression which uses the four 9's to = 100 How many such expressions can you make? Submitted

Answer There are 5 such expressions. 99 + (9/9) = 100 259

(99/.99) = 100 (9/.9) * (9/.9) = 100 ((9*9) + 9)/.9 = 100 (99-9)/.9 = 100 Two planes take off at the same exact moment. They are flying across the Atlantic. One leaves New York and is flying to Paris at 500 miles per hour. The other leaves Paris and is flying to New York at only 450 miles per hour ( because of a strong head wind ). Which one will be closer to Paris when they meet? They will both be the same distance from Paris when they meet!!! 12 members were present at a board meeting. Each member shook hands with all of the other members before & after the meeting. How many hand shakes were there? Answer 132 Think of it this way: the first person shakes hands with 11 people, the second person also shakes hands with 11 people, but you only count 10, because the hand shake with the first person was already counted. Then add 9 for the third person, 8 for the fourth, & so on. 66 hand shakes took place before & 66 after the meeting, for a total of 132. Arrange five planets such that 4 of them add up to 5th planet numerically. Each of the letters of the planet should represent a unique number from the range 0 - 9. You have to use all ten digits. There is an amazing mathematical relationship exists among the names of the planet. Answer The tought process is initially to find planets such that the total number of alphabets in them is 10. The only possible combination of planets is Saturn, Uranus, Venus, Mars and Neptune because for other combinations there will be more than 10 alphabets. Among these five, Neptune is the lenghtiest, so it must be the sum of the other four. S A T U R N U R A N U S V E N U S +

M A R S -------------N E P T U N E

Now the only possible value for N is 1. By finding the value for S, we can reach the result: 260

3 5 8 6 9 1 6 9 5 1 6 3 2 0 1 6 3 +

4 5 9 3 -------------1 0 7 8 6 1 0

You have 14 apples. Your Friend Marge takes away 3 and gives you 2. You drop 7 but pick up 4. Bret takes 4 and gives 5. You take one from Marge and give it to Bret in exchange for 3 more. You give those 3 to Marge and she gives you an apple and an orange. Frank comes and takes the apple Marge gave you and gives you a pear. You give the pear to Bret in exchange for an apple. Frank then takes an apple from Marge, gives it to Bret for an orange, gives you the orange for an apple. How many pears do you have? Submitted

Answer None Frank gave you a pear in exchange of the apple which Marge gave you. And you gave that pear to Bret in exchange for an apple. All the others exchanges involved apples and/or organges. Four couples are going to the movie. Each row holds eight seats. Betty and Jim don't want to sit next to Alice and Tom. Alice and Tom don't want to sit next to Gertrude and Bill. On the otherhand, Sally and Bob don't want to sit next to Betty and Jim. How can the couples arrange themselves in a row so that they all sit where they would like? Submitted by : Tara Smith

Answer From the given data, it can be inferred that: (Sally & Bob) NOT (Betty & Jim) NOT (Alice & Tom) NOT (Gertrude & Bill) (A) NOT (B) means A and B can not seat next to each other. Now, it is obvious that (Betty & Jim) and (Alice & Tom) will occupy the corner seats as both of them can have only one neighbour. Therefore, (Gertrude & Bill) will seat next to (Betty & Jim) (Sally & Bob) will seat next to (Gertrude & Bill) (Alice & Tom) will seat next to (Sally & Bob) Thus, there are two possible arrangements - a mirror images of each other. 1. (Betty & Jim) - (Gertrude & Bill) - (Sally & Bob) - (Alice & Tom) 2. (Alice & Tom) - (Sally & Bob) - (Gertrude & Bill) - (Betty & Jim) Substitute digits for the letters to make the following addition problem true. W H O S E T 261

E

E

T

H

A +

R

E

A

S

------------------S W O R D S Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter H, no other letter can be 3 and all other H in the puzzle must be 3. Answer It is obvious that S=1 and T=9. Also, (H + E) should be greater than 10 and hence, (E + H + E) must 20. Thus, there are 3 possible values for (E, H) pair: (6, 8) or (7, 6) or (8, 4). Use trial-n-error and everything will fit-in. W

H

O

S

E

2

8

5

1

6

T

E

E

T

H

9

6

6

9

8

A

R

E

4

7

6

A

S

4

1

+

------------------S

W

O

R

D

S

+

------------------1

2

5

7

3

1

When Socrates was imprisoned for being a disturbing influence, he was held in high esteem by his guards. All four of them hoped that something would occur that would facilitate his escape. One evening, the guard who was on duty intentionally left the cell door open so that Socrates could leave for distant parts. Socrates did not attempt to escape, as it was his philosophy that if you accept society's rules, you must also accept it's punishments. However, the open door was considered by the authorities to be a serious matter. It was not clear which guard was on that evening. The four guards make the following statements in their defense: Aaron: A) I did not leave the door open. B) Clement was the one who did it. Bob: A) I was not the one who was on duty that evening. B) Aaron was on duty. Clement: A) Bob was the one on duty that evening. B) I hoped Socrates would escape. David: A) I did not leave the door open. B) I was not surprised that Socrates did not attempt to escape. 262

Considering that, in total, three statements are true, and five statements are false, which guard is guiltyAnswer David is the guilty. Note that "All four of them hoped that something would occur that would facilitate his escape". It makes Clement's statement B True and David's statement B False. Now consider each of them as a guilty, one at a time. Aaron A

Bob

B

A

If Aaron is guilty

False False True

If Bob is guilty

True

B True

A

True

True

If David is guilty

False True

B

David A

False True True

B

True Stmts

False

4

True True

False

4

False False True True

False

5

False False True False False

3

False False False True

If Clement is guilty True True

Clement

Since in total, three statements are true and five statements are false. It is clear from the above table that David is? Brain Teaser No : 00474

Given any whole number take the sum of the digits, and the product of the digits, and multiply these together to get a new whole number. For example, starting with 6712, the sum of the digits is (6+7+1+2) = 16, and the product of the digits is (6*7*1*2) = 84. The answer in this case is then 84 x 16 = 1344. If we do this again starting from 1344, we get (1+3+4+4) * (1*3*4*4) = 576 And yet again (5+7+6) * (5*7*6) = 3780 At this stage we know what the next answer will be (without working it out) because, as one digit is 0, the product of the digits will be 0, and hence the answer will also be 0. Can you find any numbers to which when we apply the above mentioned rule repeatedly, we never end up at 0? Brain Teaser No : 00474 Given any whole number take the sum of the digits, and the product of the digits, and multiply these together to get a new whole number. For example, starting with 6712, the sum of the digits is (6+7+1+2) = 16, and the product of the digits is (6*7*1*2) = 84. The answer in this case is then 84 x 16 = 1344. If we do this again starting from 1344, we get (1+3+4+4) * (1*3*4*4) = 576 And yet again (5+7+6) * (5*7*6) = 3780 At this stage we know what the next answer will be (without working it out) because, as one digit is 0, the product of the digits will be 0, and hence the answer will also be 0.

263

Can you find any numbers to which when we apply the above mentioned rule repeatedly, we never end up at 0?

There were N stations on a railroad. After adding X stations 46 additional tickets have to be printed. Find N and X. Answer Let before adding X stations, total number of tickets t = N(N-1) After adding X stations total number of tickets are t + 46 = (N+X)(N+X-1) Subtracting 1st from 2nd 46 = (N+X)(N+X-1) - N(N-1) 46 = N2 + NX - N + NX + X2 - X - N2 + N 46 = 2NX + X2 - X 46 = (2N - 1)X + X2 X2 + (2N - 1)X - 46 = 0 Now there are only two possible factors of 46. They are (46,1) and (23,2) Case I: (46,1) 2N - 1 = 45 2N = 46 N = 23 And X = 1 Case II: (23,2) 2N - 1 = 21 2N = 22 N = 11 And X = 2 Hence, there are 2 possible answers. An emergency vehicle travels 10 miles at a speed of 50 miles per hour. How fast must the vehicle travel on the return trip if the round-trip travel time is to be 20 minutes? Answer 75 miles per hour While going to the destination, the vehicle travels 10 mils at the speed of 50 miles per hour. So the time taken to travel 10 miles is = (60 * 10) / 50 = 12 minutes Now it's given that round-trip travel time is 20 minutes. So the vehicle should complete its return trip of 10 miles in 8 minutes. So the speed of the vehicle must = (60 * 10) / 8 = 75 miles per hour 264

All of the students at a college are majoring in psychology, business, or both. 73% of the students are psychology majors, & 62% are business majors. If there are 200 students, how many of them are majoring in both psychology & business? Answer 70 students are majoring in both, psychology & business If 73% of the students are psychology majors, we know that 27% are not psychology majors. By the same reasoning, 38% are not business majors, because 62% of the students do major in business. So: 27 + 38 = 65 65% of the students are not majoring in both psychology & business, so 35% are double majors, a total of 70 students. Two trains starting at same time, one from Bangalore to Mysore and other in opposite direction arrive at their destination 1hr and 4hrs respectively after passing each other. Answer

The speed of Bangalore-Mysore train is TWICE the speed of Mysore-Bangalore train. Let the distance between Bangalore and Mysore is D kms. Also, let speed of the train from Bangalore to Mysore is X km/hr and speed of the tain from Mysore to Bangalore is Y km/hr. Now, assume that both the trains met each other at T kms from the Bangalore (point P in figure) Time taken by Bangalore-Mysore train to reach P = Time taken by Mysore-Bangalore train to reach P ( T / X ) = ( D - T ) / Y -----equ(I) Also, Bangalore-Mysore train and Mysore-Bangalore train arrive destination 1 hr and 4 hrs respectively after passing each other. It means that Bangalore-Mysore train travels (D - T) kms in 1 hr at X km/hr and Mysore-Bangalore train travels T kms in 4 hrs at Y km/hr. Hence, ( D - T ) = X and T=4*Y Substituting these values in equation I, we get (4*Y)/X=X/Y 4*Y*Y=X*X 2*Y=X Hence, the speed of Bangalore-Mysore train is TWICE the speed of Mysore-Bangalore train.How much faster is one train from other? Answer 49 times Let's assume that everyone clinked their mug with friend to his left only. It means that there are 265

total 49 clinks. Now the right clink of each person is left clink of the person on right which is already happened. Hence, there are only 49 clinks. Mrs. Watsherface had a garage sale. A custmer named Gina bought an old lamp and a rug. She paid a total of $5.25 for everything. The rug cost 25 cents more than the lamp. How much did each cost? Submitted by : Kimi

Answer The lamp cost $ 2.50 and the rug cost $ 2.75 A simple one. Assume that the lamp cost $ L. Hence the rug must have cost $ (L + 0.25) Also, total cost is $ 5.25, Hence the equation : L + L + 0.25 = 5.25 2*L=5 L = 2.50 Hence, the lamp cost $ 2.50 and the rug cost $ 2.75 Brain Teaser No : 00518

Write 1111......(243 times) i.e. a 243 digit number with all 1s. Prove that it is divisible by 243. SubmittAnswer Prove it using the mathematical induction. First here are a couple of things to note: [1] A number whose digits add up to a multiple of three is divisable by 3. e.g. 369: 3+6+9=18: 1+8=9 which is a multiple of 3 hence 369 is divisable by 3. [2] Whenever a number (X) is multiplied with another number (Y) then the product (X*Y) will have all the factors of X as well as all the factors of Y in its set of factors. e.g. if X has factors of (1,P,Q,X) and Y has factors of (1,Q,R,Y) then X*Y has factors of (1,P,Q,Q,R,X,Y). Let N = any series of digits (e.g. N=369) D = the number of digits in N (e.g. if N=369 then D=3) P = is a number constructed in the following way : a 1, followed by (D-1) 0s, followed by another 1, followed by (D-1) 0s, followed by another 1. (e.g. if N=369 then D=3 and P would be 1001001) Note that P will always be divisible by 3. Also, if we multiply N with P we are essentially repeating N for (D-1) times. e.g. if N=369 then D=3, P=1001001 and N*P=369369369 Let's start with N=111. It is clear that N is divisible by 3. (From [1]) Also, D=3 and P=1001001 N*P=111111111 (9 times) 266

The resulting number 111111111 must be divisible by 9 as N and P both are divisible by 3. Now, let's start with N=111111111. It is clear that N is divisible by 9. Also, D=9 and P=1000000001000000001 N*P=111111111... (27 times) The resulting number 1111111... (27 times) must be divisible by 27 as N is divisible by 9 and P is divisible by 3. Repeat the same procedure for N=1111111... (27 times) The resulting number 1111111... (81 times) must be divisible by 81 as N is divisible by 27 and P is divisible by 3. Similarly, for N=1111111... (81 times) The resulting number 1111111... (243 times) must be divisible by 243 as N is divisible by 81 and P is divisible by 3. Thus, 1111111... (243 times) is divisible by 243. Thanks to Ryan Hutcherson for solution !!! edKaran bought a little box of midget matches, each one inch in length. He found that he could arrange them all in the form of a triangle whose area was just as many square inches as there were matches. He then used up six of the matches, and found that with the remainder he could again construct another triangle whose area was just as many square inches as there were matches. And using another six matches he could again do precisely the same. How many matches were there in the box originally? Note that the match-box can hold maximum of 50 matches. Answer Initially, there were 42 or 36 matches in the match-box. There are 42 matches in the box with which he could form a triangle 20, 15, 7, with an area of 42 square inches. After 6 matches had been used, the remaining 36 matches would form a triangle 17, 10, 9, with an area of 36 square inches. After using another 6 matches, the remaining 30 matches would form a triangle 13, 12, 5, with an area of 30 square inches. After using another 6, the 24 remaining would form a triangle 10, 8, 6, with an area of 24 square inches. Thus, there are two possible answers. There were either 42 or 36 matches in the match-box. Also it is interesting to know that there are just 5 such triangles for which the perimeter and the area is the same (assuming all sides are integers) and they are :

1. 2. 3. 4. 5.

24 (10, 8, 6) 30 (13, 12, 5) 36 (17, 10, 9) 42 (20, 15, 7) 60 (29, 25, 6)

Find the values of each of the alphabets. 267

N O O N S O O N +

M O O N

---------J U N E Answer Using trial and error. There are 2 solutions to it and may be more. 2 4 4 2 1 4 4 2 +

5 4 4 2

---------9 3 2 6 4 1 1 4 5 1 1 4 +

0 1 1 4

---------9 3 4 2 We have to fill number from 1 to 12 at the intersection point of two or more lines. We have to construct a star using two triangle. The sum of all number lying in straight lines should be same. This can be easilty understood by the fig. and hence solved. Submitted by : Vaibhav Gupta Submit Answer

268

Users Answer (3)

BrainVista Answer

Puzzle A Friend

Add to Favourite

We have one answer where sum of all the numbers lying in straight lines is 26. If you have others, do submit them. Brain Teaser No : 00355

Montu, Bantu, Chantu and Pintu have pets. Montu says, "If Pintu and I each have a dog, then exactly one of Bantu and Chantu has a dog." Bantu says, "If Chantu and I each have a cat, then exactly one of Montu and Pintu has a dog." Chantu says, "If Montu and I each have a dog, then exactly one of Bantu and Pintu has a cat." Pintu says, "If Bantu and I each have a cat, then exactly one of Bantu and I has a dog." Only one of the four is telling the truth. Who is telling the truth?

Answer Bantu is telling the truth. For a IF-THEN statement to be false, IF part has to be true and THEN part has to be false. Since only one statement is true and remaining three are false, IF part of three statements are true & THEN part of one statement is true. Let's put the given information in table. The pet-name in the normal text represents the IF part and the pet-name in round brackets represents the THEN part. Montu Bantu Chantu Montu says

269

Dog

(Dog)

(Dog)

Pintu Dog

Bantu says Chantu says

(Dog)

Cat

Cat

(Dog)

Dog

(Cat)

Dog

(Cat)

Pintu says

Cat (Dog)

Cat (Dog)

It is clear that the IF part of the statements made by Montu, Chantu and Pintu are true as they do not contradict each other. And the IF part of the statement made by Bantu is false. Thus, Bantu is telling the truth. Montu have a Dog and may or may not have a Cat. Bantu have a Cat. Chantu have a Dog. Pintu have a Dog and a Cat. Brain Teaser No : 00520

Somebody marked the six faces of a die with the numbers 1, 2 and 3 - each number twice. The die was put on a table. Four people - Abu, Babu, Calu and Dabu - sat around the table so that each one was able to see only three sides of the die at a glance. • • •

Abu sees the number 1 and two even numbers. Babu and Calu can see three different numbers each. Dabu sees number 2 twice and he can't remember the third number.

What number is face down on the table? Answer Number 3 is face down on the table. If Abu can see two even numbers i.e. number 2 twice, and if Dabu can see number 2 twice, then number 2 must be facing up. Now everything else is simple. (see the following diagram) Dabu

Abu

1

3

2

1 270

2

Calu Babu Thus, the number hidden from the view is number 3 and hence the answer. Two identical pack of cards A and B are shuffled throughly. One card is picked from A and shuffled with B. The top card from pack A is turned up. If this is the Queen of Hearts, what are the chances that the top card in B will be the King of Hearts? Answer 52 / 2703 There are two cases to be considered. CASE 1 : King of Hearts is drawn from Pack A and shuffled with Pack B Probability of drawing King of Hearts from Pack A = 1/51 (as Queen of Hearts is not to be drawn) Probability of having King of Hearts on the top of the Pack B = 2/53 So total probability of case 1 = (1/51) * (2/53) = 2 / (51 * 53) CASE 2 : King of Hearts is not drawn from Pack A Probability of not drawing King of Hearts from Pack A = 50/51 (as Queen of Hearts is not to be drawn) Probability of having King of Hearts on the top of the Pack B = 1/53 So total probability of case 2 = (50/51) * (1/53) = 50 / (51 * 53) Now adding both the probability, the required probability is = 2 / (51 * 53) + 50 / (51 * 53) = 52 / (51 * 53) = 52 / 2703 = 0.0192378 How many possible combinations are there in a 3x3x3 rubics cube? In other words, if you wanted to solve the rubics cube by trying different combinations, how many might it take you (worst case senerio)? How many for a 4x4x4 cube? Submitted

Answer There are 4.3252 * 10^19 possible combinations for 3x3x3 Rubics and 7.4012 * 10^45 possible combinations for 4x4x4 Rubics. Let's consider 3x3x3 Rubics first. There are 8 corner cubes, which can be arranged in 8! ways. Each of these 8 cubes can be turned in 3 different directions, so there are 3^8 orientations altogether. But if you get all but one of the corner cube into chosen positions and orientations, only one of 3 orientations of the final corner cube is possible. Thus, total ways corner cubes can be placed = (8!) * (3^8)/8 = (8!) * (3^7) Similarly, 12 edge cubes can be arranged in 12! ways. 271

Each of these 12 cubes can be turned in 2 different directions, so there are 2^12 orientations altogether. But if you get all but one of the edge cube into chosen positions and orientations, only one of 2 orientations of the final edge cube is possible. Thus, total ways edge cubes can be placed = (12!) * (2^12)/2 = (12!) * (2^11) Here, we have essentially pulled the cubes apart and stuck cubes back in place wherever we please. In reality, we can only move cubes around by turning the faces of the cubes. It turns out that you can't turn the faces in such a way as to switch the positions of two cubes while returning all the others to their original positions. Thus if you get all but two cubes in place, there is only one attainable choice for them (not 2!). Hence, we must divide by 2. Total different possible combinations are = [(8!) * (3^7)] * [(12!) * (2^11)] / 2 = (8!) * (3^7) * (12!) * (2^10) = 4.3252 * 10^19 Similarly, for 4x4x4 Rubics total different possible combinations are = [(8!) * (3^7)] * [(24!)] * [(24!) / (4!^6)] / 24 = 7.4011968 * 10^45 Note that there are 24 edge cubes, which you can not turn in 2 orientations (hence no 2^24 / 2). Also, there are 4 center cubes per face i.e. (24!) / (4!^6). You can switch 2 cubes without affecting the rest of the combination as 4*4*4 has even dimensions (hence no division by 2). But pattern on one side is rotated in 4 directions over 6 faces, hence divide by 24. Brain Teaser No : 00528

Substitute digits for the letters to make the following relation true. N E V E R L +

E

A

V

E

M

E

----------------A L O N E Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter M, no other letter can be 3 and all other M in the puzzle must be 3. Answer A tough one!!! Since R + E + E = 10 + E, it is clear that R + E = 10 and neither R nor E is equal to 0 or 5. This is the only entry point to solve it. Now use trial-n-error method.

272

N

E

V

E

R

2

1

4

1

9

L

E

A

V

E

3

1

5

4

1

+

M

E

+

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

6

1

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

A L O N E 5 3 0 2 1 There are 20 people in your applicant pool, including 5 pairs of identical twins. If you hire 5 people randomly, what are the chances you will hire at least 1 pair of identical twins? (Needless to say, this could cause trouble ;)) SubmAnswer The probability to hire 5 people with at least 1 pair of identical twins is 25.28% 5 people from the 20 people can be hired in 20C5 = 15504 ways. Now, divide 20 people into two groups of 10 people each : G1 - with all twins G2 - with all people other than twins Let's find out all possible ways to hire 5 people without a single pair of indentical twins. People from G1

People from G2

No of ways to hire G1 without a single pair of indentical twins

No of ways to hire G2

0

5

10C0

10C5

252

1

4

10C1

10C4

2100

2

3

10C2 * 8/9

10C3

4800

3

2

10C3 * 8/9 * 6/8

10C2

3600

4

1

10C4 * 8/9 * 6/8 * 4/7

10C1

800

5

0

10C5 * 8/9 * 6/8 * 4/7 * 2/6

10C0

32 Total

Total ways

11584

Thus, total possible ways to hire 5 people without a single pair of indentical twins = 11584 ways So, total possible ways to hire 5 people with at least a single pair of indentical twins = 15504 11584 = 3920 ways Hence, the probability to hire 5 people with at least a single pair of indentical twins = 3920/15504 = 245/969 = 0.2528 = 25.28%itted Veeru says to Jay, "Can you figure out how many Eggs I have in my bucket?" He gives 3 clues to Jay: If the number of Eggs I have 1. is a multiple of 5, it is a number between 1 and 19 2. is not a multiple of 8, it is a number between 20 and 29 3. is not a multiple of 10, it is a number between 30 and 39 How many Eggs does Veeru have in his bucket? 273

Answer 32 eggs Let's apply all 3 condition separately and put all possible numbers together. First condition says that if multiple of 5, then the number is between 1 and 19. Hence, the possible numbers are (5, 10, 15, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39) Second condition says that if not a multiple of 8, then the number is between 20 and 29. Hence, the possible numbers are (8, 16, 20, 21, 22, 23, 25, 26, 27, 28, 29, 32) Third condition says that if not a multiple of 10, then the number is between 30 and 39. Hence, the possible numbers are (10, 20, 31, 32, 33, 34, 35, 36, 37, 38, 39) Only number 32 is there in all 3 result sets. That means that only number 32 satisfies all three conditions. Hence, Veeru have 32 eggs in his bucket. Submit Answer

Users Answer (14)

BrainV

Mr. Black, Mr. White and Mr. Grey were chatting in the Yahoo conference. They were wearing a black suit, a white suit and a grey suit, not necessarily in the same order. Mr. Grey sent message, "We all are wearing suit that are of the same color as our names but none of us is wearing a suit that is the same color as his name." On that a person wearing the white suit replied, "What difference does that make?" Can you tell what color suit each of the three persons had on? Answer Mr. Grey is wearing Black suit. Mr. White is wearing Grey suit. Mr. Black is wearing White suit. Mr. Grey must not be wearing grey suit as that is the same colour as his name. Also, he was not wearing white suit as the person wearing white suit responded to his comment. So Mr Grey must be wearing a black suit. Similarly, Mr. White must be wearing either black suit or grey suit. But Mr. Grey is wearing a black suit. Hence, Mr. White must be wearing a grey suit. And, Mr. Black must be wearing white suit. Substitute numbers for the letters so that the following mathematical expressions are correct. ABC DEF GHI --- = IE

--- = IE

--- = IE

3 6 9 Note that the same number must be used for the same letter whenever it appears. Answer A=2, B=1, C=9, D=4, E=3, F=8, G=6, H=5, I=7 274

Let's start with GHI = 9 * IE. Note that I appears on both the side. Also, after multiplying IE by 9 the answer should have I at the unit's place. The possible values of IE are 19, 28, 37, 46, 55, 64, 73, 82 and 91; out of which only 64, 73 and 82 satisfies the condition. (as all alphabet should represent different digits) Now, consider DEF = 6 * IE. Out of three short-listed values, only 73 satisfies the equation. Also, ABC = 3 * IE is satisfied by 73. Hence, A=2, B=1, C=9, D=4, E=3, F=8, G=6, H=5, I=7 219 438 657 --- = 73 3

--- = 73 6

--- = 73 9

Brain Teaser No : 00374

A, B, C and D are related to each other. • • • •

One of the four is the opposite sex from each of the other three. D is A's brother or only daughter. A or B is C's only son. B or C is D's sister.

Answer A, B & D are males; C is female. B is C's only son. A & D are C's brothers. A(male) --- C(female) --- D(male) | | B(male) Work out which relation can hold and discard the contradictory options. From (2) and (4), D can not be a only daughter and have a sister (B or C). Hence, D is A's brother i.e. D is a Male. From (4), let's say that B is D's sister i.e. B is Female. From (3), A is C's only son i.e. A is Male. But D is A's brother which means that A is not C's only son. Hence, our assumption was wrong. Thus, C is D's sister i.e. C is Female. And B must be C's only son. Now it is clear that D & B are Males and C is Female. A must be a Male as only one of them is of opposite sex from each of the other three. And he is C & D's brother.How are they related to each other? Dr. DoLittle always goes walking to the clinic and takes the same time while going and while coming back. One day he noticed something. When he left the home, the hour hand and the minute hand were exactly opposite to each other 275

and when he reached the clinic, they were together. Similarly, when he left the clinic, the hour hand and the minute hand were together and when he reached the home, they were exactly opposite to each other. How much time does Dr. DoLittle take to reach home from the clinic? Give the minimal possible answer. Answer 32 minutes 43.6 seconds In twelve hours, the minute hand and the hour hand are together for 11 times. It means that after every 12/11 hours, both the hands are together. Similarly in twelve hours, the minute hand and the hour hand are exactly opposite to each other for 11 times. It means that after every 12/11 hours, both the hands are opposite. Now, let's take an example. We know that at 12 both the hands are together and at 6 both the hands are exactly opposite to each other. After 6, both the hands are in opposition at [6+(12/11)] hours, [6+2*(12/11)] hours, [6+3*(12/11)] hours and so on. The sixth such time is [6+6*(12/11)] hours which is the first time after 12. Thus after 12, both the hands are opposite to each other at 12:32:43.6 Hence, Dr. DoLittle takes 32 minutes and 43.6 seconds to reach home from the clinic. SlowRun Express runs between Bangalore and Mumbai, For the up as well as the down journey, the train leaves the starting station at 10:00 PM everyday and reaches the destination at 11:30 PM after three days. Mr. Haani once travelled by SlowRun Express from Mumbai to Bangalore. How many SlowRun Express did he cross during his journey? Answer Mr. Haani crossed 7 SlowRun Expresses during his journey. Let's say that Mr. Haani travelled by SlowRun Express on Wednesday 10:00PM from Mumbai. The first train he would have crossed is the one scheduled to arrive at Mumbai at 11:30 PM the same day i.e. the one that left Bangalore at 10:00 PM on last Sunday. Also, he would have crossed the last train just before reaching Bangalore on Saturday. Thus, Mr. Haani must have crossed 7 SlowRun Expresses during his journey. Six cabins numbered 1-6 consecutively, are arranged in a row and are separated by thin dividers. These cabins must be assigned to six staff members based on following facts. 1. Miss Shalaka's work requires her to speak on the phone frequently throughout the day. 2. Miss Shudha prefers cabin number 5 as 5 is her lucky number. 3. Mr. Shaan and Mr. Sharma often talk to each other during their work and prefers to have adjacent cabins. 4. Mr. Sinha, Mr. Shaan and Mr. Solanki all smoke. Miss Shudha is allergic to smoke and must have non-smokers adjacent to her. 5. Mr. Solanki needs silence during work. 276

Can you tell the cabin numbers of each of them? Answer The cabins from left to right (1-6) are of Mr. Solanki, Mr. Sinha, Mr. Shaan, Mr. Sharma, Miss Shudha and Miss Shalaka. From (2), cabin number 5 is assigned to Miss Shudha. As Miss Shudha is allergic to smoke and Mr. Sinha, Mr. Shaan & Mr. Solanki all smoke, they must be in cabin numbers 1, 2 and 3 not necessarily in the same order. Also, Miss Shalaka and Mr. Sharma must be in cabin 4 and 6. From (3), Mr. Shaan must be in cabin 3 and Mr. Sharma must be in cabin 4. Thus, Miss Shalaka is in cabin 6. As Mr. Solanki needs silence during work and Mr. Shaan is in cabin 3 who often talks to Mr. Sharma during work, Mr. Solanki must be in cabin 1. Hence, Mr. Sinha is in cabin 2. Thus, the cabins numbers are 1# Mr. Solanki, 2# Mr. Sinha, 3# Mr. Shaan, 4# Mr. Sharma, 5# Miss Shudha, 6# Miss Shalaka SkyFi city is served by 6 subway lines - A, E, I, O, U and Z. • • • • • •

When it snows, morning service on line E is delayed. When it rains or snows, service on the lines A, U and Z is delayed both morning and afternoon. When the temperature drops below 20 C, afternoon service is cancelled on either line A or line O, but not both. When the temperature rises above 40 C, afternoon service is cancelled on either line I or line Z, but not both. When service on line A is delayed or cancelled, service on line I is also delayed. When service on line Z is delayed or cancelled, service on line E is also delayed.

On February 10, it snows all day with the temperature at 18C. On how many lines service will be delayed or cancelled, including both morning and afternoon? SkyFi city is served by 6 subway lines - A, E, I, O, U and Z. • • • • • •

When it snows, morning service on line E is delayed. When it rains or snows, service on the lines A, U and Z is delayed both morning and afternoon. When the temperature drops below 20 C, afternoon service is cancelled on either line A or line O, but not both. When the temperature rises above 40 C, afternoon service is cancelled on either line I or line Z, but not both. When service on line A is delayed or cancelled, service on line I is also delayed. When service on line Z is delayed or cancelled, service on line E is also delayed.

On February 10, it snows all day with the temperature at 18C. On how many lines service will be delayed or cancelled, including both morning and afternoon? 277

In a certain game, if 2 wixsomes are worth 3 changs, and 4 changs are worth 1 plut, then 6 plutes are worth how many wixsomes? Answer It is given that 2 wixsomes = 3 changs 8 wixsomes = 12 changs ----- (I) Also, given that 4 changs = 1 plut 12 changs = 3 plutes 8 wixsomes = 3 plutes ----- From (I) Therefore, 6 plutes = 16 wixsomes In a certain year, the number of girls who graduated from City High School was twice the number of boys. If 3/4 of the girls and 5/6 of the boys went to college immediately after graduation, what fraction of the graduates that year went to college immediately after graduation? Answer Assume that number of boys graduated from City High School = B Therefore, number of girls graduated from City High School = 2*B It is given that 3/4 of the girls and 5/6 of the boys went to college immediately after graduation. Hence, total students went to college = (3/4)(2*B) + (5/6)(B) = B * (3/2 + 5/6) = (7/3)B Fraction of the graduates that year went to college immediately after graduation = [(7/3)B] / [3*B] = 7/9 Therefore, the answer is 7/9 A mule and a donkey were carrying full sacks on their backs. The mule started complaining that his load was too heavy. The donkey said to him "Why are you complaining? If you gave me one of your sacks I'd have double what you have and if I give you one of my sacks we'd have an even amount." How many sacks were each of them carrying? Give the minimal possible answer. SubmittAnswer The mule was carrying 5 sacks and the donkey was carrying 7 sacks. Let's assume that the mule was carrying M sacks and the donkey was carrying D sacks. As the donkey told the mule, "If you gave me one of your sacks I'd have double what you have." D + 1 = 2 * (M-1) D + 1 = 2M - 2 D = 2M - 3 278

The donkey also said, "If I give you one of my sacks we'd have an even amount." D-1=M+1 D=M+2 Comparing both the equations, 2M - 3 = M + 2 M=5 Substituting M=5 in any of above equation, we get D=7 Hence, the mule was carrying 5 sacks and the donkey was carrying 7 sacks. edTwo people enter a race in whick you run to a point and back. Person A runs 20 mph to and from the point. Person B runs to the point going 10 mph and 30 mph going back. Who came in first? Submitted

Answer Person A came in first. Let's assume that the distance between start and the point is D miles. Total time taken by Person A to finish = (D/20) + (D/20) = D/10 = 0.1D Total time taken by Person B to finish = (D/10) + (D/30) = 2D/15 = 0.1333D Thus, Person A is the Winner.

Alternatively (if you don't like mathematics ;)), analyse the situation as follow: Note that initially speed of Person A (20 mph) was twice the speed of Person B (10 mph). Hence, when Person A (20 mph forward) reached the point, Person B (10 mph forward) was halfway. When Person A (20 mph back) finished, Person B (still 10 mph forward) reached the point. Thus, Person A wins the race and by that time Person B covers only half the distance, no matter how far the point is!!! Mark ate half of a pizza on Monday. He ate half of what was left on Tuesday and so on. He followed this pattern for one week. How much of the pizza would he have eaten during the week? Submitted

Answer Mark would have ate 127/128 (99.22%) of the pizza during the week. Mark ate half the pizza on Monday. On Tuesday, he would have ate half of the remaining pizza i.e. 1/4 of the original pizza. Similarly, he would have ate 1/8 of the original pizza on Wednesday and so on for the seven days. 279

Total pizza Mark ate during the week is = 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64 + 1/128 = 127/128 = 99.22% of the original pizza In the General meeting of "Friends Club", Sameer said, "The repairs to the Club will come to a total of Rs 3120 and I propose that this amount should be met by the members, each paying an equal amount." The proposal was immediately agreed. However, four members of the Club chose to resign, leaving the remaining members to pay an extra Rs 26 each. How many members did the Club originally have? Answer The Club originally had 24 members. Assume that there were initially N members. As 4 members resigned and remaining members paid Rs 26 each, it means that total amount of 4 members is equal to Rs 26 each from remaining (N-4) members. Thus, 4 * (3120 / N) = 26 * (N - 4) 12480 = 26N2 - 104N 26N2 - 104N - 12480 = 0

Solving the quadratic equation we get N=24. Hence, the Club originally had 24 members. Brain Teaser No : 00206

A tank can be filled by pipe A in 30 minutes and by pipe B in 24 minutes. Outlet pipe C can empty the full tank in one hour and twenty minutes. If the tank is empty initially and if all the three pipes A, B and C are opened simultaneously, in how much time will the tank be full? Answer The tank will be full in 16 minutes. In one minute, pipe A can fill 1/30 part of the tank. pipe B can fill 1/24 part of the tank. pipe C can empty 1/80 part of the tank. Thus, the net water level in one minute is = 1/30 + 1/24 - 1/80 = 15/240 part of the tank Hence, the tank will be full in 240/15 i.e. 16 minutes. A rich old Arab has three sons. When he died, he willed his 17 camels to the sons, to be divided as follows: 280

First Son to get 1/2 of the camels Second Son to get 1/3rd of the camels Third Son to get 1/9th of the camels. The sons are sitting there trying to figure out how this can possibly be done, when a very old wise man goes riding by. They stop him and ask him to help them solve their problem. Without hesitation he divides the camels properly and continues riding on his way. How did he do it? Answer The old man temporarily added his camel to the 17, making a total of 18 camels. First son got 1/2 of it = 9 Second son got 1/3 of it = 6 Third son got 1/9 of it = 2 For a total of 17. He then takes his camel back and rides away...... There were two men standing on a street. The one says to the other, "I have 3 daughters, the product of their ages is 36. What is the age of the OLDEST daughter?" The second guy says, "I need more information." So, the first guy says, "The sum of their ages is equal to the address of the house across the street." The second guy looks at the address and says, "I still need more information." So, the first guy says, "My oldest daughter wears a red dress."

281

Answer The answer is 9 years. First you need to find all the possible sets of three numbers that when multiplied equals 36: 1 1 36 1 2 18 1 3 12 149 166 229 236 334 Then you add the numbers together to find the sum 1 1 36 = 38 1 2 18 = 21 1 3 12 = 16 1 4 9 = 14 1 6 6 = 13 2 2 9 = 13 2 3 6 = 11 3 3 4 = 10 Even though we don't know the address the guy knows it. For him to need more information that means that at least two of the sets of numbers has the same sum. Two of them do, 1 6 6 and 2 2 9. When the first guy said that his OLDEST daugher wears a red dress that meant that there had to be the oldest. So 1 6 6 can't possibly be the answer. So the possible possiblity is 2 2 9 and the OLDEST daughter is 9 years old. Therefore, the answer is 9. Submit Answer

User

There are 3 colored boxes - Red, Green and Blue. Each box contains 2 envelopes. Each envelope contains money - two of them contain Rs. 25000 each, two of them contain Rs. 15000 each and remaining two contain Rs. 10000 each. There is one statement written on the cover of each box. * Red Box: Both, a red box and a blue box contain Rs. 10000 each. * Green Box: Both, a green box and a red box contain Rs. 25000 each. * Blue Box: Both, a blue box and a green box contain Rs. 15000 each. Only one of the above 3 statements is true and the corresponding box contains the maximum amount. Can you tell which box contains the maximum amount and how much? Answer Blue box contains the maximum amount Rs. 40000 As it is given that only one of the given 3 statements is true; assume in turn, each statement to be 282

true & the other 2 false and check whether the corresponding box contains the maximum amount. Let's assume that the statement on the Blue box is true. Thus, the given 3 statements can be interpreted as * Atmost one, a red box or a blue box contains Rs. 10000. * Atmost one, a green box or a red box contains Rs. 25000. * Both, a blue box and a green box contain Rs. 15000 each. Going through all possible combinations, we can conclude that Red Box : Rs. 10000 + Rs. 25000 = Rs. 35000 Green Box : Rs. 10000 + Rs. 15000 = Rs. 25000 Blue Box : Rs. 15000 + Rs. 25000 = Rs. 40000 You can test out for other two statements i.e. assuming Red box statement true and then Green box statement true. In both the cases, other statements will contradict the true statement. Sachin, Dravid and Ganguly played in a Cricket match between India and England. • • • •

None of them scored more than 99 runs. If you add the digits of the runs scored by Sachin to his own score, you will get the runs scored by Dravid. If you reverse the digits of the runs scored by Dravid, you will get the runs scored by Ganguly. The total runs scored by them is 240.

Can you figure out their individual scores? Answer Sachin, Dravid and Ganguly scored 75, 87 and 78 respectively. Sachin's score must be less than 86, otherwise Dravid's score would be more than 99. Also, he must have scored atleast 42 - incase Dravid and Ganguly scored 99 each. Also, as none of them scored more than 99 and the total runs scored by them is 240; their individual scores must be around 80. Now, use trial-n-error method to solve the teaser. Three men, including Gianni and three woman, including Sachi are in line at the BrentWood post office. Each has two different pieces of business to conduct. 1. 2. 3. 4. 5.

The first person is a woman. Carlos wants to send an overnight package. Lau is just ahead of Pimentelli who is the same sex as Lau. Gianni is two places ahead of the person who wants to buy stamps. Knutson - who is the opposite sex than Rendler - isn't the person who wanted to complain about a mail carrier. 6. The six people, not necessarily in the same order are - Anthony, Donna, the person who wants to fill out a change-of-address form, the one who wants to buy a money order, the one who wants to send Airmail to Tibet and the second person in the line. 7. The four tasks of the last two people in line, not necessarily in the same order are sending books fourth class, buying a money order, picking up a package and complaining about a mail carrier. 8. The person who wants to send books fourth class is just behind a person of the same sex. 283

9. Mary is just behind a person who wants to send an insured package. 10. The person who wants to send Airmail to Tibet is either two places ahead of or two places behind the one who wants to add postage to his or her meter. 11. Anthony isn't two places behind the who wants to pickup a registered letter. 12. Toriseza is two places ahead of the person who wants to pick up a package. 13. Knutson isn't just ahead of the person who wants to send an item parcel post. Can you figure out where each customer is in the line, his or her full name (one surname is Loti) and the two things he or she wants to accomplish? Provide your answer is POSITION - FIRST NAME - LAST NAME - BUSINESS format. Submit Answer

Answer

Users Answer (8)

A very TOUGH puzzle !!! POS FIRST NAME LAST NAME

BUSINESS

1

Sachi

Loti

• Fill Out a Change-of-Address Form • Add Postage to Meter

2

Gianni

Lau

• Pick Up a Registered Letter • Send an Item Parcel Post

3

Carlos

Pimentelli

• Overnight Package • Send Airmail to Tibet

4

Donna

Toriseza

• Buy Stamps • Send an Insured Package

5

Mary

Knutson

• Buy a Money Order • Send Books fourth Class

6

Anthony

Rendler

• Complain About a Mail Carrier • Pick Up a Package

Brain Teaser No : 00164

Substitute digits for the letters to make the following relation true. W O R L D +

T R A D E

------------C E N T E R Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter W, no other letter can be 3 and all other W in the puzzle must be 3.

Answer A tough one. 284

It is obvious that C=1. Also, the maximum possible value of E is 7. Now, start putting possible values of D, E and R as they occure frequently and use trial-n-error. W O R L D +

T R A D E

5 3 6 8 4 +

7 6 0 4 2

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

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

C E N T E R

1 2 9 7 2 6

Brain Teaser No : 00107

If you look at a clock and the time is 3:15. What is the angle between the hour and the minute hands? ( The answer to this is not zero!) Answer 7.5 degrees At 3:15 minute hand will be perfactly horizontal pointing towards 3. Whereas hour hand will be towards 4. Also, hour hand must have covered 1/4 of angle between 3 and 4. The angle between two adjacent digits is 360/12 = 30 degrees. Hence 1/4 of it is 7.5 degrees. An apple vendor has 1000 apples and 10 empty boxes. He asks his son to place all the 1000 apples in all the 10 boxes in such a manner that if he asks for any number of apples from 1 to 1000, his son should be able to pick them in terms of boxes. How did the son place all the apples among the 10 boxes, given that any number of apples can be put in one box. Answer 1, 2, 4, 8, 16, 32, 64, 128, 256, 489 Let's start from scratch. • • • • • •

285

The apple vandor can ask for only 1 apple, so one box must contain 1 apple. He can ask for 2 apples, so one box must contain 2 apples. He can ask for 3 apples, in that case box one and box two will add up to 3. He can ask for 4 apples, so one box i.e. third box must contain 4 apples. Now using box number one, two and three containing 1, 2 and 4 apples respectively, his son can give upto 7 apples. Hence, forth box must contain 8 apples. Similarly, using first four boxes containing 1, 2, 4 and 8 apples, his son can give upto 15 apples. Hence fifth box must contain 16 apples. You must have noticed one thing till now that each box till now contains power of 2 apples. Hence the answer is 1, 2, 4, 8, 16, 32, 64, 128, 256, 489. This is true for any number of apples, here in our case only upto 1000.

Brain Teaser No : 00261

The letters P, Q, R, S, T, U and V, not necessarily in that order represents seven consecutive integers from 22 to 33. • • • •

U is as much less than Q as R is greater than S. V is greater than U. Q is the middle term. P is 3 greater than S.

Can you find the sequence of letters from the lowest value to the highest value?

Answer The sequence of letters from the lowest value to the highest value is TUSQRPV. From (3), Q is the middle term. ___ ___ ___ _Q_ ___ ___ ___ From (4), there must be exactly 2 numbers between P and S which gives two possible positions. [1] ___ _S_ ___ _Q_ _P_ ___ ___ [2] ___ ___ _S_ _Q_ ___ _P_ ___ From (1), the number of letters between U and Q must be same as the number of letters between S and R. Also, the number of letters between them can be 1, 2 or 3. Using trial and error, it can be found that there must be 2 letters between them. Also, it is possible only in option [2] above. [2] ___ _U_ _S_ _Q_ _R_ _P_ ___ From (2) V must be the highest and the remaining T must be the lowest number. _T_ _U_ _S_ _Q_ _R_ _P_ _V_ Thus, the sequence of letters from the lowest value to the highest value is TUSQRPV. A contractor had employed 100 labourers for a flyover construction task. He did not allow any woman to work without her husband. Also, atleast half the men working came with their wives. He paid five rupees per day to each man, four ruppes to each woman and one rupee to each child. He gave out 200 rupees every evening. How many men, women and children were working with the constructor? Answer 16 men, 12 women and 72 children were working with the constructor. Let's assume that there were X men, Y women and Z children working with the constructor. Hence, 286

X + Y + Z = 100 5X + 4Y + Z = 200 Eliminating X and Y in turn from these equations, we get X = 3Z - 200 Y = 300 - 4Z As if woman works, her husband also works and atleast half the men working came with their wives; the value of Y lies between X and X/2. Substituting these limiting values in equations, we get if Y = X, 300 - 4Z = 3Z - 200 7Z = 500 Z = 500/7 i.e. 71.428 if Y = X/2, 300 - 4Z = (3Z - 200)/2 600 - 8Z = 3Z - 200 11Z = 800 Z = 800/11 i.e. 72.727 But Z must be an integer, hence Z=72. Also, X=16 and Y=12 There were 16 men, 12 women and 72 children working with the constructor. Because cigars cannot be entirely smoked, a Bobo who collects cigar butts can make a cigar to smoke out of every 3 butts that he finds. Today, he has collected 27 cigar butts. How many cigars will he be able to smoke? Answer 13 not 12 He makes 9 originals from the 27 butts he found, and after he smokes them he has 9 butts left for another 3 cigars. And then he has 3 butts for another cigar. So 9+3+1=13 In a small town, there are three temples in a row and a well in front of each temple. A pilgrim came to the town with certain number of flowers. Before entering the first temple, he washed all the flowers he had with the water of well. To his surprise, flowers doubled. He offered few flowers to the God in the first temple and moved to the second temple. Here also, before entering the temple he washed the remaining flowers with the water of well. And again his flowers doubled. He offered few flowers to the God in second temple and moved to the third temple. Here also, his flowers doubled after washing them with water. He offered few flowers to the God in third temple. There were no flowers left when pilgrim came out of third temple and he offered same number of flowers to the God in all three temples. What is the minimum number of flowers the pilgrim had initially? How many flower did he offer to each God? Answer

287

The pilgrim had 7 flowers, initially and he offered 8 flowers to each God. Assume that the pilgrim had X flowers initially and he offered Y flowers to each God. From the above figure, there are (8X - 7Y) flowers when the pilgrim came out of the third temple. But it is given that there were no flowers left when he came out of third temple. It means that (8X - 7Y) = 0 8X = 7Y The minimum values of X and Y are 7 and 8 respectively to satisfy above equation. Hence, the pilgrim had 7 flowers and he offered 8 flowers to each God. In general, the pilgrim had 7N flowers initially and he offered 8N flowers to each God, where N = 1, 2, 3, 4, ..... Brain Teaser No : 00432

Tanya wants to go on a date and prefers her date to be tall, dark and handsome. 1. Of the preferred traits - tall, dark and handsome - no two of Adam, Bond, Cruz and Dumbo have the same number. 2. Only Adam or Dumbo is tall and fair. 3. Only Bond or Cruz is short and handsome. 4. Adam and Cruz are either both tall or both short. 5. Bond and Dumbo are either both dark or both fair. Who is Tanya's date?

Answer Cruz is Tanya's date. As no two of them have the same number of preferred traits - from (1), exactly one of them has none of the preferred traits and exactly one of them has all the preferred traits. From (4) and (5), there are only two possibilities: * Adam & Cruz both are tall and Bond & Dumbo both are fair. 288

* Adam & Cruz both are short and Bond & Dumbo both are dark. But from (2), second possibility is impossible. So the first one is the correct possibility i.e. Adam & Cruz both are tall and Bond & Dumbo both are fair. Then from (3), Bond is short and handsome. Also, from (1) and (2), Adam is tall and fair. Also, Dumbo is the person without any preferred traits. Cruz is Dark. Adam and Cruz are handsome. Thus, following are the individual preferred traits: Cruz - Tall, Dark and Handsome Adam - Tall and Handsome Bond - Handsome Dumbo - None :-( Hence, Cruz is Tanya's date. Consider a game of Tower of Hanoi (like the one that you can play on BrainVista). If the tower has 2 discs, the least possible moves with which you can move the entire tower to another peg is 3. If the tower has 3 discs, the least possible moves with which you can move the entire tower to another peg is 7. What is the least possible moves with which you can move the entire tower to another peg if the tower has N discs? Submitted

Answer There are number of ways to find the answer. To move the largest disc (at level N) from one tower to the other, it requires 2(N-1) moves. Thus, to move N discs from one tower to the other, the number of moves required is = 2(N-1) + 2(N-2) + 2(N-3) + ..... + 22 + 21 + 20 = 2N - 1 For N discs, the number of moves is one more than two times the number of moves for N-1 discs. Thus, the recursive function is F(1) = 1 F(N) = 2*[F(N-1)] + 1 where N is the total number of discs Also, one can arrive at the answer by finding the number of moves for smaller number of discs and then derive the pattern. For 1 disc, number of moves = 1 For 2 discs, number of moves = 3 For 3 discs, number of moves = 7 For 4 discs, number of moves = 15 For 5 discs, number of moves = 31 Thus, the pattern is 2N – 1 A boy found that he had a 48 inch strip of paper. He could cut an inch off every second. 289

How long would it take for him to cut 48 pieces? He can not fold the strip and also, can not stack two or more strips and cut them together. SubmiAnswer 47 seconds. To get 48 pieces, the boy have to put only 47 cuts. i.e. he can cut 46 pieces in 46 seconds. After getting 46 pieces, he will have a 2 inches long piece. He can cut it into two with just a one cut in 1 second. Hence, total of 47 seconds.tted by : Kimi The cricket match between India and Pakistan was over. • • • •

Harbhajan scored more runs than Ganguly. Sachin scored more runs than Laxman but less than Dravid Badani scored as much runs as Agarkar but less than Dravid and more than Sachin. Ganguly scored more runs than either Agarkar or Dravid.

Each batsman scored 10 runs more than his immediate batsman. The lowest score was 10 runs. How much did each one of them score Answer A simple one. Use the given facts and put down all the players in order. The order is as follow with Harbhajan, the highest scorer and Laxman, the lowest scorer. 1. 2. 3. 4. 5. 6.

Harbhajan Ganguly Dravid Badani, Agarkar Sachin Laxman

Also, as the lowest score was 10 runs. Laxman must have scored 10, Sachin 20, Badani & Agarkar 30 and so on. 1. 2. 3. 4. 5. 6.

Harbhajan - 60 runs Ganguly - 50 runs Dravid - 40 runs Badani, Agarkar - 30 runs each Sachin - 20 runs Laxman - 10 runs

There are 10 statements written on a piece of paper: 1. 2. 3. 4. 5. 6. 7. 8. 9. 290

At least one of statements 9 and 10 is true. This either is the first true or the first false statement. There are three consecutive statements, which are false. The difference between the numbers of the last true and the first true statement divides the number, that is to be found. The sum of the numbers of the true statements is the number, that is to be found. This is not the last true statement. The number of each true statement divides the number, that is to be found. The number that is to be found is the percentage of true statements. The number of divisors of the number, that is to be found, (apart from 1 and itself) is greater than the sum of the numbers of the true statements.

10. There are no three consecutive true statements. Find the minimal possible number? Submitted

Answer The numebr is 420. If statement 6 is false, it creates a paradox. Hence, Statement 6 must be true. Consider Statement 2: • •

If it is true, it must be the first true statement. Otherwise, it creates a paradox. If it is false, it must be the second false statement. Otherwise, it creates a paradox.

In both the cases, Statement 1 is false. As Statement 1 is false, Statement 9 and Statement 10 both are false i.e. there are three consecutive true statements. 1

2 3 4 5

6

7 8

9

10

False - - - - True - - False False Let\'s assume that Statement 3 is false i.e. there are no three consecutive false statements. It means that Statement 2 and Statement 8 must be true, else there will be three consecutive false statements. 1

2

3

4 5

6

7

8

9

10

False True False - - True - True False False Also, atleast two of Statements 4, 5 and 7 must be true as there are three consecutive true statements. According to Statement 8, the number that is to be found is the percentage of true statements. Hence, number is either 50 or 60. Now if Statement 7 is true, then the number of each true statement divides the number, that is to be found. But 7 and 8 do not divide either 50 or 60. Hence, Statement 7 is false which means that Statement 4 and 5 are true. But Statement 5 contradicts the Statement 8. Hence, our assumption that Statement 3 is false is wrong and Statement 3 is true i.e. there are 3 consecutive false statements which means that Statement 8 is false as there is no other possibilities of 3 consecutive false statements. Also, Statement 7 is true as Statement 6 is not the last true statement. 1

2

3

4 5

6

7

8

9

10

False - True - - True True False False False According to Statement 7, the number of each true statement divides the number, that is to be found. And according to Statement 5, the sum of the numbers of the true statements is the number, that is to be found. For all possible combinations Statement 5 is false. There 3 consecutive true statements. Hence, Statement 2 and Statement 4 are true. 291

1

2

3

4

5

6

7

8

9

10

False True True True False True True False False False Now, the conditions for the number to be found are: 1. The numebr is divisible by 5 (Statement 4) 2. The numebr is divisible by 2, 3, 4, 6, 7 (Statement 7) 3. The number of divisors of the number, that is to be found, (apart from 1 and itself) is not greater than the sum of the numbers of the true statements. (Statement 9) The minimum possible number is 420. The divisors of 420, apart from 1 and itself are 2, 3, 4, 5, 6, 7, 10, 12, 14, 15, 20, 21, 28, 30, 35, 42, 60, 70, 84, 105, 140, 210. There are total of 22 divisors. Also, the sum of the numbers of the true statements is 22 (2+3+4+6+7=22), which satisfies the third condition. Ankit and Tejas divided a bag of Apples between them. Tejas said, "It's not fair! You have 3 times as many Apples I have." Ankit said, "OK, I will give you one Apple for each year of your age." Tejas replied, "Still not fair. Now, you have twice as many Apples as I have." "Dear, that's fair enough as I am twice older than you.", said Ankit. Ankit went to Kitchen to drink water. While Ankit was in Kitchen, Tejas took apples from Ankit's pile equal to Ankit's age. Who have more apples now? Answer At the end, Ankit and Tejas, both have the same number of apples. Let's assume that initially Tejas got N apples and his age is T years. Hence, initially Ankit got 3N apples and his age is 2T years. Operation

Ankit's Apples

Tejas's Apples

Initially

3N

N

Ankit gave T apples to Tejas (equals age of Tejas)

3N - T

N+T

Tejas took 2T apples from Ankit's pile (equals age of Ankit)

3N - 3T

N + 3T

It is given that after Ankit gave T apples to Tejas, Ankit had twice as many apples as Tejas had. 3N - T = 2*(N + T) 3N - T = 2N + 2T N = 3T From the table, at the end Ankit have (3N - 3T) apples and Tejas have (N + 3T) apples. Substituting N = 3T, we get Ankit's apples = 3N - 3T = 9T - 3T = 6T Tejas's apples = N + 3T = 3T + 3T = 6T 292

Thus, at the end Ankit and Tejas, both have the same number of apples. On evey Sunday Amar, Akbar and Anthony lunch together at Preetam-Da-Dhaba where they order lassi based on following facts. 1. 2. 3. 4.

Unless neither Amar nor Akbar have lassi, Anthony must have it. If Amar does not have lassi, either Akbar or Anthony or both have it. Anthony has lassi only if either Amar or Akbar or both have it. Akbar and Anthony never have lassi together.

Who order(s) lassi? Answer Amar and Anthony both have lassi whereas Akbar never does.

Fact (2) can be alternatively stated that "either Amar or Akbar or Anthony must have lassi". From Fact (3), it can be infered that either Amar or Akbar must have lassi. Now, from Fact (1), it is apparent that Anthony too must have lassi. But according to Fact (4), Akbar cannot have lassi when Anthony does. Brain Teaser No : 00191

Decipher this sentence. B R W Q H L F K W

Q I C E D W

H J K

Z B G

W K K

Q I B W K

Z B G

Q H S K

Z B G J

B U U

Z B G J

D B H F W.

M I K E

K Z K W

Answer Start with ZBG and ZBGJ. It should be either "the/then" or "you/your" combination as they appear more.

293

B R W Q H L F K W

H J K

Q I B W K

o b s t a c l e s

a r e

t h o s e

Q I C E D W

Z B G

W K K

M I K E

t h i n g s

y o u

s e e

w h e n

Z B G

Q H S K

Z B G J

K Z K W

y o u

t a k e

y o u r

e y e s

B U U

Z B G J

D B H F W.

o f f

y o u r

g o a l s.

Brain Teaser No : 00001

At what time immediately prior to Six O'clock the hands of the clock are exactly opposite to each other. Give the exact time in hours, minutes and seconds. Answer It is obvious that between 5 O'clock and 6 O'clock the hands will not be exactly opposite to each other. It is also obvious that the hands will be opposite to each other just before 5 O'clock. Now to find exact time: The hour hand moves 1 degree for every 12 degrees that the minute hand moves. Let the hour hand be X degree away from 5 O'clock. Therefore the minute hand is 12X degree away from 12 O'clock. Therefore solving for X Angle between minute hand and 12 O'clock + Angle between 12 O'clock and 4 O'clock + Angle between 4 O'clock and hour hand = 180 12X + 120 + (30-X) = 180 11X = 30 Hence X = 30/11 degrees (hour hand is X degree away from 5 O'clock) Now each degree the hour hand moves is 2 minutes. Therefore minutes are = 2 * 30/11 = 60/11 = 5.45 (means 5 minutes 27.16 seconds) Therefore the exact time at which the hands are opposite to each other is = 4 hrs. 54 min. 32.74 seconds Ali Baba had four sons, to whom he bequeathed his 39 camels, with the proviso that the legacy be divided in the following way : The oldest son was to receive one half the property, the next a quarter, the third an eighth and the youngest one tenth. The four brothers were at a loss as how to divide the inheritance among 294

themselves without cutting up a camel, until a stranger appeared upon the scene. Dismounting from his camel, he asked if he might help, for he knew just what to do. The brothers gratefully accepted his offer. Adding his own camel to Ali Baba's 39, he divided the 40 as per the will. The oldest son received 20, the next 10, the third 5 and the youngest 4. One camel remained : this was his, which he mounted and rode away. Scratching their heads in amazement, they started calculating. The oldest thought : is not 20 greater than the half of 39? Someone must have received less than his proper share ! But each brother discovered that he had received more than his due. How is it possible? Answer They took their percentages from 40 and not from 39, so they got more than their share. The oldest son got 1/2 of 40 = 20 which is 0.5 more The second son got 1/4 of 40 = 10 which is 0.25 more The third son got 1/8 of 40 = 5 which is 0.125 more The youngest son got 1/10 of 40 = 4 which is 0.1 more And the stranger got 1/40 of 40 = 1 which is 0.025 more (As he is not supposed to get anything) All these fractions add to = 0.5 + 0.25 + 0.125 + 0.1 + 0.025 = 1 which stranger took away. There is a family party consisting of two fathers, two mothers, two sons, one father-in-law, one mother-in-law, one daughter-in-law, one grandfather, one grandmother and one grandson. What is the minimum number of persons required so that this is possible? Answer There are total 2 couples and a son. Grandfather and Grand mother, their son and his wife and again their son. So total 5 people. Grandfather, Grandmother | | Son, wife | | Son A man went into a fast food restaurant and ate a meal costing Rs. 105, giving the accountant a Rs. 500 note. He kept the change, came back a few minutes later and had some food packed for his girl friend. He gave the accountant a Rs. 100 note and received Rs. 20 in change. Later the bank told the accountant that both the Rs. 500 and the Rs. 100 notes were counterfeit. How much money did the restaurant lose? Ignore the profit of the food restaurant. Answer He lost Rs.600 First time restaurant has given food worth Rs.105 and Rs. 395 change. Similarly second time, food worth Rs.80 and Rs.20 change. Here, we are not considering food restaurant profits. S L I D E 295

-

D E A N ---------

3 6 5 1 Each of seven digits from 0-9 are represented by a different letter above such that the subtraction is true. What word represents 3651? Answer 3651 represents LENS. Let's assign possible values to each letter and then use trial-n-error. S must be 1. Then D (under L) must be greater than 5. If D is 6, then L is 0. But then A must be 0 or 1 which is impossible. Hence, the possible values of D are 7, 8 or 9. N must be E + 1. Also, D must be A + 5 as the possible values of D are 7, 8 or 9, D can not be (10+A) + 5. Now using trial-n-error, we get S=1, I=2, L=3, A=4, N=5, E=6 and D=9 S -

L

I

D

E

D

E

A

N

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

1 -

3

2

9

6

9

6

4

5

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

3 6 5 1 L E N S Hence, 3651 represents LENS. Adam, Burzin, Clark and Edmund each live in an apartment. Their apartments are arranged in a row numbered 1 to 4 from left to right. Also, one of them is the landlord. 1. If Clark's apartment is not next to Burzin's apartment, then the landlord is Adam and lives in apartment 1. 2. If Adam's apartment is right of Clark's apartment, then the landlord is Edmund and lives in apartment 4. 3. If Burzin's apartment is not next to Edmund's apartment, then the landlord is Clark and lives in apartment 3. 4. If Edmund's apartment is right of Adam's apartment, then the landlord is Burzin and lives in apartment 2. Who is the landlord? Answer Clark is the landlord.

Assume each statement true, one at a time and see that no other statement is contradicted.

296

Let's assume that Statement (1) is true. Then, Adam is the landlord and lives in apartment 1. Also, other three's apartments will be on the right of his apartment - which contradicts Statement (4) i.e. If Edmund's apartment is right of Adam's apartment, then the landlord is Burzin. Thus, Adam is not the landlord. Let's assume that Statement (2) is true. Then, Edmund is the landlord and lives in apartment 4. Also, other three's apartments will be on the left of his apartment - which again contradicts Statement (4) i.e. If Edmund's apartment is right of Adam's apartment, then the landlord is Burzin. Thus, Edmund is not the landlord either. Let's assume that Statement (3) is true. Then, Clark is the landlord and lives in apartment 3. It satisfies all the statements for (1) Adam - (2) Edmund - (3) Clark - (4) Burzin Hence, Clark is the landlord. Similarly, you can assume Statement (4) true and find out that it also contradicts. Brain Teaser No : 00456

B, J and P are related to each other. 1. Among the three are B's legal spouse, J's sibling and P's sister-in-law. 2. B's legal spouse and J's sibling are of the same sex. Who is the married man? Answer J is the married man. Note that a person's sister-in-law may be the wife of that person's brother or the sister of that person's spouse. There are 2 cases: 1. If B's legal spouse is J, then J's sibling must be P and P's sister-in-law must be B. 2. If B's legal spouse is P, then P's sister-in-law must be J and J's sibling must be B. It is given that B's legal spouse and J's sibling are of the same sex. Also, it is obvious that P's sister-in-law is female. Then, B's legal spouse and J's sibling both must be males. B's spouse (male)

J's sibling

P's sister-in-law

(male)

(female)

-----------------------------------------------------Case I

J

P

B

Case II

P

B

J

297

Case II is not possible as B & P are married to each other and both are male. Hence, J is the married man. Brain Teaser No : 00041

A polygon has 1325 diagonals. How many vertices does it have? Answer The formula to find number of diagonals (D) given total number of vertices or sides (N) is N * (N - 3) D

=

----------2

Using the formula, we get 1325 * 2 = N * (N - 3) N2 - 3N - 2650 = 0 Solving the quadratic equation, we get N = 53 or -50 It is obvious that answer is 53 as

number of vertices can not be negative.

Alternatively, you can derive the formula as triange has 0 diagonals, quadrangel has 2, pentagon has 5, hexagon has 9 and so on...... Hence the series is 0, 0, 0, 2, 5, 9, 14, ........ (as diagram with 1,2 or 3 vertices will have 0 diagonals). Using the series one can arrive to the formula given above. Brain Teaser No : 00076

A cube is made of a white material, but the exterior is painted black. If the cube is cut into 125 smaller cubes of exactly the same size, how many of the cubes will have atleast 2 of their sides painted black? Answer 44

36 of the cubes have EXACTLY 2 of their sides painted black, but because a cube with 3 of its sides painted black has 2 of its sides painted black, you must also include the corner cubes. This was a trick question, but hopefully the title of the puzzle tipped you off to this. Brain Teaser No : 00238

Imagine a triangle of coins on a table so that the first row has one coin in it and the second row has two coins in it and so on. If you can only move one coin at a time, how many moves 298

does it take to make the triangle point the other way? For a triangle with two row it is one, for a triangle with three rows it is two, for a triangle with four rows it is three. For a traingle with five rows is it four? Submitted

Answer It takes 5 moves to make the triangle with 5 rows point the other way. 0 = a coin that has not been moved. X = the old position of the moved coin 8 = the new position of the moved coin. ________X _______X X ____8 0 0 0 8 _____0 0 0 0 ____X 0 0 0 X _______8 8 ________8 For traingle of any number of rows, the optimal number of moves can be achieved by moving the vertically symmetrical coins i.e. by moving same number of coins from bottom left and right, and remaining coins from the top. For a triangle with an odd number of rows, the total moves require are : (N2/4) - (N-4) Where N = 4, 6, 8, 10, ... For a triangle with even number of rows, the total moves require are : ((N2-1)/4) - (N-4) Where N = 5, 7, 9, 11, ...

Thanks to Alex Crosse for submitting above formulas. Brain Teaser No : 00053

A man is going to an Antique Car auction. All purchases must be paid for in cash. He goes to the bank and draws out $25,000. Since the man does not want to be seen carrying that much money, he places it in 15 evelopes numbered 1 through 15. Each envelope contains the least number of bills possible of any available US currency (i.e. no two tens in place of a twenty). At the auction he makes a successful bid of $8322 for a car. He hands the auctioneer envelopes number(s) 2, 8, and 14. After opening the envelopes the auctioneer finds exactly the right amount. How many ones did the auctioneer find in the envelopes? Answer 299

Each envelope contains the money equal to the 2 raised to the envelope number minus 1. The sentence "Each envelope contains the least number of bills possible of any available US currency" is only to misguide you. This is always possible for any amount !!! One more thing to notice here is that the man must have placed money in envelopes in such a way that if he bids for any amount less than $25000, he should be able to pick them in terms of envelopes. First envelope contains, 20 = $1 Second envelope contains, 21 = $2 Third envelope contains, 22 = $4 Fourth envelope contains, 23 = $8 and

so on...

Hence the amount in envelopes are $1, $2, $4, $8, $16, $32, $64, $128, $256, $512, $1024, $2048, $4096, $8192, $8617 Last envelope (No. 15) contains only $8617 as total amount is only $25000. Now as he bids for $8322 and gives envelope number 2, 8 and 14 which contains $2, $128 and $8192 respectively. Envelope No 2 conrains one $2 bill Envelope No 8 conrains one $100 bill, one $20 bill, one $5 bill, one $2 bill and one $1 bill Envelope No 14 conrains eighty-one $100 bill, one $50 bill, four $10 bill and one $2 bill Hence the auctioneer will find one $1 bill in the envelopes. Brain Teaser No : 00090

The minute and the hour hand of a watch meet every 65 minutes. How much does the watch lose or gain time and by how much?

Answer

The minute and the hour hand meet 11 times in 12 hours in normal watch i.e. they meet after every = (12 * 60) / 11 minutes = 65.45 minutes = 65 minutes 27.16 seconds But in our case they meet after every 65 minutes means the watch is gaining 27.16 seconds. Brain Teaser No : 00093

There is a number that is 5 times the sum of its digits. What is this number? Answer is not 0.

300

Answer The number is 45, simply because 45 = 5 * (4 + 5) How does one find this number? Let T be the digit in the tens place and U be the digit in the units place. Then, the number is 10*T + U, and the sum of its digits is T + U. The following equation can be readily written: 10*T + U = 5*(T + U) or 10*T + U = 5*T + 5*U or 5*T = 4*U Thus, T / U = 4 / 5 Since T and U are digits, T must be 4 and U must be 5. There are six boxes containing 5, 7, 14, 16, 18, 29 balls of either red or blue in colour. Some boxes contain only red balls and others contain only blue. One sales man sold one box out of them and then he says, "I have the same number of red balls left out as that of blue." Which box is the one he solds out? Answer

Total no of balls = 5 + 7 + 14 + 16 + 18 + 29 = 89 Total number of balls are odd. Also, same number of red balls and blue balls are left out after selling one box. So it is obvious that the box with odd number of balls in it is sold out i.e. 5, 7 or 29. Now using trial and error method, (89-29) /2 = 60/2 = 30 and 14 + 16 = 5 + 7 + 18 = 30 So box with 29 balls is sold out. Brain Teaser No : 00218

Ekta got chocolates to give her friends on her Birthday. If she gives 3 chocolates to each friend, one friend will get only 2 chocolates. Also, if she gives 2 chocolates to each friends, she will left with 15 chocolates. How many chocolates Ekta got on her Birthday? and how many friends are there?

Answer 47 Chocolates and 16 Friends Let's assume that there are total C chocolates and F friends. 301

According to first case, if she gives 3 chocolates to each friend, one friend will get only 2 chocolates. 3*(F - 1) + 2 = C Similarly, if she gives 2 chocolates to each friends, she will left with 15 chocolates. 2*F + 15 = C Solving above 2 equations, F = 16 and C = 47. Hence, Ekta got 47 chocolates and 16 friends Pooja and Esha met each other after long time. In the course of their conversation, Pooja asked Esha her age. Esha replied, "If you reverse my age, you will get my husbund's age. He is of course older than me. Also, the difference between our age is 1/11th of the sum of our age." Can you help out Pooja in finding Esha's age? Answer Esha's age is 45 years. Assume that Esha's age is 10X+Y years. Hence, her hunsbands age is (10Y + X) years. It is given that difference between their age is 1/11th of the sum of their age. Hence, [(10Y + X) - (10X + Y)] = (1/11)[(10Y + X) + (10X + Y)] (9Y - 9X) = (1/11)(11X + 11Y) 9Y - 9X = X + Y 8Y = 10X 4Y = 5X Hence, the possible values are X=4, Y=5 and Esha's age is 45 years. A fish had a tail as long as its head plus a quarter the lenght of its body. Its body was threequarters of its total length. Its head was 4 inches long. What was the length of the fish? Submitted

The fish is 128 inches long. It is obvious that the lenght of the fish is the summation of lenghts of the head, the body and the tail. Hence, Fish (F) = Head (H) + Body (B) + Tail (T) But it is given that the lenght of the head is 4 inches i.e. H = 4. The body is three-quarters of its total length i.e. B = (3/4)*F. And the tail is its head plus a quarter the lenght of its body i.e. T = H + B/4. Thus, the equation is F=H+B+T F = 4 + (3/4)*F + H + B/4 F = 4 + (3/4)*F + 4 + (1/4)*(3/4)*F F = 8 + (15/16)*F (1/16)*F = 8 F = 128 inches Thus, the fish is 128 inches long. Assume that you have just heard of a scandal and you are the first one to know. You pass it on to four person in a matter of 30 minutes. Each of these four in turn passes it to four other persons in the next 30 minutes and so on. How long it will take for everybody in the World to get to know the scandal? 302

Assume that nobody hears it more than once and the population of the World is approximately 5.6 billions. Answer Everybody in the World will get to know the scandal in 8 hours. You came to know of a scandal and you passed it on to 4 persons in 30 minutes. So total (1+4) 5 persons would know about it in 30 minutes. By the end of one hour, 16 more persons would know about it. So total of (1+4+16) 21 persons would know about it in one hour. Similarly, the other (1+4+16+64) persons would have know about it in one and a half hours. (1+4+16+64+256) persons would have know about it in two hours and so on... It can be deduced that the terms of the above series are the power of 4 i.e. 4^0, 4^1, 4^2, 4^3 and so on upto (2N+1) terms. Also, the last term would be 4^2N where N is the number of hours. Sum of the above mentioned series = [4^(2N+1)-1]/3 The sum of the series must be 5.6 billions. Hence, equating the sum of the series with 5.6 billions, we get N=8 hours. Scandals travel FAST !!! A B C D E

F

G H

I Each of the digits from 1 to 9 is represented by a different letter above. Also, A + B + C = C + D + E = E + F + G = G + H + I = 13 Which digit does E represent? Answer E represents 4. Find out all possible groups of three different numbers that add up to 13 and arrange them according to given condition. If one number is 9, it must go with 1 and 3. If one number is 8, it must go with either 1 and 4 or 2 and 3. If one number is 7, it must go with either 1 and 5 or 2 and 4. If one number is 6, it must go with either 2 and 5 or 3 and 4. It is clear that 9 must go with 1 and 3. Also, no digit may be used in more than two sums. Hence, there are 2 cases: Case I: If 8 goes with 1 and 4, then 7 goes with 2 and 4, then 6 goes with 2 and 5. Case II: If 8 goes with 2 and 3, then 7 goes with 2 and 4, then 6 goes with 3 and 4.

303

But in case II, 3 is used in three sums. Hence, Case I is correct. And the possible arrangements are: 9

3

1

5

8 4

6

2 7

7

2 6

4

8

1 3

5 9 Thus, E must be 4. A, B and C are three points on a straight line, not necessarily equidistant with B being between A and C. Three semicircles are drawn on the same side of the line with AB, BC and AC as the diameters. BD is perpendicular to the line ABC, and D lies on the semicircle AC. If the funny shaped diagram between the three semicircles has an area of 1000 square cms, find the length of BD.

304

Answer

The length of BD is 35.68 cms There are 3 right-angled triangles - ABD, CBD and ADC. From ABD, AB^2 + BD^2 = AD^2 ------ I From CBD, CB^2 + BD^2 = CD^2 ------ II From ADC, AD^2 + CD^2 = AC^2 ------ III Adding I and II, AB^2 + BC^2 + 2*BD^2 = AD^2 + CD^2 ------ IV FROM III and IV AB^2 + BC^2 + 2*BD^2 = AC^2 AB^2 + BC^2 + 2*BD^2 = (AB+CB)^2 2*BD^2 = 2*AB*CB BD^2 = AB*CB BD = SQRT(AB*CB) Given that funny shaped diagram beween three semicircles has an area of 1000 square cms. [PI/2 * (AC/2)^2] - [PI/2 * (AB/2)^2] - [PI/2 * (BC/2)^2] = 1000 PI/8 * [AC^2 - AB^2 - BC^2] = 1000 PI * [(AB+BC)^2 - AB^2 - BC^2] = 8000 PI * [2*AB*BC] = 8000 AB * BC = 4000/PI Hence BD = SQRT(4000/PI) = 35.68 cms where PI = 3.141592654 Hence, the length of BD is 35.68 cms. Submit Answer

Users Answer (33)

BrainVista Answer

P

Brain Teaser No : 00660

Gomzi has 3 timepieces in his house - a wall clock, an alarm clock and a wristwatch. The wristwatch is always accurate, whereas the wall clock gains 2 minutes everyday and the alarm clock loses 2 minutes everyday. At exactly midnight last night, all three watches were showing the same time. 305

If today is 25 July 2003, then on which date all three clocks will show the same time again?

Answer All three clocks will show the same time again on midnight between 19 July 2004 and 20 July 2004. A clock finishes on round in 12*60 i.e. 720 minutes. If a clock gains 2 minutes everyday, then it would be 720 minutes ahead after 360 days. Thus, after 360 days, it will show the same time again. Similary, if a clock loses 2 minutes everyday, then it would be 720 minutes behind after 360 days. Thus, after 360 days, it will show the same time again. Thus, after 360 days all three clocks will show the same time again i.e. midnight between 19 July 2004 and 20 July 2004. You have 9 marbles. 8 marbles weigh 1 ounce each, & one marble weighs 1.5 ounces. You are unable to determine which is the heavier marble by looking at them. You have a weighing scale that consists of 2 pans, but the scale is only good for 2 total weighings. How can you determine which marble is the heaviest one using the scale & in 2 weighings? Answer Divide 9 marbles into 3 groups of 3 marbles each. Take any 2 groups and place them on each pan. If they balance, remove the marbles from the pans, & place any 2 of the marbles from the remaining unweighed group on the pans, 1 on each pan. If one is heavier, it is the heavier marble, but if they balance, the remaining unweighed marble is the heavier one. If your first weighing does not balance, remove the marbles from the lighter pan, & place 1 marble on each pan from the heavier pan. The heavier 1 is the 1.5 ounce marble, but if they balance, then the marble from the heavy pan from the first weighing that was not weighed in the second weighing is the heavy 1. Once a week a wagon driver leaves his hut and drives his wagon to the river dock to pick up supplies for his town. At 4:05 PM, one-fifth of the way to the dock, he passes the Temple. At 4:15 PM, one-third of the way, he passes the Preetam-Da-Dhabaa. At what time does he reached the dock? Answer 5:05 PM

At 4:05 PM, the wagon driver passes the temple, one-fifth of the way to the dock. Also, at 4:15 PM, he passes the Preetam-Da-Dhabaa, one-third of the way. Thus, he travels 2/15 (1/3 - 1/5) of the distance in 10 minutes. 306

At 4:15 PM, he has already travelled 1/3 of the distance. Thus 2/3 of the way is remaining, which can be travelled in = ( (2/3) * 10 ) / (2/15) = 50 minutes At 4:15, he was at Preetam-Da-Dhabaa.and remaining way will take 50 more minutes. Hence, the driver will reach at 5:05 PM to the dock. Brain Teaser No : 00115

Four prisoners escape from a prison. The prisoners, Mr. East, Mr. West, Mr. South, Mr. North head towards different directions after escaping. The following information of their escape was supplied: • • • • •

The escape routes were North Road, South Road, East Road and West Road None of the prisoners took the road which was their namesake Mr. East did not take the South Road Mr.West did not the South Road The West Road was not taken by Mr. East

What road did each of the prisoners take to make their escape Answer Put all the given information into the table structure as follow: North Road South Road East Road Mr. North

West Road

No

Mr. South

No

Mr. East

No

Mr. West

No

No

No No

Now from table, two things are obvious and they are: • •

Mr.North took the South Road Mr.East took the North Road

Put this information into the table, Also keep in mind that the prisoners head towards different directions after escaping. North Road South Road East Road

307

Mr. North

No

YES

Mr. South

No

No

Mr. East

YES

No

West Road

No

No

No

No

Mr. West

No

No

No

Now from the table: • •

Mr.West took the East Road Mr.South took the West Road

So the answer is: • • • •

Mr.North took the South Road Mr.South took the West Road Mr.East took the North Road Mr.West took the East Road

Shahrukh speaks truth only in the morning and lies in the afternoon, whereas Salman speaks truth only in the afternoon and lies in the morning. A says that B is Shahrukh. Is it morning or afternoon and who is A - Shahrukh or Salman? Answer It is Afternoon and A can be Salman or Shahrukh. If A is Salman, he is speaking truth. If A is Shahrukh, he is lying. Want to confirm it? Consider following 4 possible answers and check for its truthness individually. 1. 2. 3. 4.

It is Morning and A is Shahrukh It is Morning and A is Salman It is Afternoon and A is Shahrukh It is Afternoon and A is Salman

A rich man died. In his will, he has divided his gold coins among his 5 sons, 5 daughters and a manager. According to his will: First give one coin to manager. 1/5th of the remaining to the elder son. Now give one coin to the manager and 1/5th of the remaining to second son and so on..... After giving coins to 5th son, divided the remaining coins among five daughters equally. All should get full coins. Find the minimum number of coins he has? Answer We tried to find out some simple mathematical method and finally we wrote small C program to find out the answer. The answer is 3121 coins. Here is the breakup: First son = 624 coins Second son = 499 coins Third son = 399 coins Forth son = 319 coins Fifth son = 255 coins 308

Daughters = 204 each Manager = 5 coins There is a grid of 20 squares by 10 squares. How many different rectangles are possible? Note that square is a rectangle. Answer 11550 The Generic solution to this is: Total number of rectangles = (Summation of row numbers) * (Summation of column numbers) Here there are 20 rows and 10 columns or vice versa. Hence, total possible rectangles = ( 20 + 19 + 18 + 17 + 16 + .... + 3 + 2 + 1 ) * ( 10 + 9 +8 + 7 + .... + 3 + 2 + 1) = ( 210 ) * (55) = 11550 Hence, total 11,550 different rectangles are possible. If you don't believe it, try formula on some smaller grids like 4x2, 3x2, 3x3 etc... If A+B=C, D-C=A and E-B=C, then what does D+F stands for? Provide your answer in letter terms as well as in number terms. Submitted by : David

Answer J or 10 A simple one. Assume that each character represents the number equivalent to the position in the alphabet i.e. A = 1, B = 2, C = 3, D = 4 and so on. Now let's check our assumption. A + B = C i.e. 1 + 2 = 3 D - C = A i.e. 4 - 3 = 1 E - B = C i.e. 5 - 2 = 3 Thus, our assumption was Correct. Hence, D + F = J i.e. 4 + 6 = 10 A woman took a certain number of eggs to the market and sold some of them. The next day, through the industry of her hens, the number left over had been doubled, and she sold the same number as the previous day. On the third day the new remainder was tripled, and she sold the same number as before. On the fourth day the remainder was quadrupled, and her sales the same as before. On the fifth day what had been left over were quintupled, yet she sold exactly the same as on all the previous occasions and so disposed of her entire stock. What is the smallest number of eggs she could have taken to market the first day, and how many did she sell daily? Note that the answer is not zero. Submitted

Answer She took 103 eggs to market on the first day and sold 60 eggs everyday. 309

Let's assume that she had N eggs on the first day and she sold X eggs everyday. Putting down the given information in the table as follow. Days Eggs at the start of the day Eggs Sold

Eggs Remaining

Day 1

N

X

N-X

Day 2

2N-2X

X

2N-3X

Day 3

6N-9X

X

6N-10X

Day 4

24N-40X

X

24N-41X

Day 5

120N-205X

X

120N-206X

It is given that she disposed of her entire stock on the fifth day. But from the table above, the number of eggs remaining are (120N-206X). Hence, 120N - 206X = 0 120N = 206X 60N = 103X The smallest value of N and X must be 103 and 60 respectively. Hence, she took 103 eggs to market on the first day and sold 60 eggs everyday. John lives in "Friends Society" where all the houses are in a row and are numbered sequentially starting from 1. His house number is 109. Jessy lives in the same society. All the house numbers on the left side of Jessy's house add up exactly the same as all the house numbers on the right side of her house. What is the number of Jessy's house? Find the minimal possible answer. Answer There are 288 houses and Jessy's house number is 204. Let's assume that in the "Friends Society" there are total N houses numbered from 1 to N and Jessy's house number is X. Now it is given that all the house numbers on the left side of Jessy's house add up exactly the same as all the house numbers on the right side of her house. Hence, 1 + 2 + 3 + ..... + (X-1) = (X+1) + (X+2) + (X+3) + ..... + N Both the sides of the above equations are in A.P. Hence, using A.P. summation formaula, [(X-1)/2][2*(1) + (X-1-1)] = [(N-X)/2][2*(X+1) + (N-X-1)] [X-1][(2) + (X-2)] = [N-X][(2X+2) + (N-X-1)] (X-1)(X) = (N-X)(N+X+1) X2 - X = N2 + NX + N - NX - X2 - X X 2 = N2 + N - X 2 2X2 = N2 + N X2 = (N2 + N)/2 X2 = N(N+1)/2 Now, using Trial and Error method to find values of N and X such that above equation is satisfied, we get 310

1. 2. 3. 4. 5.

N = 8, X = 6 N = 49, X = 35 N = 288, X = 204 N = 1681, X = 1189 N = 9800, X = 6930

But we require minimal possible answer and it is given that John's house number is 109. It means that there are atleast 109 houses. Hence, first two are not possible. And the answer is : there are 288 houses and Jessy's house number is 204. Makayla had $1.19 in change. None of the coins was a dollar. Nicole ask her for change for a dollar, but Makayla could not make change. What coins did she have? Submitted

Answer As it is given that Makayla had $1.19, it means she would have four pennies. Now, the remaining $1.15 in coins must not add up for exactly a dollar. Therefore she would not have 4 quarters or 2 quarters and 5 dimes. But she would have either 1 quarter or 3 quarters. Hence, there are 2 solutions. Solution I 1 Quarter, 9 Dimes, 4 Pennies (0.25 + 0.90 + 0.04 = $1.19) Solution II 3 Quarters, 4 Dimes, 4 Pennies (0.75 + 0.40 + 0.04 = $1.19) A group of friends went on a holiday to a hill station. It rained for 13 days. But when it rained in the morning, the afternoon was lovely. And when it rained in the afternoon, the day was preceded by clear morning. Altogether there were 11 very nice mornings and 12 very nice afternoons. How many days did their holiday last? Answer The holiday last for 18 days.

Let's assume the number of days as follows: Rain in the morning and lovely afternoon = X days Clear morning and rain in the afternoon = Y days No rain in the morning and in the afternoon = Z days Number of days with rain = X + Y = 13 days Number of days with clear mornings = Y + Z = 11 days Number of days with clear afternoons = X + Z = 12 days Solving above 3 equations, we get X = 7, Y = 6 and Z = 5 Hence, total number of days on holiday = 18 days Brain Teaser No : 00299

Substitute digits for the letters to make the following Division true 311

Y F Y ----------A Y | N E L L Y | N L Y ---------------P P L P N H ---------N L Y N L Y ---------0 0 0 Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter N, no other letter can be 3 and all other N in the puzzle must be 3. Submitted by : Calon

Answer See the pattern of the Y. AY * Y = NLY i.e. Y is multiplied by Y and the last digit of the answer is also Y. Thus, the value of Y would be 5 or 6. Also, H=0 as L - H = L P = 2N as P - N = N L - Y = P = 2N E-L=p Let's find out the minimum possible values. If N=1, then P=2, Y=5, L=7 and E=9. Note that the value of Y can not be 6 as it makes L=8 and E=10 which is not possible. Hence, Y=5, N=1, P=2, L=7, E=9, H=0 Now, using trial-n-error or rather solving F*AY=PNH, we get F=6 and A=3. 5 6 5

Y F Y

-----------

-----------

3 5 | 1 9 7 7 5

A Y | N E L L Y

| 1 7 5

| N L Y

-----------

-----------

312

2 2 7

P P L

2 1 0

P N H

-----------

-----------

1 7 5

N L Y

1 7 5

N L Y

-----------

-----------

0 0 0

0 0 0

Brain Teaser No : 00566

Here is the family tree of Mr. RAHUL RAHUL | --------------------------------------------|

|

|

|

RATISH

YASH

OM

TRILOK

|

|

?

--------

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

|

|

|

|

|

AMAR

AMIT

RAM

HARSH

ASHOK

|

|

-----

-------

|

|

|

|

|

How many children does Mr. TRILOK have?

Answer TRILOK have 5 children. Name of the person and number of his children are related by some pattern. Assign each vowel following values. A=0 E=1 I=2 O=3 U=4 The number of children to any person is the sum of the values represented by vowels in his 313

name. RATISH = 0(A) + 2(I) = 2 OM = 3(O) = 3 AMIT = 0(A) + 2(I) = 2 ASHOK = 0(A) + 3(O) = 3 TRILOK = 2(I) + 3(O) = 5 Hence, TRILOK have 5 children. Major Jasbir is forming five-person Special Task Group. The group must contain one leader, two bomb-experts and two soldiers. P, Q and R are possible bomb-experts. R, S and T are possible leaders. U, V and W are possible soldiers. Also, P and R prefers to work with each other in the same team. T prefers to work only if V works. How many different possible Groups, Major Jasbir can make? Answer Major Jasbir can make 8 different possible groups. As 2 bomb-experts to be selected from the given 3 and also P & R prefers to work together, PR must be there in all the possible Groups. Also, T prefers to work only if V works. It doesn't mean that V won't work without T. Hence, possible groups are: PR - S - UV PR - S - VW PR - S - WU PR - T - UV PR - T - VW PQ - R - UV PQ - R - VW PQ - R - WU Hence, there 8 different groups are possible. The secret agent X emailed some code to his head office. They are "RADAR, LEVEL, ROTOR, REDIVIDER, MOTOR". But four of these five words have something in common and one is fake. Can you tell which one is fake? Ignore the fact that four of the code-words are of the same length. Answer The fake code-word is MOTOR.

All the code-words except MOTOR are Palindromes. Brain Teaser No : 00287

In the village called TALAJA, only three TV channels are available - Moon Plus, Mony and Mee TV. Out of 4000 TV viewers in the village, 1500 watch Moon TV, 2000 watch Mony and 2500 watch Mee TV. 314

Amongst these, 500 viewers watch Moon Plus and Mony, 800 watch Moon Plus and Mee TV, and 1000 watch Mony and Mee TV. How many viewers watch all three channels?

Answer 300 viewers watch all three channels. Let's assume that total X viewers watch all three channels. total viewers who watch only Moon Plus and Mony = 500-X total viewers who watch only Moon Plus and Mee TV = 800-X total viewers who watch only Mony and Mee TV = 1000-X total viewers who watch only Moon Plus = 1500 - (500-X) - (800-X) - X = 200 + X total viewers who watch only Mony = 2000 - (500-X) - (1000-X) - X = 500 + X total viewers who watch only Mee TV = 2500 - (1000-X) - (800-X) - X = 700 + X We know that total viewers are 4000. Summing up all 7 values, X + (500 - X) + (800 - X) + (1000 - X) + (200 + X) + (500 + X) + (700 + X) = 4000 X + 3700 = 4000 X = 300 Hence, total 300 viewers watch all three channels. A man was looking at a portrait. Someone asked him, "Whose picture are you looking at?" He replied, pointing at the portrait: "Brothers and sisters have I none, but this man's son is my father's son." Now whose picture is the man looking at? Answer The man is looking at his FATHER's portrait. "my father's son" is the man himself as he do not have any brothers and sisters. So the statement reduces to "this man's son is myself." Now it is clear that the portrait is of his father. Given the following facts: 1. 2. 3. 4. 5. 315

Dinesh is younger than Farukh and older than Gurmit. Jatin is younger than Chandu and older than Eshrat. Amit is younger than Irfan and older than Chandu. Farukh is younger than Bhavin and older than Hemant. Irfan is younger than Gurmit and older than Jatin.

6. Hemant is older than Gurmit. Who is the Youngest? Answer Eshrat is the youngest. Discard whoever are older than someone. From (1) Gurmit is younger than Dinesh and Farukh. From (5) Jatin is younger than Irfan and Gurmit. From (2) Eshrat is younger than Jatin and Chandu. From above 3 deductions, Eshrat is younger than Dinesh, Farukh, Irfan, Gurmit, Jatin and Chandu. Also, From (3) Chandu is younger than Amit and Irfan. From (4) Hemant is younger than Farukh and Bhavin. From (6) Gurmit is younger than Hemant. From above 3 deductions, Gurmit is younger than Farukh, Bhavin and Hemant. Also, Chandu is younger than Amit and Irfan. But as seen earlier, Eshrat is younger than Gurmit and Chandu. Hence, Eshrat is the youngest. Last Saturday Milan went for the late night show and came late. In the morning family members asked him which movie did he see. He gave different answers to everyone. • • • • •

He told to his father that he had gone to see MONEY. According to his mom, he saw either JOHNY or BABLU. His elder brother came to know that he saw BHABI. To his sister, he told ROBOT. And his grandpa heard that he saw BUNNY.

Thus, Milan gave six movie names, all five letter words. But he saw some other movie with five letter word. Moreover, each of the six movie names mentioned above has exactly two letters common with the movie he saw. (with the same positions) Can you tell which movie did Milan see? Answer Milan saw BOBBY. The six movie names are - MONEY, JOHNY, BABLU, BHABI, ROBOT and BUNNY. Compare MONEY and JOHNY. They have O common at the second place and Y common at the fifth place. Also, they can't have two different letters each, common with the required movie as the letters in remaining three places are all different. Thus, the required movie must have either O at the second place or Y at the fifth place or both. Similarly, comparing JOHNY and BUNNY - the required movie must have either N at the fourth place or Y at the fifth place or both. Also, comparing MONEY and BUNNY - the required movie must have either N at the third place or Y at the fifth place or both. From the above 3 deduction, either Y is at fifth place or O is at the second place and N is at the 316

third & fourth place. The later combination is not possible as BABLU, BHABI & ROBOT will need at least 3 other letters which makes the required movie 6 letter long. Hence, the required movie must have Y at the fifth place. Now Y is not there in BABLU and BHABI at the fifth place and they have only B common at the first place. Hence, B must be the first letter. As B is at the first place and Y is at the fifth place and every movie has exactly 2 letters common with the required movie. From BUNNY, the required movie do not have U at the second place and N at the third and fourth place. Now looking at JOHNY and MONEY, they must have O common at the second place. Using the same kind of arguments for BABLU, BHABI and ROBOT, we can conclude that Milan saw BOBBY. Jim lies a lot. He tells the truth on only one day in a week. One day he said: "I lie on Mondays and Tuesdays." The next day he said: "Today is either Sunday, Saturday or Thursday." The next day he said: "I lie on Fridays and Wednesdays." On which day of the week does Jim tell the truth? Answer Jim tells the truth on Tuesday. As Jim tells truth only on one day in a week, his statement on day 1 and day 3 both can not be false. Otherwise he tells truth on more than one days in a week. Also, all three statements are mad on three consecutive days, statement made on day 1 and day 3 both can not be true. Thus, either the statement made on day 1 or day 3 is true and other is false. Also, the statement made on day 2 must be false i.e. day 1 is not Saturday, Friday or Wednesday. Let's assume that the statement 1 is true. Then from the statement 3, day 1 must be either Friday or Wednesday. But it is already deduced that day 1 is not Saturday, Friday or Wednesday. Hence, the statement made on day 1 is false and the last statement is true. then from the statement 1, day 3 must be either Monday or Tuesday. But it is already deduced that day 1 can not be Saturday i.e. day 3 can't be Monday. Hence, Jim tells the truth on Tuesday. 4 men can dig 4 holes in 4 days. How many hours does it take for 1 man to dig half a hole? Submitted

Answer There is nothing like "HALF HOLE". Consider a chessboard with a single Rook. A Rook can move any number of square sideways/forward, but not diagonally. What is the minimum number of moves the Rook needs to make, in order to pass over all the squares on the chessboard and return to the original position? Answer 16 moves As a Rook can move any number of square sideways/forward, but not diagonally and there are 8 317

rows and 8 columns on the chessboard; the Rook needs minimum 16 moves to pass over all the squares and return to the original position. A farmer needs 8 gallons of water. He has only three unmared buckets, two 6 gallon and one 11 gallon bucket. How can he collect 8 gallons of water using three unmarked buckets? Provide solution with minimal water wastage. Answer Here is the solution with 10 gallon water wastage. OPERATIONS

6 6 11

Fill 6 gallon bucket with water

6 0 0

Empty 6 gallon bucket into 11 gallon bucket

0 0 6

Fill 6 gallon bucket with water

6 0 6

Fill 11 gallon bucket to full using filled 6 gallon bucket. This will leave 1 gallon water in 6 gallon bucket

1 0 11

Empty 11 gallon bucket into second 6 gallon bucket.

1 6 5

Empty 11 gallon bucket - wastage of 5 gallon water

1 6 0

Empty second 6 gallon bucket into 11 gallon bucket

1 0 6

Fill seccond 6 gallon bucket with water

1 6 6

Fill 11 gallon bucket to full using filled second 6 gallon bucket. This will leave 1 gallon water in second 6 gallon bucket

1 1 11

Fill first 6 gallon bucket with 1 gallon water which is in second 6 gallon bucket

2 0 11

Empty 11 gallon bucket into second 6 gallon bucket.

2 6 5

Empty 11 gallon bucket - wastage of 5 gallon water

2 6 0

Fill 11 gallon bucket with water in both the 6 gallon buckets

0 0 11

I bought a car with a peculiar 5 digit numbered licence plate which on reversing could still be read. On reversing value is increased by 78633. Whats the original number if all digits are different? Answer Only 0 1 6 8 and 9 can be read upside down. So on rearranging these digits we get the answer as 10968. Jack and Jill are playing cards for a stake of $1 a game. At the end of the evening, Jack has won 3 games and Jill has won $3. How many games did they play? Submitted by : Nathalie Drouin

Answer They played total of 9 games. Jack won 3 games and Jill won 6 games. If Jack has won three games and Jill has won $3, she lost a dollar for each loss, therefore she has won 6 and lost 3 to make $3 and he won the other 3 that she lost! Sam and Mala have a conversation. • 318

Sam says I am certainly not over 40

• •

Mala says I am 38 and you are atleast 5 years older than me Now Sam says you are atleast 39

All the statements by the two are false. How old are they really? Answer Sam is 41 and Mala is 37. Let's invert the teaser and read it like this : • • •

Sam says I am certainly over 40 Mala says I am not 38 and you are atmost 4 years older than me Now Sam says you are atmost 38

From first statement it is clear that Sam is over 40. Also, from next 2 statements it is clear that Mala is less then 38. Hence the possibilities are : Sam = 41, 42, 43, 44, 45, ...... Mala = 37, 36, 35, 34, 33, ...... It also says that the difference between their age is maximum 4 years. Hence, there is only one possible pair i.e. 41 and 37, all other combination have differences more then 4. Hence the answer - Sam is 41 and Mala is 37. A person travels on a cycle from home to church on a straight road with wind against him. He took 4 hours to reach there. On the way back to the home, he took 3 hours to reach as wind was in the same direction. If there is no wind, how much time does he take to travel from home to church? Answer Let distance between home and church is D. A person took 4 hours to reach church. So speed while travelling towards church is D/4. Similarly, he took 3 hours to reach home. So speed while coming back is D/3. There is a speed difference of 7*D/12, which is the wind helping person in 1 direction, & slowing him in the other direction. Average the 2 speeds, & you have the speed that person can travel in no wind, which is 7*D/24. Hence, person will take D / (7*D/24) hours to travel distance D which is 24/7 hours. Answer is 3 hours 25 minutes 42 seconds There are N secret agents each know a different piece of secret information. They can telephone each other and exchange all the information they know. After the telephone call, they both know anything that either of them knew before the call. What are the minimum number of telephone calls needed so that all of the them know everything? Answer (2N - 3) telephone calls, for N = 2,3 (2N - 4) telephone calls, for N > 3 319

Divide the N secret agents into two groups. If N is odd, one group will contain one extra agent. Consider first group: agent 1 will call up agent 2, agent 2 will call up agent 3 and so on. Similarly in second group, agent 1 will call up agent 2, agent 2 will call up agent 3 and so on. After (N - 2) calls, two agents in each the group will know anything that anyone knew in his group, say they are Y1 & Y2 from group 1 and Z1 & Z2 from group 2. Now, Y1 will call up Z1 and Y2 will call up Z2. Hence, in next two calls total of 4 agents will know everything. Now (N - 4) telephone calls are reqiured for remaining (N - 4) secret agents. Total telephone calls require are = (N - 2) + 2 + (N - 4) = 2N - 4 Let\'s take an example. Say there are 4 secret agents W, X, Y & Z. Divide them into two groups of 2 each i.e. (W, X) and (Y, Z). Here, 4 telephone calls are required. 1. 2. 3. 4.

W will call up X. Y will call up Z. W, who knows WX will call up Y, who knows YZ. X, who knows WX will call up Z, who knows YZ.

Take an another example. Say there are 5 secret agents J, K, L, M & N. Divide them into two groups i.e. (J, K) and (L, M, N). Here, 6 telephone calls are required. 1. 2. 3. 4. 5. 6.

J will call up K. L will call up M. M will call up N. Now M and N know LMN. J, who knows JK will call up M, who knows LMN. K, who knows JK will call up N, who knows LMN. L will call up to anyone of four.

Mrs. F has invited several wives of delegates to the United Nations for an informal luncheon. She plans to seat her 9 guests ina row such that each lady will be able to converse with the person directly to her left and right. She has prepared the following list. Mrs. F speaks English only. Mrs. G speaks English and French. Mrs. H speaks English and Russian. Mrs. J speaks Russian only. Mrs. K speaks English only. Mrs. L speaks French only. Mrs. M speaks French and German. Mrs. N speaks English and German. Mrs. O speaks English only. How many distinct seating arrangements are possible? Give all possible seating arrangements. Note that ABCD and DCBA are the same. Answer 126 distinct seating arrangements are possible. 320

Mrs. J and Mrs. H must be together and Mrs. J must be at the end as Mrs. J speaks only Russian and Mrs. H is the only other Russian speaker. Mrs. L speaks only French and there are two others - Mrs. G and Mrs. M - who speak French. Here there are 2 cases. •



CASE A : Mrs. L is at the other end If Mrs. L is at the other end, either Mrs. G or Mrs. M must seat next to her. o

CASE AA : Mrs. G seats next to Mrs. L Then, Mrs. M must seat next to Mrs. G and Mrs. N must seat next to Mrs. M. This is because Mrs. M speaks French and German, and Mrs. N is the only other German speaker. Thus, the possible seating arrangement is JHxxxNMGL, where x is the English speakers. Mrs. F, Mrs. K and Mrs. O can be arranged in remaining 3 positions in 3! different ways i.e. 6 ways.

o

CASE AB : Mrs. M seats next to Mrs. L If so, then either Mrs. N or Mrs. G must seat next to Mrs. M CASE ABA : Mrs. N seats next to Mrs. M Thus, the possible seating arrangement is JHxxxxNML, where x is the English speakers. Mrs. F, Mrs. G, Mrs. K and Mrs. O can be arranged in remaining 4 positions in 4! different ways i.e. 24 ways.



CASE ABB : Mrs. G seats next to Mrs. M Thus, the possible seating arrangement is JHxxxxGML, where x is the English speakers. Mrs. F, Mrs. K, Mrs. N and Mrs. O can be arranged in remaining 4 positions in 4! different ways i.e. 24 ways.

CASE B : Mrs. L does not seat at the end It means that Mrs. G, Mrs. L and Mrs. M must seat together. Also, Mrs. L must seat between Mrs. G and Mrs. M.

o

321



CASE BA : Mrs. G seats left and Mrs. M seats right to Mrs. L i.e. GLM



CASE BAA : GLM is at the other end Thus, the possible seating arrangement is JHxxxxGLM, where x is the English speakers. Mrs. F, Mrs. K, Mrs. N and Mrs. O can be arranged in remaining 4 positions in 4! different ways i.e. 24 ways.



CASE BAB : GLM is not at the other end Then Mrs. N must seat next to Mrs. M. Now, we have a group of four GLMN where Mrs. G and Mrs. N speak English. Thus, the possible seating arrangement is JHxxxX, where x is the individual English speakers and X is the group of four females with English speakers at the both ends. Thus, there are 4! different ways i.e. 24 ways.

o

CASE BB : Mrs. M seats left and Mrs. G seats right to Mrs. L i.e. MLG Then, Mrs. N must seat next to Mrs. M. Now, we have a group of four NMLG where Mrs. G and Mrs. N speak English. Thus, the possible seating arrangement is JHxxxX, where x is the individual English speakers and X is the group of four females with English speakers at the both ends. Thus, there are 4! different ways i.e. 24 ways.

Thus, total different possible seating arrangements are : = 6 (case AA) + 24 (case ABA) + 24 (case ABB) + 24 (case BAA) + 24 (case BAB) + 24 (case BB) = 126 seating arrangements Thus, 126 distinct seating arrangements are poosible. What is the smallest number which when divided by 10 leaves a remainder of 9, when divided by 9 leaves a remainder of 8, when divided by 8 leaves a remainder of 7, when divided by 7 leaves a remainder of 6 and so on until when divided by 2 leaves a remainder of 1? Answer The smallest such number is 2519. The easiest way is to find the Least Common Multiple (LCM) of 2, 3, 4, 5, 6, 7, 8 and 9. And subtract 1 from it. The LCM of 2, 3, 4, 5, 6, 7, 8 and 9 is given by 2520. Hence, the required number is 2519 Three friends divided some bullets equally. After all of them shot 4 bullets the total number of bullets remaining is equal to the bullets each had after division. Find the original number divided. Answer 18

Assume that initial there were 3*X bullets. So they got X bullets each after division. All of them shot 4 bullets. So now they have (X - 4) bullets each. But it is given that,after they shot 4 bullets each, total number of bullets remaining is equal to the bullets each had after division i.e. X Therefore, the equation is 3 * (X - 4) = X 3 * X - 12 = X 2 * X = 12 X=6 Therefore the total bullets before division is = 3 * X = 18 Brain Teaser No : 00114

322

Everyday in his business a merchant had to weigh amounts from 1 kg to 121 kgs, to the nearest kg. What are the minimum number of different weights required and how heavy should they be? The minimum number is 5 and they should weigh 1, 3, 9, 27 and 81 kgs Replace each letter by a digit. Each letter must be represented by the same digit and no beginning letter of a word can be 0. O N E O N E O N E + O N E ------T E N Answer Use trial and error. 0 =1, N = 8 ,E = 2, T = 7 1 8 2 1 8 2 1 8 2 + 1 8 2 -----7 2 8 A man is on a search for Atlantis and comes upon an island where all the inhabitants know whether Atlantis is still around or not. However, all of the inhabitants are either Fairies or Trolls and they all use a spell to appear humanoid so you cannot tell which is which. And the Faries always tell the truth and the Trolls always lie, but there is a slight complication, some of the Fairies have gone insane and always lie and some of the Trolls have also gone insane and always tell the truth. So here is your task: you must ask the first inhabitant that you come to ONE question and from that ONE question you must determine wether Atlantis is still around or not. What is the question that you must ask? Answer There are 2 answers to it: Answer I"Is the statement that you are reliable equivalent to the statement that Atlantis is still around?"

323

Answer II"Do

you believe that the Statement that you are a Fairy is equivalent to the statement that Atlantis is still around?" Brain Teaser No : 00276

A frog starts climbing 15 feet wall. Each hour he climbs 3 feet and rests for 30 minutes. During rest, he slips back 2 feet. How many hours does the frog take to reach the top? Answer 19 hours A frog climbs 1 foot per 1 1/2 hours as during 30 minutes rest he slips back 2 feet. This way he will climb 12 feet in 18 hours. In next hour he will climb 3 more feet i.e. he will complete 15 feet in 19 hours and will reach the top of the wall. If a bear eats 65 pounds in fish every day EXCEPT every 6th day which it only eats 45 pounds of fish. If the bear continues this, how many pounds of fish will it eat in 200 days? Submitted by : David

Answer The bear will eat 12,340 pounds of fish in 200 days. It is given that on every 6th day beareats 45 pounds of fish i.e. on day number 6, 12, 18, 24, .... 192, 198 the bear eats 45 pounds of fish. Total number of 6th days = 200/6 = 33 (the bear eats 45 pounds) Hence, the normal days are = 200 - 33 = 167 (the bear eats 65 pounds) Thus, in 200 days, the bear will eat = (167) * (65) + (33) * (45) = 10855 + 1485 = 12,340 pounds You have 3 points labelled A, B and C. You then have another 3 points labelled 1, 2 and 3. The aim of the puzzle is to connect point A with point 1, 2 and 3. Point B with point 1, 2 and 3 and point C with point 1, 2 and 3. Now while connecting the points you have to follow one rule - the lines cannot cross over each other. A B C 1 2 3 PS : You can arrange the points in order as long as the lines DO NOT cross over each other. Answer

There is no solution to it, if you consider 2 dimensions. It is impossible to join each of points A, B and C with points 1, 2 and 3 without lines crossing each other. There is solution, if you consider 3 dimensions. Consider a circular base and a line perpendicular to it passing from the center. Now take any 3 points along the perimeter of the circular base as points 1, 2 and 3. Similarly take any 3 points along the perpendicular 324

line as points A, B and C. Now it is quite simple to join each of points A, B and C with points 1, 2 and 3 without any of the lines crossing each other. The other possible 3D structure is Pyramid. Take points 1, 2 and 3 as a vertices of the triangular base and points A, B and C along the height of the Pyramid which is perpendicular to the triangular base and passing through the apex. Brain Teaser No : 00477

Suppose five bales of hay are weighed two at a time in all possible ways. The weights in pounds are 110, 112, 113, 114, 115, 116, 117, 118, 120, and 121. How much does each bale weigh? Submitted by : Travis Lara

Answer They weigh 54, 56, 58, 59, 62 pounds. Let's assume that the weight of five bales are B1, B2, B3, B4 and B5 pounds respectively. Also, B1 <= B2 <= B3 <= B4 <= B5 It is given that five bales of hay are weighed two at a time in all possible ways. It means that each of the bale is weighted four times. Thus, 4*(B1 + B2 + B3 + B4 + B5) = (110 + 112 + 113 + 114 + 115 + 116 + 117 + 118 + 120 + 121) 4*(B1 + B2 + B3 + B4 + B5) = 1156 (B1 + B2 + B3 + B4 + B5) = 289 pounds Now, B1 and B2 must add to 110 as they are the lightest one. B1 + B2 = 110 Similarly, B4 and B5 must add to 121 as they are the heaviest one. B4 + B5 = 121 From above three equation, we get B3 = 58 pounds Also, it is obvious that B1 and B3 will add to 112 - the next possible higher value. Similarly, B3 and B5 will add to 120 - the next possible lower value. B1 + B3 = 112 B3 + B5 = 120 Substituting B3 = 58, we get B1 = 54 and B5 = 62 From 2 & 3 equations, we get B2 = 56 and B4 = 59 Hence, the weight of five bales are 54, 56, 58, 59 and 62 pounds. Pinto says, "The horse is not Black." Sandy says, "The horse is either Brown or Grey." Andy says, "The horse is Brown." At least one is telling truth and at least one is lying. Can you tell the color of the horse? 325

Answer The color of the horse can be any color other than Black and Brown. If the color of the horse is Black - all are lying. If the color of the horse is Brown - all are telling truth. Thus, the horse is neither Black nor Brown.

If the color of the horse is Grey - Pinto and Sandy are telling truth whereas Andy is lying. If the color of the horse is other than Black, Brown and Grey - Pinto is telling truth whereas Sandy and Andy are lying. You must have noticed that for the given conditions, Pinto is always telling truth whereas Andy is always lying Brain Teaser No : 00258

Three convicts are brought into the warden's office. He says he can parole one of them and to decide which one he will parole he takes out 5 hats (3 red and 2 white). He stands behind them and places a hat on each one of their heads and puts the other two remaining hats in a drawer. He tells the prisioners they can look at the others hats and if they can tell which hat they have on they will be the one who is paroled. The first man looks at the other two and says, "I don't know." The second man looks at the others hats and says, "I don't know." The third man who is blind says, "Even though I have not the gift of sight I can tell by what the others have said that the color of my hat is..." What color is the blind mans hat and how does he know? Submitted

326

Answer The color of blind man's hat is Red. It is sure that the first man saw either both Red hats or one White hat and one Red hat. There are 6 such possibilities: 1) R R R 2)

R

R

W

3)

R

W

R

4)

W

R

R

5)

W

R

W

Hello sajeesh murali • my Answers • my Favourites • Modify Personal Info • Subscribe • Logout

6) W W R In all above possibilities, the first man won't be sure of the color of his hat. Now, the second man knows that the first man saw either both Red hats or one White hat and one Red hat. And, he also knows that its one of the above 6 possibilities. (like we know ;)) But he says, "I don't know". That means that (2) and (5) are not the possibilities as in either case he would be sure of the color of his hat (Red) by just looking at the third man's color of hat (White). Now, the blind man knows that there are just 4 possibilities - (1), (3), (4), (6) - and in all, the color of his hat is Red. Submit Answer

Users Answer (48)

BrainVista Answer

Puzzle A Friend

Add to Favourite

Back to Search Result

• Jigsaw Puzzle • Join the Dots • Marbles Game • Balls Game • Towers of Hanoi • Think Number • Find A Day

Brain Teaser No

Three Gold (G) coins, three Silver (S) coins and three Copper (C) coins are arranged in a single row as follow: G S C G S C G S C • • •

Only 2 adjacent unlike coins can be moved at any one time. The moved coins must be in contact with at least one other coin in line. i.e. no pair of coins is to be moved and placed away from the remaining ones. No coin pairs can be reversed i.e. a S-C combination must remain in that order in its new positionwhen it is moved.

What is the minimum number of moves required to get all the coins in following order? C C C S S S G G G Show all moves. Answer Minimum number of moves are 8. 327

Move

Order of Coins

0 S

G

S

C

G

S

C

G

S

C

G

S

C

C

S

C

G

S

C

C

S

G

G

S

C

C

S

G

G

S

C

S

C

1

G

2

G

3

G

S

C

4

G

S

C

C

5

G

S

C

C

6

G

S

C

C

C

S

7

C

C

C

8

C

C

C

S

G

S

C

G G

G

S

G

G

S

S

G

G

S

S

G

G

S

S

G

S

G

A fly is flying between two trains, each travelling towards each other on the same track at 60 km/h. The fly reaches one engine, reverses itself immediately, and flies back to the other engine, repeating the process each time. The fly is flying at 90 km/h. If the fly flies 180 km before the trains meet, how far apart were the trains initially? Answer Initially, the trains were 240 km apart. The fly is flying at the speed of 90 km/h and covers 180 km. Hence, the fly flies for 2 hours after trains started. It's obvious that trains met 2 hours after they started travelling towards each other. Also, trains were travelling at the speed of 60 km/h. So, each train traveled 120 km before they met. Hence, the trains were 240 km apart initially. What is the minimum number of numbers needed to form every number from 1 to 7,000? Example: To form 4884, you would need 2 4s & 2 8s. 4822 requires a 4, a 8, & 2 2s, but you would not count the numbers again that you had already counted from making 4884. Answer 36 You will need 3 of numbers 0, 7, 8 & 9, & 4 of numbers 1-6. A drinks machine offers three selections - Tea, Coffee or Random (Either tea or Coffee) but the machine has been wired up wrongly so that each button does not give what it claims. If each drink costs 50p, how much minimum money do you have to put into the machine to work out which button gives which selection? Submitted

328

Answer You have to put just 50p. Put 50p and push the button for Random. There are only 2 possibilities. It will give either Tea or Coffee. • •

If it gives Tea, then the button named Random is for Tea. The button named Coffee is for Random selection. And the button named Tea is for Coffee. If it gives Coffee, then the button named Random is for Coffee. The button named Tea is for Random selection. And the button named Coffee is for Tea.

Thus, you can make out which button is for what by putting just 50p and pressing Random selection first. You have 13 balls which all look identical. All the balls are the same weight except for one. Using only a balance scale, can find the odd one out with only 3 weighings? Is it possible to always tell if the odd one out is heavier or lighter than the other balls? Submitted by : Brett Hurrell

Answer It is always possible to find odd ball in 3 weighings and in most of the cases it is possible to tell whether the odd ball is heavier or lighter. Only in one case, it is not possible to tell the odd ball is whether heavier or lighter. 1. Take 8 balls and weigh 4 against 4. o If both are not equal, goto step 2 o If both are equal, goto step 3

2. One of these 8 balls is the odd one. Name the balls on heavier side of the scale as H1, H2, H3 and H4. Similarly, name the balls on the lighter side of the scale as L1, L2, L3 and L4. Either one of H's is heavier or one of L's is lighter. Weigh (H1, H2, L1) against (H3, H4, X) where X is one ball from the remaining 5 balls in intial weighing.

329

o

If both are equal, one of L2, L3, L4 is lighter. Weigh L2 against L3.  If both are equal, L4 is the odd ball and is lighter.  If L2 is light, L2 is the odd ball and is lighter.  If L3 is light, L3 is the odd ball and is lighter.

o

If (H1, H2, L1) is heavier side on the scale, either H1 or H2 is heavier. Weight H1 against H2  If both are equal, there is some error.  If H1 is heavy, H1 is the odd ball and is heavier.  If H2 is heavy, H2 is the odd ball and is heavier.

o

If (H3, H4, X) is heavier side on the scale, either H3 or H4 is heavier or L1 is lighter. Weight H3 against H4

  

If both are equal, L1 is the odd ball and is lighter. If H3 is heavy, H3 is the odd ball and is heavier. If H4 is heavy, H4 is the odd ball and is heavier.

3. One of the remaining 5 balls is the odd one. Name the balls as C1, C2, C3, C4, C5. Weight (C1, C2, C3) against (X1, X2, X3) where X1, X2, X3 are any three balls from the first weighing of 8 balls. o

If both are equal, one of remaining 2 balls is the odd i.e. either C4 or C5. Weigh C4 with X1  If both are equal, C5 is the odd ball. But you can not tell whether it is heavier or lighter.  If C4 is heavy, C4 is the odd ball and is heavier.  If C4 is light, C4 is the odd ball and is lighter.

o

If (C1, C2, C3) is heavier side, one of C1, C2, C3 is the odd ball and is heavier. Weigh C1 and C2.  If both are equal, C3 is the odd ball and is heavier.  If C1 is heavy, C1 is the odd ball and is heavier.  If C2 is heavy, C2 is the odd ball and is heavier.

o

If (C1, C2, C3) is lighter side, one of C1, C2, C3 is the odd ball and is lighter. Weigh C1 and C2.  If both are equal, C3 is the odd ball and is heavier.  If C1 is light, C1 is the odd ball and is lighter.  If C2 is light, C2 is the odd ball and is lighter.

How many squares are there in a 5 inch by 5 inch square grid? Note that the grid is made up of one inch by one inch squares. Submitted by : Kristin Monroe

Answer There are 55 squares in a 5 by 5 grid. There are 25 squares of one grid. There are 16 squares of four grids i.e. 2 by 2 There are 9 squares of nine grids i.e. 3 by 3 There are 4 squares of sixteen grids i.e. 4 by 4 There is 1 square of twenty-five girds i.e. 5 by 5 Hence, there are total 25 + 16 + 9 + 4 + 1 = 55 squares. You must have noticed one thing that total number squares possible of each size is always a perfact square i.e. 25, 16, 9, 4, 1 For a grid of N by N, the possible number of squares are = N2 + (N - 1)2 + (N - 2)2 + (N - 3)2 + ......... + 32 + 22 + 12 330

For 1 by 1 grid, total squares = 12 = 1 For 2 by 2 grid, total squares = 22 + 12 = 5 For 3 by 3 grid, total squares = 32 + 22 + 12 = 14 For 4 by 4 grid, total squares = 42 + 32 + 22 + 12 = 30 For 5 by 5 grid, total squares = 52 + 42 + 32 + 22 + 12 = 55 Five horses ran in the race. • • • • • •

There were no ties. Sikandar did not come first. Star was neither first nor last. Mughal Glory came in one place after Sikandar. Zozo was not second. Rangila was two place below Zozo.

In what order did the horses finish? Answer It's simple. Let's find the possible places horses can finish. Possibilities are: Sikandar - 2,3,4 (not 5th as Mughal Glory came one place after him) Star - 2,3,4 Mughal Glory - 3,4,5 Zozo - 1,3 (not 4th & 5th as Rangila is two place after him) Rangila - 3,5 So the result is: 1 Zozo 2 Star 3 Rangila 4 Sikandar 5 Mughal Glory If you added together the number of 2's in each of the following sets of numbers, which set would contain the most 2's: 1-333, 334-666, or 667-999? Answer 1-333 The reason why is because 200-299 each begins with a 2! If one person sends the e-mail to two friends, asking each of them to copy the mail and send it to two of their friends, those in turn send it to two of their friends and so on. How many e-mails would have been sent by the time it did 30 sets? Answer 2147483646 First person sent the mail to 2 persons. Those 2 sent the mail to 2 persons each, total 4 persons. Now, those 4 person sent mail to total 8 persons, then 8 to 16 persons, 16 to 32 persons and so on.... Hence, it a series of 2, 4, 8, 16, 32 upto 30 numbers It is a Geometric series with common ratio 2 and first number is also 2. Summation of such series 331

is given by A * (Rn - 1) / (R - 1) where A = First term R = Common Ratio n = total numbers So total number of times mail sent by the time it did 30 sets = 2 * (230 - 1) / (2 - 1)

= 2 * (1073741824 - 1) = 2 * 1073741823 = 2147483646 Brain Teaser No : 00347

At the entrance to a members club stands a stranger seeking admission. A friend told him that it's easy to get in. You just have to answer a question corrcetly! Answering wrong, however, will result in being shot! To live a little longer, the man waits in a back alley near the entrance for people to go in. After a while a man comes to the entrance. The door warden asks him: "Twelve?" to which he replies "Six!" and goes in. "That's easy." our friend thinks, but he waits a little longer. Another man comes to the door. "Six?" the door warden asks, to which he replies "Three!" and goes in. "That's too good to be true" our friend thinks, and he was right. Because, when asked "Four?", he answered "Two!" and was found dead in the alley. What was the correct answer? Submitted by : Milind Gadagkar

Answer The correct answer was "Four". The answer is the number of letters in the word spoken by the door warden. "Twelve" contains "Six" letters i.e. T, W, E, L, V, E "Six" contains "Three" letters i.e. S, I, X Similarly, "Four" contains "Four" letters i.e. F, O, U, R There is a perfect sphere of diameter 40 cms. resting up against a perfectly straight wall and a perfectly straight floor i.e. the wall and the floor make a perfect right angle. Can a perfect sphere of diameter 7 cms. pass through the space between the big sphere, the wall and the floor? Support your answer with valid arguments. Don't submit just "Yes" or "No". Submit Answer

332

Users Answer (23)

BrainVista Answer

Puzzle A Friend

Add to Favourite

For the sake of simplicity, consider two-dimension i.e view sphere as a two dimensional circle with diameter 40 cms. From Figure I, (40 cms diameter sphere) OC2 = OD2 + CD2 OC2 = 202 + 202 OC = 28.28427 cms Also, X is the closest point to origin O on the sphere. CX = 20 cms (radius) OX = OC - CX OX = 28.28427 - 20 OX = 8.28427 cms From Figure II, (7 cms diameter sphere) OP2 = OQ2 + PQ2 OP2 = (3.5)2 + (3.5)2 OP = 4.94974 cms Also, Y is the farthest point to origin O on the sphere. PY = 3.5 cms (radius) OY = OP + PY OY = 4.94974 + 3.5 OY = 8.44974 cms Now, as OY > OX i.e. smaller sphere requires more space than the space available. Hence, smaller sphere of 7 cms diameter can not pass through the space between the big sphere, the wall and the floor. The puzzle can be solved by another method. Draw a line tangent to the big sphere at the point X such that X is the closest point to the origin O on sphere. The tanget will cut X and Y axes at A and B respectively such that OA=OB. [See Fig III] From above, OX=8.28427 cms. From the right angle triangle OAB, we can deduct that OA = OB = 11.71572 cms AB = 16.56854 cms Now, the diameter of the inscribed circle of right angle triangle is given by d = a + b - c where a <= b < c The maximum possible diameter of the circle which can pass through the space between the big 333sphere, the wall and the floor is

Submit Answer

Users Answer (23)

BrainVista Answer

Puzzle A Friend

Add

Sarika multiplied 414 by certain number and obtained 69958 as the answer. But she found that there is some error in the answer - both the 9s in the answer are wrong and all the other digits are correct. Can you find the correct answer? Answer The correct answer is 60858. If you divide 69958 by 414, you will get 168.98. Hence, assume some three digit number and multiply it by 414 and use 6**58 as the answer. Assume three digit number such that * * * 4 1 4 ------------* * * * * * 0 * * * 0 0 ------------6 * * 5 8 It is obvious that the last digit of the assumed number must be 7. * * 7 4 1 4 ------------* * 8 * * 7 0 * * 8 0 0 ------------6 * * 5 8 Now, the second last digit of the assumed number must be 4 or 9. Also, the first digit of the assumed number must be 1 as the first digit of the answer is 6. Using trial and error for above two conditions, the answer is 1 4 7 4 1 4 ------------5 8 8 334

1 4 7 0 5 8 8 0 0 ------------6 0 8 5 8 Find the least number which when divided by 35, leaves remainder 25; when divided by 45, leaves remainder 35 and when divided by 55, leaves remainder 45. Answer 3455 The answer is LCM of (35, 45, 55) minus 10. LCM of (35, 45, 55) is 3465. Hence, the answer is 3455. The ratio of Boys to Girls is 6:4. 60% of the boys and 40% of the girls take lunch in the canteen. What % of class takes lunch in canteen? Answer Assume there are 6X boys and 4X Girls Total Students taking lunch in canteen = (6X)(60/100) + (4X)(40/100) = 36(X/10) + 16(X/10) = 52(X/10) Total students are = 6X + 4X = 10X % of class taking lunch in canteen = ((52X/10) * 100 ) / 10X = 52 % In the following multiplication, certain digits have been replaced with asterisks (*). Replace all the asterisks such that the problem holds the result. * * 7 X

3

*

*

----------

*

*

0

*

*

1

*

5

*

3

------------* 7 Answer

*

A simple one.

335

*

1

3

1

7

X

3

1

9

---------0

5

1

1

7

5

1

3

1

3

------------3 7 3 2 3 How long would it take you to count 1 billion orally if you could count 200 every minute and were given a day off every four years? Assume that you start counting on 1 January 2001. SubmitteAnswer 9 Years, 187 Days, 5 Hours, 20 minutes As you can count 200 per minute, to count 1 billion you require = 1,000,000,000/200 minutes = 5,000,000 minutes = 83,333.3333 hours = 3,472.2222 days = 9.512937 years = 9 Years, 187 Days, 5 Hours, 20 minutes Note that a day off every four year will be a Leap day. Hence, no need to consider leap year. dFive students - Akash, Chintan, Jignesh, Mukund and Venky - appeared for an exam. There were total five questions - two multiple choice (a, b or c) and three true/false questions. They answered five questions each and answered as follow. I II III IV V -------------------------------------------------Chintan

c

b

True

True

False

Akash

c

c

True

True

True

Jignesh

a

c

False

True

True

Mukund

b

a

True

True

False

Venky

b

b

True

False

True

-------------------------------------------------Also, no two students got the same number of correct answers. Can you tell which are the correct answers? What are their individual score? Answer The correct answers are b, a, True, False and False. Also, the scores are Jignesh (0), Akash (1), Chintan (2), Venky (3) and Mukund (4). 336

As no two students got the same number of correct answers, the total number of correct answers must be either 15 (1+2+3+4+5) or 10 (0+1+2+3+4). Let's find out the maximum number of correct answers possible from the answers given by them. For Question I = 2 (b or c) For Question II = 2 (b or c) For Question III = 4 (True) For Question IV = 4 (True) For Question V = 3 (True) Thus, the maximum number of correct answers possible are 15 (2+2+4+4+3) which means that Akash would have given all correct answers as only he answered True for questions III, IV and V. But then Chintan and Jignesh would have exactly 3 correct answers. And also, Mukund and Venky would have 2 correct answers. So no one got all five correct. One can also arrive at this conclusion by trial-and-error, but that would be bit lengthy. Now, it is clear that total number of correct answers are 10 (0+1+2+3+4). Questions III and IV both can not be False. If so, total number of correct answers would not be 10. So the student who got all wrong can not be Chintan, Akash and Mukund. If Venky got all wrong, then Chintan, Jignesh and Mukund each would have atleast 2 correct answers. It means that Akash would have to be the student with only one correct answer and the correct answers for questions I and II would be a and a respectively. But then the total number of correct answers would be 1 (a) + 1 (a) + 1 (False) + 4 (True) + 2 (Flase) = 9. Thus, Jignesh is the student with all wrong answers. The correct answers are b, a, True, False and False. Also, the scores are Jignesh (0), Akash (1), Chintan (2), Venky (3) and Mukund (4). Eleven boys and girls wait to take their seats in the same row in a movie theater. There are exactly 11 seats in the row. They decided that after the first person sits down, the next person has to sit next to the first. The third sits next to one of the first two and so on until all eleven are seated. In other words, no person can take a seat that separates him/her from at least one other person. How many different ways can this be accomplished? Note that the first person can choose any of the 11 seats. Answer There are 1024 different ways. This is the type of Brain Teaser that can be solved using the method of induction. If there is just a one person and one seat, that person has only one option. If there are two persons and two seats, it can be accomplished in 2 different ways. If there are three persons and three seats, it can be accomplished in 4 different ways. Remember that no person can take a seat that separates him/her from at least one other person. Similarly, four persons and four seats produce 8 different ways. And five persons with five seats produce 16 different ways. It can be seen that with each additional person and seat, the different ways increase by the power of two. For six persons with six seats, there are 32 different ways. 337

For any number N, the different possible ways are 2(N-1) Thus, for 11 persons and 11 seats, total different ways are 210 i.e. 1024 The secret agent X emailed a code word to his head office. They are "AIM DUE OAT TIE MOD". But four of these five words are fake and only one contains the information. The agent X also mailed a sentence as a clue - if I tell you any one character of the code word, you would be able to tell the number of vowels in the code word. Can you tell which is the code word? Answer The code word is TIE.

If you were told any one character of MOD, then you would not be able to determine whether the number of vowels are one or two. e.g. if you were told M, there are two words with M - AIM with 2 vowels and MOD with 1 vowel. So you would not be able to say the number of vowels. Same arguments can be given for characters O and D. Hence, the word with any one of M, O or D is not a code word i.e. AIM, DUE, OAT and MOD are not the code word. Thus, TIE is the code word. T : two words - TIE and OAT, both with 2 vowels I : two words - TIE and AIM, both with 2 vowels E : two words - TIE and DUE, both with 2 vowels. Brain Teaser No : 00361

Four men - Abraham, Bobby, Clinton and Denial - are standing in a straight line. 1. 2. 3. 4.

One man is fair, handsome and unscarred. Two men who are not fair, are each standing next to Abraham. Bobby is the only man standing next to exactly one handsome man. Clinton is the only man not standing next to exactly one scarred man.

Who is fair, handsome and unscarred?

Answer Clinton is fair, handsome and unscarred. From (2), both the men standing next to Abraham are not fair. Also, exactly one man is fair, handsom and unscarred. Hence, there are two cases: Case 1 :: ? (N, ?, ?) : Abraham (Y, Y, N) : ? (N, ?, ?) : ? (?, ?, ?) Case 2 :: ? (N, ?, ?) : Abraham (?, ?, ?) : ? (N, ?, ?) : ? (Y, Y, N) Note the representation - Name (Fair, Handsome, Scarred). "Y" stands for Yes and "N" stabds for No. Abraham (Y, Y, N) means Abraham is Fair, Handsome and Unscarred. It is clear that either Abraham or the man at the extreme right is fair, handsome and unscarred. 338

From (4), it is deduced that Clinton is standing next to unscarred man and each of the other men standing next to exactly one scarred man. Case 1 :: Clinton (N, ?, N) : Abraham (Y, Y, N) : ? (N, ?, Y) : ? (?, ?, Y) Case 2 :: ? (N, ?, Y) : Abraham (?, ?, Y) : ? (N, ?, N) : Clinton (Y, Y, N) From (3), Bobby is the only man standing next to exactly one handsome man. But in Case 1, Clinton is standing next to exactly one handsome man. Hence, Case 1 is not possible and Case 2 is the correct one. Case 2 :: ? (N, ?, Y) : Abraham (?, ?, Y) : ? (N, ?, N) : Clinton (Y, Y, N) Again from (3) and (4), there are 2 possibilities as shown below. Case 2a :: Denial (N, N, Y) : Abraham (?, N, Y) : Bobby (N, N, N) : Clinton (Y, Y, N) Case 2b :: Bobby (N, N, Y) : Abraham (?, Y, Y) : Denial (N, N, N) : Clinton (Y, Y, N) Thus, Clinton is fair, handsome and unscarred. Also, Abraham may be either fair or not fair. An orange colored glass has Orange juice and white colored glass has Apple juice both of equal volumes. 50ml of the orange juice is taken and poured into the white glass. After that similarly, 50ml from the white glass is poured into the orange glass. Of the two quantities, the amount of apple juice in the orange glass and the amount of orange juice in the white glass, which one is greater and by how much? Answer The two quantities are equal. Solve it by taking example. Let's assume that both glasses contain 450 ml of juice each. Now, 50ml of the orange juice is taken and poured into the White glass. Hence, orange colored glass contains 400 ml of Orange juice and white glass contains 450 ml of Apple juice and 50 ml of Orange juice i.e. total of 500 ml from white glass contains 450 ml of Apple juice and 50 ml of Orange juice. It means that every 50 ml from white glass contains 45 ml of Apple juice and 5 ml of Orange juice. Similary, 50 ml of juice from white glass is poured into orange glass. Now this 50 ml is not a pure apple juice. It contains 45 ml of Apple juice and 5 ml of Orange juice. Hence, Orange glass contains 405 ml of Orange juice and 45 ml of Apple juice. Similary, white glass contains 405 ml of Apple juice and 45 ml of Orange juice. Orange Glass Orange Juice

Apple Juice

White Glass Orange Juice

Apple Juice

Initially

450 ml

0 ml

0 ml

450 ml

50 ml from Orange Glass is poured into White Glass

400 ml

0 ml

50 ml

450 ml

50 ml from White Glass is poured into Orange Glass

405 ml

45 ml

45 ml

405 ml

339

Now it is clear that the amount of apple juice in the orange glass and the amount of orange juice in the white glass are the same. P.S. Here we assumed 450 ml as initial quantity in both the glasses just for simplicity. You can try the same by assuming any other number. But the answer is the same. Brain Teaser No : 00433

Annie, Bunnie, Candy and Dina visited Edy on 14th February. 1. The time of each visit was as follows: - Annie at 8:00 - Bunnie at 9:00 - Candy at 10:00 - Dina at 11:00 Each time mentioned above may be either AM or PM. 2. Candy did not visit Edy between Bunnie and Dina. 3. At least one female visited Edy between Annie and Bunnie. 4. Annie did not visit Edy before both Candy and Dina. Can you tell at what time did they individually visit Edy?

Answer Bunnie (9:00AM) - Dina (11:00AM) - Annie (8:00PM) - Candy (10:00PM) From the given data, it is clear that at least one female visited Edy in the morning and at least one female visited Edy in the evening. Also, from (4), Annie did not visit Edy first. It means that Annie visited Edy at 8:00 PM From (3), Bunnie must have visited Edy at 9:00 AM. Also, either Candy or Dina or both visited Edy in the morning. But from (2), only Dina must have visited Edy in the morning at 11:00 AM and hence, Candy visited Edy at 10:00 PM. The order of visits must be: Bunnie (9:00AM) - Dina (11:00AM) - Annie (8:00PM) - Candy (10:00PM) In training for a competition, you find that swimming downstream (with the current) in a river, you can swim 2 miles in 40 minutes, & upstream (against the current), you can swim 2 miles in 60 minutes. How long would it take you to swim a mile in still water? Answer You are able to swim downstream at 3 miles an hour, & upstream at 2 miles an hour. There is a difference of 1 mile an hour, which is the river helping you in 1 direction, & slowing you in the other direction. Average the 2 rates, & you have the rate that you can swim in still water, which is 2.5 miles an hour. 340

You can thus swim a mile in still water in 24 minutes. Father's age is three years more than three times the son's age. After three years, father's age will be ten years more than twice the son's age. What is the father's present age? Answer Let son's present age is X years. Hence, father's present age is (3X + 3) years. After 3 years, son's age will be (X + 3) years. and father's age will be (3X + 6) years. But given that after 3 years father's age will be ten years more than twice the son's age. (3X + 6) = 2 * (X + 3) + 10 3X + 6 = 2X + 16 X = 10 Therefore, father's present age is 33 years. Submit Answer

Users Answer (17)

Brai

Brain Teaser No : 00570

• • • • • •

A is the father of two children - B and D who are of different sexes. C is B's spouse. E is the same sex as D. B and C have the two children - F who is the same sex as B and G who is the same sex as C. E's mother, H who is married to L, is the sister of D's mother, M. E and E's spouse, I have two children - J and K who are the same sex as I.

Note that no persons have married more than once. Also, there are more number of females than males. Can you tell how many females are there?

Answer There are 7 females and 6 males. Assume that there are four sexes - male, female, X and Y. Prepare the following tree based on the data given : sister L(m) - H(f) -------------------- M(f) - A(m) |

|

|

|

E(x) - I(y) 341

D(x)

B(y) - C(x)

|

|

|

|

J(y)

K(y)

F(y)

G(x)

It is clear that there are altogether 13 persons - 2 males, 2 females, 4 Xs and 5 Ys. It is given that there are more number of females than male. Hence, all Y must represent female. Thus, there are 7 females and 6 males. A positive integer that, when added to 1000 gives a sum which is greater than when multiplied by 1000. Find the positive integer. Answer The positive integer is 1. Sum of 1 and 1000 = 1 + 1000 = 1001 Multiplication of 1 and 1000 = 1 * 1000 = 1000 Thus, sum of 1 and 1000 is greater than the multiplication of 1 and 1000. Mr. D'souza has bought four cars - Merc, Honda, Ford, Zen - as presents for his sons' birthdays, all of which are next week. Given the following information, what will each son get? Alan will not get the Honda unless Barry gets the Merc and Denzil gets the Ford. Barry will not get the Ford unless Carl gets the Zen and Alan gets the Merc. Denzil will not get the Zen unless Alan gets the Honda and Barry gets the Merc. Alan will not get the Merc unless Carl gets the Zen and Denzil gets the Ford. Barry will not get the Merc unless Alan gets the Zen and Denzil gets the Ford. Alan will not get the Zen unless Barry gets the Honda and Carl gets the Merc. Carl will not get the Zen unless Barry gets the Honda and Alan gets the Ford. Alan will not get the Ford unless Barry gets the Zen and Denzil gets the Honda. Carl will not get the Merc unless Denzil gets the Honda. Answer Let's put given 9 information in a table. The person in Bold Font will not get the corresponding car unless the persons in Normal Font get the corresponding cars. Also, the person will Italics will get the remaining car.

342

Merc

Honda

Ford

Zen

1

Barry

Alan

Denzil

Carl

2

Alan

Denzil

Barry

Carl

3

Barry

Alan

Carl

Denzil

4

Alan

Barry

Denzil

Carl

5

Barry

Carl

Denzil

Alan

6

Carl

Barry

Denzil

Alan

7

Denzil

Barry

Alan

Carl

8

Carl

Denzil

Alan

Barry

9

Carl

Denzil

?

?

Now, let's assume that Alan gets the Merc. Then from (4), Barry gets the Honda, Denzil gets the Ford and Carl gets the Zen. But from (7), Carl will not get the Zen unless Barry gets the Honda and Alan gets the Ford. Thus, it contradicts the original assumption. Hence, Alan will not get the Merc. Let's assume that Alan gets the Honda. Then from (1), Barry gets the Merc, Denzil gets the Ford and Carl gets the Zen. But from (5) or from (7), it contradicts the original assumption. Hence, Alan will not get the Honda. Let's assume that Alan gets the Ford. Then from (8), Carl gets the Merc, Denzil gets the Ford and Barry gets the Zen - which does not contradict any of the statement. Similaly, you can assume that Alan gets the Zen. (which is contradictory to (9)) Hence, Alan gets the Ford, Barry gets the Zen, Carl gets the Merc and Denzil gets the Honda. Yesterday in a party, I asked Mr. Shah his birthday. With a mischievous glint in his eyes he replied. "The day before yesterday I was 83 years old and next year I will be 86." Can you figure out what is the Date of Birth of Mr. Shah? Assume that the current year is 2000. Answer Mr. Shah's date of birth is 31 December, 1915 Today is 1 January, 2000. The day before yesterday was 30 December, 1999 and Mr. Shah was 83 on that day. Today i.e. 1 January, 2000 - he is 84. On 31 December 2000, he will be 85 and next year i.e. 31 December, 2001 - he will be 86. Hence, the date of birth is 31 December, 1915. Many people do think of Leap year and date of birth as 29th February as 2000 is the Leap year and there is difference of 3 years in Mr. Shah's age. But that is not the answer. Brain Teaser No : 00800

There are 4 mathematicians - Brahma, Sachin, Prashant and Nakul - having lunch in a hotel. Suddenly, Brahma thinks of 2 integer numbers greater than 1 and says, "The sum of the numbers is..." and he whispers the sum to Sachin. Then he says, "The product of the numbers is..." and he whispers the product to Prashant. After that following conversation takes place : Sachin : Prashant, I don't think that we know the numbers. Prashant : Aha!, now I know the numbers. Sachin : Oh, now I also know the numbers. Nakul : Now, I also know the numbers. What are the numbers? Explain your answer. Submitted

Answer The numbers are 4 and 13. As Sachin is initially confident that they (i.e. he and Prashant) don't know the numbers, we can conclude that 343

1) The sum must not be expressible as sum of two primes, otherwise Sachin could not have been sure in advance that Prashant did not know the numbers. 2) The product cannot be less than 12, otherwise there would only be one choice and Prashant would have figured that out also. Such possible sum are - 11, 17, 23, 27, 29, 35, 37, 41, 47, 51, 53, 57, 59, 65, 67, 71, 77, 79, 83, 87, 89, 93, 95, 97, 101, 107, 113, 117, 119, 121, 123, 125, 127, 131, 135, 137, 143, 145, 147, 149, 155, 157, 161, 163, 167, 171, 173, 177, 179, 185, 187, 189, 191, 197, .... Let's examine them one by one. If the sum of two numbers is 11, Sachin will think that the numbers would be (2,9), (3,8), (4,7) or (5,6). Sachin : "As 11 is not expressible as sum of two primes, Prashant can't know the numbers." Here, the product would be 18(2*9), 24(3*8), 28(4*7) or 30(5*6). In all the cases except for product 30, Prashant would know the numbers. - if product of two numbers is 18: Prashant : "Since the product is 18, the sum could be either 11(2,9) or 9(3,6). But if the sum was 9, Sachin would have deduced that I might know the numbers as (2,7) is the possible prime numbers pair. Hence, the numbers must be 2 and 9." (OR in otherwords, 9 is not in the Possible Sum List) - if product of two numbers is 24: Prashant : "Since the product is 24, the sum could be either 14(2,12), 11(3,8) or 10(4,6). But 14 and 10 are not in the Possible Sum List. Hence, the numbers must be 3 and 8." - if product of two numbers is 28: Prashant : "Since the product is 28, the sum could be either 16(2,14) or 11(4,7). But 16 is not in the Possible Sum List. Hence, the numbers must be 4 and 7." - if product of two numbers is 30: Prashant : "Since the product is 30, the sum could be either 17(2,15), 13(3,10) or 11(5,6). But 13 is not in the Possible Sum List. Hence, the numbers must be either (2,15) or (5,6)." Here, Prashant won't be sure of the numbers. Hence, Prashant will be sure of the numbers if product is either 18, 24 or 28. Sachin : "Since Prashant knows the numbers, they must be either (3,8), (4,7) or (5,6)." But he won't be sure. Hence, the sum is not 11. Summerising data for sum 11: Possible Sum PRODUCT Possible Sum

344

2+9

18

2+9=11 (possible) 3+6=9

3+8

24

2+12=14 3+8=11 (possible) 4+6=10

4+7

28

2+12=14 3+8=11 (possible) 4+6=10

5+6

30

2+15=17 (possible) 3+10=13 5+6=11 (possible)

Following the same procedure for 17: Possible Sum PRODUCT Possible Sum 2+15

30

2+15=17 (possible) 3+10= 13 5+6=11 (possible)

3+14

42

2+21=23 (possible) 3+14=17 (possible) 6+7=13

4+13

52

2+26=28 4+13=17 (possible)

5+12

60

2+30=32 3+20=23 (possible) 4+15=19 5+12=17 (possible) 6+10=16

6+11

66

2+33=35 (possible) 3+22=25 6+11=17 (possible)

7+10

70

2+35=37 (possible) 5+14=19 7+10=17 (possible)

8+9

72

2+36=38 3+24=27 (possible) 4+18=22 6+12=18 8+9=17 (possible)

Here, Prashant will be sure of the numbers if the product is 52. Sachin : "Since Prashant knows the numbers, they must be (4,13)." For all other numbers in the Possible Sum List, Prashant might be sure of the numbers but Sachin won't. Here is the step by step explaination: Sachin : "As the sum is 17, two numbers can be either (2,15), (3,14), (4,13), (5,12), (6,11), (7,10) or (8,9). Also, as none of them is a prime numbers pair, Prashant won't be knowing numbers either." Prashant : "Since Sachin is sure that both of us don't know the numbers, the sum must be one of the Possible Sum List. Further, as the product is 52, two numbers can be either (2,26) or (4,13). But if they were (2,26), Sachin would not have been sure in advance that I don't know the 345

numbers as 28 (2+26) is not in the Possible Sum List. Hence, two numbers are 4 and 13." Sachin : "As Prashant now knows both the numbers, out of all possible products - 30(2,15), 42(3,14), 52(4,13), 60(5,12), 66(6,11), 70(7,10), 72(8,9) - there is one product for which list of all possible sum contains ONLY ONE sum from the Possible Sum List. And also, no such two lists exist. [see table above for 17] Hence, two numbers are 4 and 13." Nakul figured out both the numbers just as we did by observing the conversation between Sachin and Prashant. It is interesting to note that there are no other such two numbers. We checked all the possible sums till 500 !!! Substitute digits for the letters to make the following subtraction problem true. S A N T A -

C

L

A

U

S

----------------X M A S Note that the leftmost letter can't be zero in any word. Also, there must be a one-to-one mapping between digits and letters. e.g. if you substitute 3 for the letter M, no other letter can be 3 and all other M in the puzzle must be 3. Answer One of the simplest brain teaser as there are total 26 possible answers. It is obvious that S=C+1. Since A-S=S, it is clear that A=2*S or 2*s-10. Also, L and X are interchangeable.

346

SANTA - CLAUS = XMAS

347

24034

- 16492

= 7542

24034

- 17492

= 6542

24074

- 15432

= 8642

24074

- 18432

= 5642

24534

- 16492

= 8042

24534

- 18492

= 6042

24794

- 16452

= 8342

24794

- 18452

= 6342

24804

- 15462

= 9342

24804

- 19462

= 5342

24974

- 16432

= 8542

24974

- 18432

= 6542

36806

- 27643

= 9163

36806

- 29643

= 7163

36156

- 27693

= 8463

36156

- 28693

= 7463

62132

- 54206

= 7926

62132

- 57206

= 4926

62172

- 53246

= 8926

62172

- 58246

= 3926

62402

- 53276

= 9126

62402

- 59276

= 3126

62712

- 53286

= 9426

62712

- 59286

= 3426

62932

- 58206

= 4726

62932

- 54206

= 8726

Oracle Oracle 7 Concepts and Architecture Database Structures. 1. What are the Oracle Database?.

components of Physical database

structure of

ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and one or more Control files. 2. What are the ORACLE database?

components

of

Logical

database

structure

of

Tablespaces and the Database's Schema Objects. 3. What is a Tablespace? A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together. 4. What is SYSTEM tablespace and When is it Created? Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. 5. Explain the relationship among Database, Tablespace and Data file. Each databases logically divided into one or more tablespaces One or more data files are explicitly created for each tablespace. 6. What is schema? A schema is collection of database objects of a User. 7. What are Schema Objects ? Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages anddatabase links. 8. Can objects of the same Schema reside in different tablespaces.? 348

Yes. 9. Can a Tablespace hold objects from different Schemes ? Yes. 10. what is Table ? A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns. 11. What is a View ? A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.) 12. Do

View contain Data ?

Views do not contain or store data. 13. Can a

View based on another View ?

Yes. 14. What are the advantages of Views ? Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table. Hide data complexity. Simplify commands for the user. Present the data in a different perpecetive from that of the base table. Store complex queries. 15. What is a Sequence ? A sequence generates a serial list of unique numbers for numerical columns of a database's tables. 16.

What is a Synonym ?

A synonym is an alias for a table, view, sequence or program unit. 17. What are the type of Synonyms? There are two types of Synonyms Private and Public. 18. What is a Private Synonyms ? A Private Synonyms can be accessed only by the owner. 19. What is a Public Synonyms ? A Public synonyms can be accessed by any user on the database. 20. What are synonyms used for ? Synonyms are used to : Mask the real name and owner of an object. 349

Provide public access to an object Provide location transparency for tables,views or program units of a remote database. Simplify the SQL statements for database users. 21. What is an Index ? An Index is an optional structure associated with a table to have direct access to rows,which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

350

22.

How are Indexes Update ?

Indexes are automatically maintained and used by ORACLE. Changes to table data are automatically incorporated into all relevant indexes. 23. What are Clusters ? Clusters are groups of one or more tables physically together to share common columns and are often used together.

stores

24. What is cluster Key ? The related columns of the tables in a cluster is called the Cluster Key. 25. What is Index Cluster ? A Cluster with an index on the Cluster Key. 26. What is Hash Cluster ? A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk. 27. When can Hash Cluster used ? Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows. 28. What is

Database Link ?

A database link is a named object that describes a "path" from one database to another. 29. What are the types of Database Links ? Private Database Link, Public Database Link & Network Database Link. 30. What is Private Database Link ? Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures. 31. What is Public Database Link ? Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

351

32.

What is Network Database link ?

Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition. 33. What is Data Block ? ORACLE database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk. 34. How to define Data Block size ? A data block size is specified for each ORACLE database when the database is created. A database users and allocated free database space in ORACLE datablocks. Block size is specified in INIT.ORA file and cann't be changed latter. 35. What is Row Chaining ? In Circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs , the data for the row is stored in a chain of data block (one or more) reserved for that segment. 36. What is an Extent ? An Extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information. 37.

What is a Segment ?

A segment is a set of extents allocated for a certain logical structure. 38. What are the different type of Segments ? Data Segment, Index Segment, Rollback Segment and Temporary Segment. 39. What is a Data Segment ? Each Non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment. 40. What is an Index Segment ? Each Index has an Index segment that stores all of its data. 41. What is

Rollback Segment ?

A Database contains one store "undo" information.

or

more Rollback Segments to temporarily

42. What are the uses of Rollback Segment ? 352

Rollback Segments are used : To generate read-consistent database information during recovery to rollback uncommitted transactions for users.

database

43. What is a Temporary Segment ? Temporary segments are created by ORACLE needs a temporary work area to complete statement finishes execution, the temporary released to the system for future use.

when a SQL statement execution. When the segment extents are

44. What is a Data File ? Every ORACLE database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database. 45. What are the Characteristics of Data Files ? A data file can be associated with only one database.Once created a data file can't change size. One or more data files form a logical unit of database storage called a tablespace. 46. What is a Redo Log ? The set of Redo Log files the database's redo log.

for a database is collectively known as

47. What is the function of Redo Log ? The Primary function of the redo log is to record all changes made to data. 48. What is the use of Redo Log Information ? The Information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database's data files. 49. What does a Control file Contain ? A Control file records the physical structure of the database. It contains the following information. Database Name Names and locations of a database's files and redolog files. Time stamp of database creation. 50. What is the use of Control File ? When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery. 353

51. What is a Data Dictionary ? The data dictionary of an ORACLE database is a set of tables and views that are used as a read-only reference about the database. It stores information about both the logical and physical structure of the database, the valid users of an ORACLE database, integrity constraints defined for tables in the database and space allocated for a schema object and how much of it is being used. 52. What is an Integrity Constrains ? An integrity constraint is a declarative way to define a business rule for a column of a table. 53. Can an Integrity Constraint be enforced on a table if some existing table data does not satisfy the constraint ? No. 54. Describe the different type of Integrity Constraints supported by ORACLE ? NOT NULL Constraint - Disallows NULLs in a table's column. UNIQUE Constraint - Disallows duplicate values in a column or set of columns. PRIMARY KEY Constraint - Disallows duplicate values and NULLs in a column or set of columns. FOREIGN KEY Constrain - Require each value in a column or set of columns match a value in a related table's UNIQUE or PRIMARY KEY. CHECK Constraint - Disallows values that do not satisfy the logical expression of the constraint. 55. What is difference between UNIQUE constraint and PRIMARY KEY constraint ? A column defined as UNIQUE can contain NULLs while a column defined as PRIMARY KEY can't contain Nulls. 56. Describe Referential Integrity ? A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only if the value for the column or set of columns (the dependent value) matches a value in a column of a related table (the referenced value). It also specifies the type of data manipulation allowed on referenced data and the action to be performed on dependent data as a result of any action on referenced data. 57. What are the integrity constraint ?

Referential actions supported by FOREIGN KEY

UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of referenced data. DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted. 58. What is self-referential integrity constraint ? 354

If a foreign key reference a parent key called self-referential integrity constraint.

of the same table is

59. What are the Limitations of a CHECK Constraint ? The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain subqueries, sequence, the SYSDATE,UID,USER or USERENV SQL functions, or the pseudo columns LEVEL or ROWNUM. 60. What is the maximum defined on a column ? No Limit.

number

of

CHECK

constraints

that

can

be

SYSTEM ARCHITECTURE : 61. What constitute an ORACLE Instance ? SGA and ORACLE background processes constitute an ORACLE instance. (or) Combination of memory structure and background process. 62. What is SGA ? The System Global Area (SGA) is a shared memory region allocated by ORACLE that contains data and control information for one ORACLE instance. 63. What are the components of SGA ? Database buffers, Redo Log Buffer the Shared Pool and

Cursors.

64. What do Database Buffers contain ? Database buffers store the most recently data. It can also contain modified data permanently written to disk. 65. What do Redo Log Buffers contain ? Redo Log Buffer stores redo entries database. 66. What is Shared Pool ? Shared Pool is a portion of the constructs such as shared SQL areas.

a

SGA

log

used blocks of database that has not yet been

that

of

changes

contains

made

shared

to

the

memory

67. What is Shared SQL Area ? A Shared SQL area is required to process every unique SQL statement submitted to a database and contains information such as the parse tree and execution plan for the corresponding statement. 68. What is Cursor ? A Cursor is a handle ( a name or pointer) for the memory associated with a specific statement. 69. What is PGA ? Program Global Area (PGA) is a memory buffer that contains data and control information for a server process. 70. What is User Process ? 355

A user process is created and maintained to execute the software code of an application program. It is a shadow process created automatically to facilitate communication between the user and the server process. 71. What is Server Process ? Server Process handle requests from connected user process. A server process is in charge of communicating with the user process and interacting with ORACLE carry out requests of the associated user process. 72. What are the two types of Server Configurations ? Dedicated Server Configuration and Multi-threaded Server Configuration. 73. What is Dedicated Server Configuration ? In a Dedicated Server Configuration a Server Process handles requests for a Single User Process. 74. What is a Multi-threaded Server Configuration ? In a Multi-threaded Server Configuration many user processes share a group of server process. 75. What is a Parallel Server option in ORACLE ? A configuration for loosely coupled systems where multiple instance share a single physical database is called Parallel Server. 76. Name the ORACLE Background Process ? DBWR - Database Writer. LGWR - Log Writer CKPT - Check Point SMON - System Monitor PMON - Process Monitor ARCH - Archiver RECO - Recover Dnnn - Dispatcher, and LCKn - Lock Snnn - Server. 77. What Does DBWR do ? Database writer writes cache to the data files.

modified blocks from the database buffer

78.When Does DBWR write to the database ? DBWR writes when more data needs to be read into the SGA and too few database buffers are free. The least recently used data is written to the data files first. DBWR also writes when CheckPoint occurs. 79. What does LGWR do ? Log Writer (LGWR) writes redo log entries generated in the redo log buffer of the SGA to on-line Redo Log File. 80. When does LGWR write to the database ? LGWR writes redo log entries into an on-line redo when transactions commit and the log buffer files are full. 81. What is the function of checkpoint(CKPT)? 356

log

file

The Checkpoint (CKPT) process is responsible for signaling DBWR at checkpoints and updating all the data files and control files of the database. 82. What are the functions of SMON ? System Monitor (SMON) performs instance recovery at instance startup. In a multiple instance system (one that uses the Parallel Server), SMON of one instance can also perform instance recovery for other instance that have failed SMON also cleans up temporary segments that are no longer in use and recovers dead transactions skipped during crash and instance recovery because of file-read or off-line errors. These transactions are eventually recovered by SMON when the tablespace or file is brought back on-line SMON also coalesces free extents within the database to make free space contiguous and easier to allocate. 83. What are functions of PMON ? Process Monitor (PMON) performs process recovery when a user process fails PMON is responsible for cleaning up the cache and Freeing resources that the process was using PMON also checks on dispatcher and server processes and restarts them if they have failed. 84. What is the function of ARCH ? Archiver (ARCH) copies the on-line redo log files to archival storage when they are full. ARCH is active only when a database's redo log is used in ARCHIVELOG mode. 85. What is function of RECO ? RECOver (RECO) is used to resolve distributed transactions that are pending due to a network or system failure in a distributed database. At timed intervals,the local RECO attempts to connect to remote databases and automatically complete the commit or rollback of the local portion of any pending distributed transactions. 86. What is the function of Dispatcher (Dnnn) ? Dispatcher (Dnnn) process is responsible for routing requests from connected user processes to available shared server processes and returning the responses back to the appropriate user processes. 87. How many Dispatcher Processes are created ? Atleast one Dispatcher process is created for protocol in use.

every

communication

88. What is the function of Lock (LCKn) Process ? Lock (LCKn) are used for inter-instance locking when the ORACLE Parallel Server option is used. 89. What is the maximum number of Lock Processes used ? Though a single LCK process is sufficient for most Parallel Server systems upto Ten Locks (LCK0,....LCK9) are used for inter-instance locking.

357

DATA ACCESS 90. Define Transaction ? A Transaction is a logical unit of work that comprises one or more SQL statements executed by a single user. 91. When does a Transaction end ? When it is committed or Rollbacked. 92. What does COMMIT do ? COMMIT makes permanent the changes resulting from all SQL statements in the transaction. The changes made by the SQL statements of a transaction become visible to other user sessions transactions that start only after transaction is committed. 93. What does ROLLBACK do ? ROLLBACK retracts any of statements in the transaction.

the

changes

resulting

from

the

SQL

94. What is SAVE POINT ? For long transactions that contain many SQL statements, intermediate markers or savepoints can be declared which can be used to divide a transaction into smaller parts. This allows the option of later rolling back all work performed from the current point in the transaction to a declared savepoint within the transaction. 95. What is Read-Only Transaction ? A Read-Only transaction ensures that the results of each query executed in the transaction are consistant with respect to the same point in time. 96. What is the function of Optimizer ? The goal of the optimizer is to choose the most efficient way to execute a SQL statement. 97. What is Execution Plan ? The combinations of the steps the optimizer chooses to execute a statement is called an execution plan. 98. What are the different approaches used by Optimizer in choosing an execution plan ? Rule-based and Cost-based. 99. What are the factors that affect OPTIMIZER in choosing an Optimization approach ? The OPTIMIZER_MODE initialization parameter Statistics in the Data Dictionary the OPTIMIZER_GOAL parameter of the ALTER SESSION command hints in the statement. 100. What are the values that can be specified for OPTIMIZER MODE Parameter ? COST and RULE. 101. Will the Optimizer always OPTIMIZER_MODE is set to "Cost'? 358

use

COST-based

approach

if

Presence of statistics in the data dictionary for atleast one of the tables accessed by the SQL statements is necessary for the OPTIMIZER to use COST-based approach. Otherwise OPTIMIZER chooses RULEbased approach. 102. What is the effect of setting the value of OPTIMIZER_MODE to 'RULE' ? This value causes the optimizer to choose the rule_based approach for all SQL statements issued to the instance regardless of the presence of statistics. 103. What are the values that can be parameter of the ALTER SESSION Command ?

specified

for

OPTIMIZER_GOAL

CHOOSE,ALL_ROWS,FIRST_ROWS and RULE. 104. What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL, parameter of the ALTER SESSION Command ? The Optimizer chooses Cost_based approach and optimizes with the goal of best throughput if statistics for atleast one of the tables accessed by the SQL statement exist in the data dictionary. Otherwise the OPTIMIZER chooses RULE_based approach. 105. What is the effect of setting the value "ALL_ROWS" for OPTIMIZER_GOAL parameter of the ALTER SESSION command ? This value causes the optimizer to the cost-based approach for all SQL statements in the session regardless of the presence of statistics and to optimize with a goal of best throughput. 106. What is the effect of setting the value 'FIRST_ROWS' for OPTIMIZER_GOAL parameter of the ALTER SESSION command ? This value causes the optimizer to use the cost-based approach for all SQL statements in the session regardless of the presence of statistics and to optimize with a goal of best response time. 107. What is the effect of setting the 'RULE' for OPTIMIER_GOAL parameter of the ALTER SESSION Command ? This value causes the optimizer to choose the rule-based approach for all SQL statements in a session regardless of the presence of statistics. 108. What is RULE-based approach to optimization ? Choosing an executing planbased on the access paths available and the ranks of these access paths. 109. What is COST-based approach to optimization ? Considering available access paths and determining the most efficient execution plan based on statistics in the data dictionary for the tables accessed by the statement and their associated clusters and indexes.

PROGRAMMATIC CONSTRUCTS 359

110. What are the different types of PL/SQL program units that can be defined and stored in ORACLE database ? Procedures and Functions,Packages and Database Triggers. 111. What is a Procedure ? A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve a specific problem or perform a set of related tasks. 112. What is difference between Procedures and Functions ? A Function returns a value to the caller where as a Procedure does not. 113. What is a Package ? A Package is a collection of related procedures, functions, variables and other package constructs together as a unit in the database. 114. What are the advantages of having a Package ? Increased functionality (for example,global package variables can be declared and used by any proecdure in the package) and performance (for example all objects of the package are parsed compiled, and loaded into memory once) 115. What is Database Trigger ? A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a result of an insert in,update to, or delete from a table. 116. What are the uses of Database Trigger ? Database triggers can be used to automatic data generation, audit data modifications, enforce complex Integrity constraints, and customize complex security authorizations. 117. What are the differences between Database Trigger and Integrity constraints ? A declarative integrity constraint is a statement about the database that is always true. A constraint applies to existing data in the table and any statement that manipulates the table. A trigger does not apply to data loaded before the definition of the trigger, therefore, it does not guarantee all data in a table conforms to the rules established by an associated trigger. A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.

360

DATABASE SECURITY 118. What are Roles ? Roles are named groups of related privileges that are granted to users or other roles. 119. What are the use of Roles ? REDUCED GRANTING OF PRIVILEGES - Rather than explicitly granting the same set of privileges to many users a database administrator can grant the privileges for a group of related users granted to a role and then grant only the role to each member of the group. DYNAMIC PRIVILEGE MANAGEMENT - When the privileges of a group must change, only the privileges of the role need to be modified. The security domains of all users granted the group's role automatically reflect the changes made to the role. SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can be selectively enable (available for use) or disabled (not available for use). This allows specific control of a user's privileges in any given situation. APPLICATION AWARENESS - A database application can be designed to automatically enable and disable selective roles when a user attempts to use the application. 120. How to prevent unauthorized use of privileges granted to a Role ? By creating a Role with a password. 121. What is default tablespace ? The Tablespace to contain specifying a tablespace name.

schema

objects

created

without

122. What is Tablespace Quota ? The collective amount of disk space available to the objects in a schema on a particular tablespace. 123. What is a profile ? Each database user is assigned a Profile that specifies limitations on various system resources available to the user. 124. What are the system resources that can be controlled through Profile ? The number of concurrent sessions the user can establish the CPU processing time available to the user's session the CPU processing time available to a single call to ORACLE made by a SQL statement the amount of logical I/O available to the user's session the amout of logical I/O available to a single call to ORACLE made by a SQL statement the allowed amount of idle time for the user's session the allowed amount of connect time for the user's session. 125. What is Auditing ? Monitoring of user access to aid in the investigation of database use. 126. What are the different Levels of Auditing ? Statement Auditing, Privilege Auditing and Object Auditing. 361

127. What is Statement Auditing ? Statement auditing is the auditing of the powerful system privileges without regard to specifically named objects. 128. What is Privilege Auditing ? Privilege auditing is the auditing of the use of powerful privileges without regard to specifically named objects. 129. What is Object Auditing ? Object auditing is the auditing objects without regard to user.

system

of accesses to specific schema

DISTRIBUTED PROCESSING AND DISTRIBUTED DATABASES 130. What is Distributed database ? A distributed database is a network of databases managed by multiple database servers that appears to a user as single logical database. The data of all databases in the distributed database can be simultaneously accessed and modified. 131. What is Two-Phase Commit ? Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. It has two phase, a Prepare Phase and a Commit Phase. 132. Describe two phases of Two-phase commit ? Prepare phase - The global coordinator (initiating node) ask a participants to prepare (to promise to commit or rollback the transaction, even if there is a failure) Commit - Phase - If all participants respond to the coordinator that they are prepared, the coordinator asks all nodes to commit the transaction, if all participants cannot prepare, the coordinator asks all nodes to roll back the transaction. 133. What is the mechanism provided by ORACLE for table replication ? Snapshots and SNAPSHOT LOGs 134. What is a SNAPSHOT ? Snapshots are read-only copies of a master table located on a remote node which is periodically refreshed to reflect changes made to the master table. 135. What is a SNAPSHOT LOG ? A snapshot log is a table in the master database that is associated with the master table. ORACLE uses a snapshot log to track the rows that have been updated in the master table. Snapshot logs are used in updating the snapshots based on the master table. 136. What is a SQL * NET? SQL *NET is ORACLE's mechanism for interfacing with the communication protocols used by the networks that facilitate distributed processing and distributed databases. It is used in Clint-Server and Server-Server communications. 362

DATABASE OPERATION, BACKUP AND RECOVERY 137. What are the steps involved in Database Startup ? Start an instance, Mount the Database and Open the Database. 138. What are the steps involved in Database Shutdown ? Close the Database, Dismount the Database and Shutdown the Instance. 139. What is Restricted Mode of Instance Startup ? An instance can be started in (or later altered to be in) restricted mode so that when the database is open connections are limited only to those whose user accounts have been granted the RESTRICTED SESSION system privilege. 140. What are the different modes of mounting a Database with the Parallel Server ? Exclusive Mode If the first instance that mounts a database does so in exclusive mode, only that Instance can mount the database. Parallel Mode If the first instance that mounts a database is started in parallel mode, other instances that are started in parallel mode can also mount the database. 141. What is Full Backup ? A full backup is an operating system backup of all data files, on-line redo log files and control file that constitute ORACLE database and the parameter. 142. Can Full Backup be performed when the database is open ? No. 143. What is Partial Backup ? A Partial Backup is any operating system backup short of a full backup, taken while the database is open or shut down. 144.WhatisOn-lineRedoLog? The On-line Redo Log is a set of tow or more on-line redo files that record all committed changes made to the database. Whenever a transaction is committed, the corresponding redo entries temporarily stores in redo log buffers of the SGA are written to an on-line redo log file by the background process LGWR. The on-line redo log files are used in cyclical fashion. 145. What is Mirrored on-line Redo Log ? A mirrored on-line redo log consists of copies of on-line redo log files physically located on separate disks, changes made to one member of the group are made to all members. 146. What is Archived Redo Log ? Archived Redo Log consists archived before being reused.

363

of

Redo

Log

files

that

have

147. What are the advantages of operating a database in ARCHIVELOG mode over operating it in NO ARCHIVELOG mode ? Complete database recovery from disk failure is possible only in ARCHIVELOG mode. Online database backup is possible only in ARCHIVELOG mode. 148. What is Log Switch ? The point at which ORACLE ends writing to one online redo log file and begins writing to another is called a log switch. 149. What are the steps involved in Instance Recovery ? R_olling forward to recover data that has not been recorded in data files, yet has been recorded in the on-line redo log, including the contents of rollback segments. Rolling back transactions that have been explicitly rolled back or have not been committed as indicated by the rollback segments regenerated in step a. Releasing any resources (locks) held by transactions in process at the time of the failure. Resolving any pending distributed transactions phase commit at the time of the instance failure.

undergoing

a two-

Data Base Administration Introduction to DBA 1. What is a Database instance ? Explain A database instance (Server) is a set of memory structure and background processes that access a set of database files. The process can be shared by all users. The memory structure that are used to store most queried data from database. This helps up to improve database performance by decreasing the amount of I/O performed against data file. 2. What is Parallel Server ? Multiple instances Multi-CPU environments)

accessing

the

same

database

(Only

In

3. What is a Schema ? The set of objects owned by user account is called the schema. 4.

What is an Index ? How it is implemented in Oracle Database ?

An index is a database structure used by the server to have direct access of a row in a table. An index is automatically created when a unique of primary constraint clause is specified in create table comman (Ver 7.0) 364

key

5. What is clusters ? Group of tables physically stored together because they share common columns and are often used together is called Cluster. 6. What is a cluster Key ? The related columns of the tables are called the cluster key. The cluster key is indexed using a cluster index and its value is stored only once for multiple tables in the cluster. 7. What are Database ?

the

basic

element

of

Base

configuration

It consists of one or more data files. one or more control files. two or more redo log files. The Database contains multiple users/schemas one or more rollback segments one or more tablespaces Data dictionary tables User objects (table,indexes,views etc.,) The server that access the database consists of SGA (Database buffer, Dictionary Cache buffers, Shared SQL pool) SMON (System MONito) PMON (Process MONitor) LGWR (LoG Write) DBWR (Data Base Write) ARCH (ARCHiver) CKPT (Check Point) RECO Dispatcher User Process with associated PGS

of

an

oracle

Buffers, Redo log

8. What is a deadlock ? Explain . Two processes wating to update the rows of a table which are locked by the other process then deadlock arises. In a database environment this will often happen because of not issuing proper row lock commands. Poor design of front-end application may cause this situation and the performance of server will reduce drastically. These locks will be released automatically when a commit/rollback operation performed or any one of this processes being killed externally.

365

MEMORY MANAGEMENT 9. What is SGA ? How it is different from

Ver 6.0 and Ver 7.0 ?

The System Global Area in a Oracle database is the area in memory to facilitates the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is Database buffers, Dictionary cache, Redo Log Buffer and Shared SQL pool (ver 7.0 only) area. 10. What is a Shared SQL pool ? The data dictionary cache is stored in an area in SGA called the Shared SQL Pool. This will allow sharing of parsed SQL statements among concurrent users. 11. What is mean by Program Global Area (PGA) ? It is area in memory that is used by a Single Oracle User Process. 12. What is a data segment ? Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored. 13. What are the factors causing the reparsing of SQL statements in SGA? Due to insufficient Shared SQL pool size. Monitor the ratio of the reloads SQL statements. If the ratio increase the SHARED_POOL_SIZE.

takes place while executing is greater than 1 then

LOGICAL & PHYSICAL ARCHITECTURE OF DATABASE. 14. What is

Database Buffers ?

Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size. 15. What is dictionary cache ? Dictionary cache is information about the databse objects stored in a data dictionary table. 16. What is meant by recursive hints ? Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of Data Dictionary Cache. 366

17. What is meant by redo log buffer ? Change made to entries are written to the on-line redo log files. So that they can be used in roll forward operations during database recoveries. Before writing them into the redo log files, they will first brought to redo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size. 18. How will you swap objects into a different table space for an existing database ? Export the user Perform import using the command imp system/manager file=export.dmp indexfile=newrite.sql. This will create all definitions into newfile.sql. Drop necessary objects. Run the script newfile.sql after altering the tablespaces. Import from the backup for the necessary objects. 19. List the Optional Flexible Architecture (OFA) of Oracle database ? or How can we organise the tablespaces in Oracle database to have maximum performance ? SYSTEM - Data dictionary tables. DATA - Standard operational tables. DATA2- Static tables used for standard operations INDEXES - Indexes for Standard operational tables. INDEXES1 - Indexes of static tables used for standard operations. TOOLS - Tools table. TOOLS1 - Indexes for tools table. RBS - Standard Operations Rollback Segments, RBS1,RBS2 - Additional/Special Rollback segments. TEMP - Temporary purpose tablespace TEMP_USER - Temporary tablespace for users. USERS - User tablespace. 20. How will you force database to use particular rollback segment ? SET TRANSACTION USE ROLLBACK SEGMENT rbs_name. 21. What is meant by free extent ? A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free. 22. How free extents are managed in Ver 6.0 and Ver 7.0 ? Free extents cannot be merged together in Ver 6.0. Free extents are periodically coalesces with the extent in Ver 7.0 367

neighboring

free

23.Which parameter in Storage clause will reduce no. of rows per block? PCTFREE parameter Row size also reduces no of rows per block. 24. What is the significance of having storage clause ? We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updations etc., 25. How does Space allocation table place within a block ? Each block contains entries as follows Fixied block header Variable block header Row Header,row date (multiple rows may exists) PCTEREE (% of free space for row updation in future) 26. What is the role of PCTFREE parameter is Storage clause ? This is used to reserve expansion of rows.

certain

amount

of

space

in

a

block

for

27. What is the OPTIMAL parameter ? It is used to set the optimal length of a rollback segment. 28. What is the functionality of SYSTEM table space ? To manage the database level transactions such as modifications of the data dictionary table that record information about the free space usage. 29. How will you create multiple rollback segments in a database ? Create a database which implicitly creates a SYSTEM Rollback Segment in a SYSTEM tablespace. Create a Second Rollback Segment name R0

in the SYSTEM tablespace.

Make new rollback segment available (After shutdown, modify init.ora file and Start database) Create other tablespaces (RBS) Deactivate Rollback rollback segments.

Segment

for rollback segments. R0

and

activate the newly created

30. How the space utilisation takes place within rollback segments ? It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is in use then it forced to acquire a new extent (No. of extents is based on the optimal size) 368

31. Why query fails sometimes ? Rollback segment entry loads.

dynamically

extent

to handle larger transactions

A single transaction may wipeout all avaliable free space in the Rollback Segment Tablespace. This prevents other user using Rollback segments. 32. How will you monitor the space allocation ? By quering DBA_SEGMENT table/view. 33. How

will you monitor rollback segment status ?

Querying the DBA_ROLLBACK_SEGS view IN USE - Rollback Segment is on-line. AVAILABLE - Rollback Segment available but not on-line. OFF-LINE - Rollback Segment off-line INVALID - Rollback Segment Dropped. NEEDS RECOVERY - Contains data but need recovery or corupted. PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed database. 34. List the sequence of events when a large transaction that exceeds beyond its optimal value when an entry wraps and causes the rollback segment to expand into another extend. Transaction Begins. An entry is made in the RES header for new transactions entry Transaction acquires blocks in an extent of RBS The entry attempts to wrap into second extent. None is available, so that the RBS must extent. The RBS checks to see if it is part of its OPTIMAL size. RBS chooses its oldest inactive segment. Oldest inactive segment is eliminated. RBS extents The Data dictionary table for space management are updated. Transaction Completes. 35. How can we plan storage for very large tables ? Limit the number of extents in the table Separate Table from its indexes. Allocate Sufficient temporary storage. 36. How will you estimate the space required by a non-clustered tables? Calculate Calculate Calculate Calculate Calculate 369

the the the the the

total header size available dataspace per data block combined column lengths of the average row total average row size. average number rows that can fit in a block

Calculate the number of blocks and bytes required for the table. After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table. 37. It is possible to use raw devices the advantages over file. system files ?

as data files and what is

Yes. The advantages over file system files. I/O will be improved because which writing into disk. Disk Corruption will be very less.

Oracle

is

bye-passing the kernnel

38. What is a Control file ? Database's overall physical architecture is maintained in a file called control file. It will be used to maintain internal consistency and guide recovery operations. Multiple copies of control files are advisable. 39. How to database ?

implement

the

multiple

control

files

for

an

existing

Shutdown the databse Copy one of the existing control file to new location Edit Config ora file by adding new control file.name Restart the database. 40. What is meant by Redo Log file mirrorring ? How it can be achieved? Process of having a copy of redo log files is called mirroring. This can be achieved by creating group of log files together, so that LGWR will automatically writes them to all the members of the current on-line redo log group. If any one group fails then database automatically switch over to next group. It degrades performance. 41. What is advantage of having disk shadowing/ Mirroring ? Shadow set of disks save as a backup in the event of disk failure. In most Operating System if any disk failure occurs it automatically switchover to place of failed disk. Improved performance because most OS support volume shadowing can direct file I/O request to use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks. 42. What is use of Rollback Segments In Database ? They allow the database multiple transactions.

370

to

maintain

read consistency between

43. What is a Rollback segment entry ? It is the set of before image data blocks that contain rows that are modified by a transaction. Each Rollback Segment entry must be completed within one rollback segment. A single rollback segment can have multiple rollback segment entries. 44. What is hit It is a for data.

ratio ?

measure

of

well the data cache buffer is handling requests

Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads. 45. When will be a segment released ? When Segment is dropped. When Shrink (RBS only) When truncated (TRUNCATE used with drop storage option) 46. What are disadvanteges of having raw devices ? We should depend (fully reliable)

on

export/import

utility

for

backup/recovery

The tar command cannot be used for physical file backup, instead we can use dd command which is less flexible and has limited recoveries. 47. List the factors that can affect the accuracy of the estimations ? The space used transaction entries and deleted records does not become free immediately after completion due to delayed cleanout. Trailling nulls and length bytes are not stored. Inserts of, updates to and deletes of rows as well as columns larger than a single datablock, can cause fragmentation an chained row pieces. DATABASE SECURITY & ADMINISTRATION 48. What is user Account in Oracle database ? An user account is not a physical structure in Database but it is having important relationship to the objects in the database and will be having certain privileges. 49. How will you enforce security using stored procedures ? Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. 371

50. What are the dictionary tables used to monitor a database spaces ? DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. 51. What are the responsibilities of a Database Administrator ? Installing and upgrading the Oracle Server and application tools. Allocating system storage and planning future storage requirements for the database system. Managing primary database structures (tablespaces) Managing primary objects (table,views,indexes) Enrolling users and maintaining system security. Ensuring compliance with Oralce license agreement Controlling and monitoring user access to the database. Monitoring and optimising the performance of the database. Planning for backup and recovery of database information. Maintain archived data on tape Backing up and restoring the database. Contacting Oracle Corporation for technical support. 52. What are the database ?

the roles

and user accounts created automatically with

DBA - role Contains all database system privileges. SYS user account - The DBA role will be assigned to this account. All of the basetables and views for the database's dictionary are store in this schema and are manipulated only by ORACLE. SYSTEM user account - It has all the system privileges for the database and additional tables and views that display administrative information and internal tables and views used by oracle tools are created using this username. 54. What are the database administrators utilities avaliable ? SQL * DBA - This allows DBA to monitor and control an ORACLE database. SQL * Loader - It loads data from standard operating system files (Flat files) into ORACLE database tables. Export (EXP) and Import (imp) utilities allow you to move existing data in ORACLE format to and from ORACLE database. 55. What are the file (init.ora) ?

minimum

parameters should exist in the parameter

DB NAME - Must set to a text string of no more than 8 characters and it will be stored inside the datafiles, redo log files and control files and control file while database creation.

372

DB_DOMAIN - It is string that specifies the network domain where the database is created. The global database name is identified by setting these parameters (DB_NAME & DB_DOMAIN) CONTORL FILES - List of control filenames of the database. If name is not mentioned then default name will be used. DB_BLOCK_BUFFERS cache in SGA.

-

To

determine the no of buffers in the buffer

PROCESSES To determine number of operating system processes that can be connected to ORACLE concurrently. The value should be 5 (background process) and additional 1 for each user. ROLLBACK_SEGMENTS List of rollback segments an ORACLE instance acquires at database startup. Also optionally and LICENSE_MAX_USERS.

LICENSE_MAX_SESSIONS,LICENSE_SESSION_WARNING

56. What is a trace file and how is it created ? Each server When an process, it be used for

and background process can write an associated trace file. internal error is detected by a process or user dumps information about the error to its trace. This can tuning the database.

57. What are roles ? How can we implement roles ? Roles are the easiest way to grant and manage common privileges needed by different groups of database users. Creating roles and assigning provies to roles. Assign each role to group of users. This will simplify the job of assigning privileges to individual users. 58. What are the steps to switch a database's archiving mode between NO ARCHIVELOG and ARCHIVELOG mode ? 1. 2. 3. 4. 5.

Shutdown the database instance. Backup the databse Perform any operating system specific steps (optional) Start up a new instance and mount but do not open the databse. Switch the databse's archiving mode.

59. How can you enable automatic archiving ? Shut the database Backup the database Modify/Include LOG_ARCHIVE_START_TRUE in init.ora file. Start up the databse.

373

60. How can destination ?

we

specify

the

Archived

log

file

name

format

and

By setting the following values in init.ora file. LOG_ARCHIVE_FORMAT = arch %S/s/T/tarc (%S - Log sequence number and is zero left paded, %s Log sequence number not padded. %T Thread number lef-zero-paded and %t - Thread number not padded). The file name created is arch 0001 are if %S is used. LOG_ARCHIVE_DEST = path. 61. What is the use of

ANALYZE command

?

To perform one of these function on an index,table, or cluster: - to collect statisties about object used by the optimizer and store them in the data dictionary. - to delete statistics about the object used by object from the data dictionary. - to validate the structure of the object. - to identify migrated and chained rows of the table or cluster. MANAGING DISTRIBUTED DATABASES. 62. How can we reduce the network traffic ? - Replictaion of data in distributed environment. - Using snapshots to replicate data. - Using remote procedure calls. 63. What is snapshots ? Snapshot is an object used to distribute database at specified read only.

dynamically replicate data between time intervals. In ver 7.0 they are

64. What are the various type of snapshots ? Simple and Complex. 65. Differentiate simple and complex, snapshots ? - A simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT BY clauses, JOINs, sub-query or snashot of operations. - A complex snapshots contain atleast any one of the above. 66. What dynamic data replication ? Updating or Inserting records in remote database through database triggers. It may fail if remote database is having any problem. 67. How can you Enforce Refrencial Integrity

in snapshots ?

Time the references to occur when master tables are not in use. Peform the reference the manually immdiately locking the master tables. We can join tables in snopshots by creating a complex snapshots that will based on the master tables. 374

68. What are the options available to

refresh snapshots ?

COMPLETE Tables are completly regenerated using the snapshot's query and the master tables every time the snapshot referenced. FAST - If simple snapshot used then a snapshot log can be used to send the changes to the snapshot tables. FORCE Default value. If possible it performs a FAST refresh; Otherwise it will perform a complete refresh. 69. what is snapshot log ? It is a table that maintains a record of modifications to the master table in a snapshot. It is stored in the same database as master table and is only available for simple snapshots. It should be created before creating snapshots. 70. When will the data in the snapshot log be used ? We must be able to create a after row trigger on table (i.e., it should be not be already available ) After giving table privileges. We cannot specify snapshot log name because oracle uses the name of the master table in the name of the database objects that support its snapshot log. The master table name should be less than or equal to 23 characters. (The table name created will be MLOGS_tablename, and trigger name will be TLOGS name). 72. What are the benefits of distributed options in databases ? Database on other servers can be updated and those transactions can be grouped together with others in a logical unit. Database uses a two phase commit. MANAGING BACKUP & RECOVERY 73. What are the different methods of backing up oracle database ? - Logical Backups - Cold Backups - Hot Backups (Archive log) 74. What is a logical backup ? Logical backup involves reading a set of databse records and writing them into a file. Export utility is used for taking backup and Import utility is used to recover from backup.

375

75. What is cold backup ? What are the elements of it ? Cold backup is taking backup of all shutdown of database. We need to take. - All Data files. - All Control files. - All on-line redo log files. - The init.ora file (Optional)

physical

files

after

normal

76. What are the different kind of export backups ? Full back - Complete database Incremental - Only affected tables from last incremental date/full backup date. Cumulative backup - Only affected table from the last cumulative date/full backup date. 77. What is hot backup and how it can be taken ? Taking backup of archive log files when database is open. For this the ARCHIVELOG mode should be enabled. The following files need to be backed up. All data files. All Archive log, redo log files. All control files. 78. What is the use of FILE option in EXP command ? To give the export file name. 79. What is the use of COMPRESS option in EXP command ? Flag to indicate whether export should compress fragmented segments into single extents. 80. What is the use of GRANT option in EXP command ? A flag to indicate whether grants exported or not. Value is 'Y' or 'N'.

on

databse

objects

will

be

81. What is the use of INDEXES option in EXP command ? A flag to indicate whether indexes on tables will be exported. 82. What is the use of ROWS option in EXP command ? Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the databse objects will be created. 83. What is the use of CONSTRAINTS option in EXP command ? A flag to indicate whether constraints on table need to be exported. 84. What is the use of FULL option in EXP command ? A flag to indicate whether full databse export should be performed. 85. What is the use of OWNER option in EXP command ? List of table accounts should be exported. 376

86. What is the use of TABLES option in EXP command ? List of tables should be exported. 87. What is the use of RECORD LENGTH option in EXP command ? Record length in bytes. 88. What is the use of INCTYPE option in EXP command ? Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL. 89. What is the use of RECORD option in EXP command ? For Incremental exports, the flag indirects whether a record will be stores data dictionary tables recording the export. 90. What is the use of PARFILE option in EXP command ? Name of the parameter file to be passed for export. 91. What is the use of PARFILE option in EXP command ? Name of the parameter file to be passed for export. 92.

What is the use of ANALYSE ( Ver 7) option in

EXP command ?

A flag to indicate whether statistical information about the exported objects should be written to export dump file. 93.

What is the use of CONSISTENT (Ver 7) option in

EXP command ?

A flag to indicate whether a read consistent version of all the exported objects should be maintained. 94.

What is use of LOG (Ver 7) option in

EXP command ?

The name of the file which log of the export will be written. 95.What is the use of FILE option in

IMP command ?

The name of the file from which import should be performed. 96.

What is the use of SHOW option in IMP command ?

A flag to indicate whether file content should be displayed or not. 97.

What is the use of IGNORE option in IMP command ?

A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands. 98. What is the use of GRANT option in IMP command ? A flag to indicate whether grants on database objects will be imported. 377

99. What is the use of INDEXES option in IMP command ? A flag to indicate whether import should import index on tables or not. 100. What is the use of ROWS option in IMP command ? A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects will be exectued.

SQL PLUS STATEMENTS 1. What are the types of SQL Statement ? Data Definition Language : CREATE,ALTER,DROP,TRUNCATE,REVOKE,NO AUDIT & COMMIT. Data Manipulation Language : INSERT,UPDATE,DELETE,LOCK TABLE,EXPLAIN PLAN & SELECT. Transactional Control : COMMIT & ROLLBACK Session Control : ALTERSESSION & SET ROLE System Control : ALTER SYSTEM. 2. What is a transaction ? Transaction is logical unit between two commits and commit and rollback. 3. What is difference between TRUNCATE & DELETE ? TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. 4. What is a join ? Explain the different types of joins ? Join is a query multiple tables.

which

retrieves

related columns or rows from

Self Join - Joining the table with itself. Equi Join - Joining two tables by equating two Non-Equi Join - Joining two tables by equating Outer Join - Joining two tables in such a retrive rows that do not have corresponding table. 5. What is the

Subquery ?

Subquery is a query whose conditions of the main query. 378

common columns. two common columns. way that query can also join value in the other

return

values

are

used

in

filtering

6. What is correlated sub-query ? Correlated sub_query is a sub_query which has reference to the main query. 7. Explain

Connect by Prior ?

Retrives rows in hierarchical order. e.g. select empno, ename from emp where. 8. Difference between SUBSTR and INSTR ? INSTR (String1,String2(n,(m)), INSTR returns the position of the mth occurrence 2 in string1. The search begins from nth position of string1.

of the string

SUBSTR (String1 n,m) SUBSTR returns a character string of size m in string1, starting from nth postion of string1. 9. Explain UNION,MINUS,UNION ALL, INTERSECT ? INTERSECT returns all distinct rows selected by both queries. MINUS returns all distinct rows selected by the first query but not by the second. UNION - returns all distinct rows selected by either query UNION ALL - returns all rows selected by either query,including all duplicates. 10. What is ROWID ? ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno, rownumber are the components of ROWID. 11. What is the fastest way of accessing a row in a table ? Using ROWID. CONSTRAINTS 12. What is an Integrity Integrity constraint in a table.

is

Constraint ? a

rule

that

restricts values to a column

13. What is Referential Integrity ? Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.

379

14. What are the usage of

SAVEPOINTS ?

SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed. 15.

What is ON DELETE CASCADE ?

When ON DELETE CASCADE is specified ORACLE maintains integrity by automatically removing dependent foreign if a referenced primary or unique key value is removed.

referential key values

16. What are the data types allowed in a table ? CHAR,VARCHAR2,NUMBER,DATE,RAW,LONG and LONG RAW. 17. What is difference between CHAR the maximum SIZE allowed for each type ?

and VARCHAR2 ?

What is

CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255 and 2000 for VARCHAR2. 18. How many LONG columns are allowed in a table ? Is it possible to use LONG columns in WHERE clause or ORDER BY ? Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause. 19. What are the pre requisites ? I. to modify datatype of a column ? ii. to add a column with NOT NULL constraint ? To Modify the datatype of a column the column must be empty. to add a column with NOT NULL constrain, the table must be empty. 20. Where the integrity constrints are stored in Data Dictionary ? The integrity constraints are stored in

USER_CONSTRAINTS.

21. How will you a activate/deactivate integrity constraints ? The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint. 22. If an unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE ? It won't, Because SYSDATE format contains time attached with it. 23. What is a database link ? Database Link is can be accessed.

380

a

named

path

through

which a remote database

24. How to access the current value and next value from a sequence ? Is it possible to access the current value in a session before accessing next value ? Sequence name CURRVAL, Sequence name NEXTVAL. It is not possible. Only if you access next value in the session, current value can be accessed. 25. What is CYCLE/NO CYCLE in a Sequence ? CYCLE specifies that the sequence continues to generate values after reaching either maximum or minimum value. After pan ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum. NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value. 26. What are the advantages of

VIEW ?

To protect some of the columns of a table from other users. To hide complexity of a query. To hide complexity of calculations. 27. Can a view conditions ?

be

updated/inserted/deleted?

If

Yes

under

what

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible. 28.If a View on a single base table is manipulated will the changes be reflected on the base table ? If changes are made to the tables which are base tables of a view will the changes be reference on the view. FORMS 3.0 BASIC 1.What is an SQL *FORMS ? SQL *forms is 4GL tool for based interactive application.

developing

and

executing;

Oracle

2. What is the maximum size of a form ? 255 character width and 255 characters

Length.

3. Name the two files that are created when you generate the form give the filex extension ? INP (Source File) FRM (Executable File) 381

4. How do you control the constraints in forms ? Select the use constraint property is ON Block definition screen. BLOCK 5. Commited block sometimes refer to a BASE TABLE ? True or False. False. 6. Can we create two blocks with the same name in form 3.0 ? No. 7. While specifying master/detail relationship between blocks specifying the join condition is a must ? True or False.

two

True. 8. What is a Trigger ? A piece of logic that is executed at or triggered by a SQL *forms event. 9. What are the types of

TRIGGERS ?

1. Navigational Triggers. 2. Transaction Triggers. 10. What are the different types of key triggers ? Function Key Key-function Key-others Key-startup 11. What is the difference between a Function Key Trigger and Key Function Trigger ? Function key triggers are associated with individual SQL*FORMS function keys You can attach Key function triggers to 10 keys or key sequences that normally do not perform any SQL * FORMS operations. These keys refered as key F0 through key F9. 12. What does an on-clear-block Trigger fire? It fires just before SQL * forms the current block. 13. How do you trap the error in forms 3.0 ? using On-Message or On-Error triggers.

382

14. State the order in which these triggers are executed ? POST-FIELD,ON-VALIDATE-FIELD,POST-CHANGE and KEY-NEXTFLD. KEY-NEXTFLD,POST-CHANGE, ON-VALIDATE-FIELD, POST-FIELD. 15. What is the usuage of an ON-INSERT,ON-DELETE and ON-UPDATE TRIGGERS ? These triggers are executes when inserting,deleting and updating operations are performed and can be used to change the default function of insert,delete or update respectively. For Eg, instead of inserting can be updated in the same table.

a

row

in a table an existing row

16. When will ON-VALIDATE-FIELD trigger executed ? It fires when a value in a field has been changed and the field status is changed or new and the key has been pressed. If the field status is valid then any further change to the value in the field will not fire the on-validate-field trigger. 17. A query fetched 10 records How many times does a PRE-QUERY Trigger and POST-QUERY Trigger will get executed ? PRE-QUERY fires once. POST-QUERY fires 10 times. 18. and

What is the difference a POST-CHANGE trigger ?

between

ON-VALIDATE-FIELD

trigger

When you changes the Existing value to null, the On-validate field trigger will fire post change trigger will not fire. At the time of execute-query post-chage trigger will fire, on-validate field trigger will not fire. 19. What is the and a trigger ? On-validate-field New or changed. Post-field-trigger will fire.

difference trigger whenever

between

fires, the

an ON-VALIDATE-FIELD trigger

when the field Validation status control

leaving form the field, it

20. What is the difference between a POST-FIELD trigger and a POSTCHANGE trigger ? Post-field trigger fires whenever the control leaving from the filed. Post-change trigger fires at the time of execute-query procedure invoked or filed validation status changed.

383

21. When is PRE-QUERY trigger executed ? When Execute-query or count-query Package procedures are invoked. 22. Give the sequence in which triggers fired during insert operations, when the following 3 triggers are defined at the smae block level ? a. ON-INSERT b. POST-INSERT c. PRE-INSERT PRE-INSERT,ON-INSERT & POST-INSERT. 23. Can we use GO-BLOCK package in a pre-field trigger ? No. 24. Is a Keystartup trigger fires as result of a operator pressing a key explicitly ? No. 25. How can you execute the user defined triggers in forms 3.0 ? Execute_Trigger (trigger-name) 26. When does an on-lock trigger fire ? It will fires whenever SQL * Forms would normally attempt to lock a row. 26. What is Post-Block is a . a. Navigational Trigger. b. Key trigger c. Transaction Trigger. Navigational Trigger. 27. What is the difference between keystartup and pre-form ? Key-startup trigger fires after successful navigation into a form. Pre-form trigger fires before enter into the form. 28. What is the difference between keystartup and pre-form ? Key-startup triigger fires after successful navigation into a form. Pre-form trigger fires before enter into the form. PACKAGE PROCEDURE & FUNCTION 29. What is a Package Procedure ? A Package proecdure is built in PL/SQL procedure. 30. What are the different types of Package Procedure ? 1. Restricted package procedure. 2. Unrestricted package proecdure. 384

31. What is the difference between restricted and unrestricted package procedure ? Restricted package procedure that affects the basic basic functions of SQL * Forms. It cannot used in all triggers execpt key triggers. Unrestricted package procedure that does not interfere with the basic functions of SQL * Forms it can be used in any triggers. 32. Classify the restricted following. a. Call b. User-Exit c. Call-Query d. Up e. Execute-Query f. Message g. Exit-From h. Post i. Break a. Call b. c. d. e. f. g. h. i.

and

unrestricted

procedure

from

the

- unrestricted User Exit - Unrestricted Call_query - Unrestricted Up - Restricted Execute Query - Restricted Message - Restricted Exit_form - Restricted Post - Restricted Break - Unrestricted.

33. Can we use a restricted package procedure in ON-VALIDATE-FIELD Trigger ? No. 34. What SYNCHRONIZE procedure does ? It synchoronizes the terminal screen with the internal state of the form. 35. What are the unrestricted procedures used to change the popup screen position during run time ? Anchor-view Resize -View Move-View. 36. What Enter package procedure does ? Enter Validate-data in the current validation unit. 37. What ERASE package procedure does ? Erase removes an indicated global variable.

385

38. What is the difference between NAME_IN and COPY ? Copy is package procedure and writes values into a field. Name in is a package function and returns the contents variable to which you apply.

of

the

38. Identify package function from the following ? 1. Error-Code 2. Break 3. Call 4. Error-text 5. Form-failure 6. Form-fatal 7. Execute-query 8. Anchor_View 9. Message_code 1. 2. 3. 4. 5.

Error_Code Error_Text Form_Failure Form_Fatal Message_Code

40. How does the command POST differs from COMMIT ? Post writes data in the form to the database but does not perform database commit Commit permenently writes data in the form to the database. 41. What the PAUSE package procedure does ? Pause suspends processing until the operator presses a function key 42. What package procedure is used for calling another form ? Call

(E.g. Call(formname)

43. What package procedure used for invoke sql *plus from sql *forms ? Host (E.g. Host (sqlplus)) 44. Error_Code is a package proecdure ? a. True b. false False. 45. EXIT_FORM is a restricted package procedure ? a. True b. False True. 46. When the form is running in DEBUG mode, If you want to examine the values of global variables and other form variables, What package procedure command you would use in your trigger text ? Break. 386

SYSTEM VARIABLES 47. List the system variables related in Block and Field? 1. 2. 3. 4. 5. 6. 7.

System.block_status System.current_block System.current_field System.current_value System.cursor_block System.cursor_field System.field_status.

48. What is the and system.cursor_field ?

difference

between

system.current_field

1. System.current_field gives name of the field. 2. System.cursor_field gives name of the field with block name. 49. The value recorded in system.last_record variable is of type a. Number b. Boolean c. Character. b. Boolean. User Exits : 50. What is an User Exits ? A user exit is a subroutine which are written in programming languages using pro*C pro *Cobol , etc., that link into the SQL * forms executable. 51. What are the type of

User Exits ?

ORACLE Precompliers user exits OCI (ORACLE Call Interface) Non-ORACEL user exits. Page : 52. What do you mean by a page ? Pages are collection and graphics.

of

display

information, such as constant text

53. How many pages you can in a single form ? Unlimited. 54. Two popup pages can appear on the screen at a time ? a. True b. False a. True. 387

55.What is the significance of PAGE 0 in forms 3.0 ? Hide the fields for internal calculation. 56. Deleting a page removes information about all the fields in that page ? a. True. b. False a. True. Popup Window : 57. What do you mean by a pop-up window ? Pop-up windows are screen areas that the display screen when a form is running.

overlay

all or a portion of

58. What are the types of Pop-up window ? the pop-up field editor pop-up list of values pop-up pages. Alert : 59. What is an Alert ? An alert is window that appears in the overlaying a portion of the current display.

middle

of

the

FORMS 4.0 01. Give the Types of modules in a form? Form Menu Library 02. Write the Abbreviation for the following File Extension 1. FMB 2. MMB 3. PLL FMB ----- Form Module Binary. MMB ----- Menu Module Binary. PLL ------ PL/SQL Library Module 03.

What

are the design facilities

Default Block facility. Layout Editor. Menu Editor. Object Lists. Property Sheets. PL/SQL Editor. Tables Columns Browser. Built-ins Browser. 388

Binary. available

in

forms 4.0?

screen

04.

What is

a

Layout

Editor?

The Layout Editor is a graphical design facility for and arranging items and boilerplate text and objects in your application's interface.

creating graphics

05. BLOCK 05. What do you mean by a block in forms4.0? Block is a single mechanism for grouping related items into functional unit for storing,displaying and manipulating records. 06. Explain

types

of

Block

in

a

forms4.0?

Base table Blocks. Control Blocks. 1. A base table block is one that is associated with a specific database table or view. 2. A control block is a block that is not associated with a database table. ITEMS 07.

List

the

Types

of

Items?

Text item. Chart item. Check box. Display item. Image item. List item. Radio Group. User Area item. 08.

What is a

Navigable

item?

A navigable item is one that operators can navigate to with the keyboard during default navigation, or that Oracle forms can navigate to by executing a navigational built-in procedure. 09.

Can

you

change

the color of the push button in design time?

No. 10.

What is a Check

Box?

A Check Box is a two state control that indicates whether a certain condition or value is on or off, true or false. The display state of a check box is always either "checked" or "unchecked". 11. What are the triggers associated with a check box? Only When-checkbox-activated Trigger associated with a Check box. 389

PL/SQL Basics of PL/SQL 1. What is PL/SQL ? PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching. 2. What is the basic structure of PL/SQL ? PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL. 3. What are the components of a PL/SQL block ? A set of related declarations and procedural statements is called block. 4. What are the components of a PL/SQL Block ? Declarative part, Executable part and Execption part. Datatypes PL/SQL 5. What are the datatypes a available in PL/SQL ? Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite data types such as RECORD & TABLE. 6. What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes? % TYPE provides that variable.

the data type of a variable or a database column to

% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor. The advantages are : I. Need not know about variable's data type ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly. 7. What is difference between % ROWTYPE and TYPE RECORD ? % ROWTYPE is to be used whenever query returns a entire row of a table or view. TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables. E.g.

TYPE

r_emp is RECORD (eno emp.empno% type,ename emp ename

%type ); e_rec emp% ROWTYPE 390

cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE. 8. What is PL/SQL table ? Objects of type TABLE are called "PL/SQL tables", which are modelled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key. Cursors 9. What is a cursor ? Why Cursor is required ? Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows. 10. Explain the two type of Cursors ? There are two types of cursors, Implict Cursor and Explicit Cursor. PL/SQL uses Implict Cursors for queries. User defined cursors are called Explicit Cursors. They can be declared and used. 11. What are the PL/SQL Statements used in cursor processing ? DECLARE CURSOR cursor name, OPEN cursor INTO or Record types, CLOSE cursor name.

name,

FETCH cursor name

12. What are the cursor attributes used in PL/SQL ? %ISOPEN - to check whether cursor is open or not % ROWCOUNT - number of rows featched/updated/deleted. % FOUND - to check whether cursor has fetched any row. True if rows are featched. % NOT FOUND - to check whether cursor has featched any row. True if no rows are featched. These attributes are proceded with SQL for Implict Cursors and with Cursor name for Explict Cursors. 13. What is a cursor for loop ? Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed. eg. FOR emp_rec IN C1 LOOP salary_total := salary_total +emp_rec sal; END LOOP;

391

14. What will happen after commit statement ? Cursor C1 is Select empno, ename from emp; Begin open C1; loop Fetch C1 into eno.ename; Exit When C1 %notfound;----commit; end loop; end; The cursor having query after COMMIT/ROLLBACK.

as

SELECT

The cursor having query after COMMIT/ROLLBACK.

as

SELECT....

15. Explain the usage of

....

FOR does

UPDATE gets closed not get closed even

WHERE CURRENT OF clause in cursors ?

WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from a cursor. Database Triggers 16. What is a database trigger ? Name some usages of database trigger ? Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modificateions, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables. 17. How many types of database triggers can be specified on a table ? What are they ?

Before

Update

Delete

o.k.

o.k.

o.k.

o.k.

o.k.

o.k.

Row

Insert

After Row

Before Statement

o.k.

o.k.

o.k.

After Statement

o.k.

o.k.

o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement. If WHEN clause is specified, the trigger fires according to the retruned boolean value.

392

18. Is it possible to use Transaction control ROLLBACK or COMMIT in Database Trigger ? Why ?

Statements

such

a

It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affects logical transaction processing. 19. What are execution ?

two

virtual

tables

available

during

database

trigger

The table columns are referred as OLD.column_name and NEW.column_name. For triggers related to INSERT only NEW.column_name values only available. For triggers related to UPDATE only OLD.column_name NEW.column_name values only available. For triggers related to DELETE only OLD.column_name values only available. 20. What happens if a procedure that updates a column of table X is called in a database trigger of the same table ? Mutation of table occurs. 21. Write the order of precedence for validation of a column in a table ? I. done using Database triggers. ii. done using Integarity Constraints. I & ii. Exception : 22. What is an Exception ? What are types of Exception ? Exception is the error handling part of PL/SQL block. The types are Predefined and user_defined. Some of Predefined execptions are. CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR INVALID_NUMBER LOGON_DENIED NOT_LOGGED_ON PROGRAM-ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE VALUE_ERROR ZERO_DIVIDE OTHERS. 23. What is Pragma EXECPTION_INIT ? Explain the usage ? The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error. e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number) 393

24. What is Raise_application_error ? Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored subprogram or database trigger. 25. What are the return values of functions SQLCODE and SQLERRM ? SQLCODE returns the latest code of the error that has occured. SQLERRM returns the relevant error message of the SQLCODE. 26. Where the Pre_defined_exceptions are stored ? In the standard package. Procedures, Functions & Packages ; 27. What is a stored procedure ? A stored procedure specific function.

is

a

sequence

of

statements that perform

28. What is difference between a PROCEDURE & FUNCTION ? A FUNCTION is alway returns a value using the return statement. A PROCEDURE may return one or more values through parameters or may not return at all. 29. What are advantages fo Stored Procedures / Extensibility,Modularity, time compilation.

Reusability,

Maintainability

and

one

30. What are the modes of parameters that can be passed to a procedure ? IN,OUT,IN-OUT parameters. 31. What are the two parts of a procedure ? Procedure Specification and Procedure Body. 32. Give the structure of the procedure ? PROCEDURE name (parameter list.....) is local variable declarations BEGIN Executable statements. Exception. exception handlers end; 33. Give the structure of the function ? 394

FUNCTION name (argument list .....) Return datatype is local variable declarations Begin executable statements Exception execution handlers End; 34. Explain how procedures and functions are called in a PL/SQL block ? Function is called as part of an expression. sal := calculate_sal ('a822'); procedure is called as a PL/SQL statement calculate_bonus ('A822'); 35. What is Overloading of procedures ? The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures. e.g. DBMS_OUTPUT put_line 36. What is a package ? What are the advantages of packages ? Package is a database object that groups logically related procedures. The advantages of packages are Modularity, Easier Applicaton Design, Information. Hiding,. reusability and Better Performance. 37.What are two parts of package ? The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification contains declarations that are packages and local to the schema. Package Body contains actual procedures and local the procedures and cursor declarations.

global

to

the

declaration of

38. What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ? A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package. A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures. 39. How a. b. c.

packaged procedures and functions are called from the following? Stored procedure or anonymous block an application program such a PRC *C, PRO* COBOL SQL *PLUS

a. PACKAGE NAME.PROCEDURE NAME (parameters); variable := PACKAGE NAME.FUNCTION NAME (arguments); EXEC SQL EXECUTE b. 395

BEGIN

PACKAGE NAME.PROCEDURE NAME (parameters) variable := PACKAGE NAME.FUNCTION NAME

(arguments); END; END EXEC; EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have

c. any out/in-out parameters. A function can not be called. 40. Name the tables where and functions are stored ?

characteristics

of

Package,

procedure

User_objects, User_Source and User_error. FORMS4.0 12. what is a display item? Display items are similar to text items but store only fetched or assigned values. Operators cannot navigate to a display item or edit the value it contains. 13. What is a list item? It is a list of text elements. 14. What are the display styles of list items? Poplist, No text Item displayed in the list item. Tlist, No element in the list is highlighted. 15. What is a radio Group? Radio groups display a fixed no of options Exclusive . User can select one out of n number of options. 16. How many radio group?

maximum

number

that

are

mutually

of radio buttons can you assign to a

Unlimited no of radio buttons can be assigned to a radio group 17. can you change the default value of the radio button group at run time? No. 18.What triggers are associated with the radio group? Only when-radio-changed trigger associated with radio group Visual Attributes.

396

19. What is a visual attribute? Visual Attributes are the font, color and pattern characteristics of objects that operators see and intract with in our application. 20. What are the types of visual attribute settings? Custom Visual attributes Default visual attributes Named Visual attributes. Window 21. What is a window? A window, byitself , can be thought of as an empty frame. The frame provides a way to intract with the window, including the ability to scroll, move, and resize the window. The content of the window ie. what is displayed inside the frame is determined by the canvas View or canvas-views displayed in the window at run-time. 22. What are the differrent types of windows? Root window, secondary window. 23. Can a root window be made modal? No. 24. List the buil-in routine for controlling window during run-time? Find_window, get_window_property, hide_window, move_window, resize_window, set_window_property, show_View 25. List the windows event triggers available in Forms 4.0? When-window-activated, deactivated, when-window-resized 26. What built-in window dynamically?

when-window-closed,

is

used

for

changing

the

when-window-

properties of the

Set_window_property Canvas-View 27. What is a canvas-view? A canvas-view interface items 397

is the background object on which you layout the (text-items, check boxes, radio groups, and so on.)

and boilerplate objects that operators see and interact with as they run your form. At run-time, operators can see only those items that have been assiged to a specific canvas. Each canvas, in term, must be displayed in a specfic window. 28. Give the equivalent term in forms 4.0 for the following. Page, Page 0? Page - Canvas-View Page 0 - Canvas-view null. 29. What are the types of canvas-views? Content View, Stacked View. 30. What is the content view and stacked view? A content view is the "Base" view that occupies the entire content pane of the window in which it is displayed. A stacked view differs from a content canvas view in that it is not the base view for the window to which it is assigned 31. List the during run-time?

built-in

routines

for the controlling canvas views

Find_canvas Get-Canvas_property Get_view_property Hide_View Replace_content_view Scroll_view Set_canvas_property Set_view_property Show_view Alert 32. What is an Alert? An alert is a modal window that displays operator of some application condition

a

message

notifies

33. What are the display styles of an alert? Stop, Caution, note 34. Can you attach an alert to a field? No 35. What built-in is used for showing the alert during run-time? Show_alert.

398

the

36. Can you change the alert messages at run-time? If yes, give the name of th built-in messages at run-time. Yes.

to chage the alert

Set_alert_property.

37. What is the built-in function used for finding the alert? Find_alert Editors 38. List the editors availables in forms 4.0? Default editor User_defined editors system editors. 39. What buil-in routines are used to display editor dynamicaly? Edit_text item show_editor LOV 40. What is an Lov? A list of values displayed in a pop-up window

is

a

single

or

multi

column

selection

list

41. Can you attach an lov to a field at design time? Yes. 42. Can you attach an lov to a field at run-time? if yes, give the build-in name. Yes.

Set_item_proprety

43. What is the built-in used for showing lov at runtime? Show_lov 44. What is the during run-time?

built-in

used

to

get

and

set lov properties

Get_lov_property Set_lov_property Record Group 45. What is a record Group? A record group is an internal oracle forms data structure that has a simillar column/row frame work to a database table 399

46. What are the different type of a record group? Query record group Static record group Non query record group 47. Give built-in routine related to a record groups? Create_group (Function) Create_group_from_query(Function) Delete_group(Procedure) Add_group_column(Function) Add_group_row(Procedure) Delete_group_row(Procedure) Populate_group(Function) Populate_group_with_query(Function) Set_group_Char_cell(procedure) 48. What is the built_in routine used to count the no of rows in a group? Get_group _row_count System Variables 49. List system variables available in forms 3.0?

available

in

forms

4.0,

and

not

System.cordination_operation System Date_threshold System.effective_Date System.event_window System.suppress_working 50. System.effective_date system variable is read only True/False False 51. What is a library in Forms 4.0? A library is a collection of Pl/SQL program units, including user named procedures, functions & packages 52. Is it possible to attach same library to more than one form? Yes 53. Explain the following file extention related to library? .pll,.lib,.pld The library pll files is a portable design file comparable to an fmb form file The library lib file is a plat form specific, generated library file comparable to a fmx form file The pld file is Txt format file and can be used for source controlling your library files 400

Parameter 54. How do you pass the parameters from one form to another form? To pass one or more parameters to a called form, the calling form must perform the following steps in a trigger or user named routine excute the create_parameter_list built_in function to programatically. Create a parameter list to execute the add parameter built_in procedure to add one or more parameters list. Execute the call_form, New_form or run_product built_in procedure and include the name or id of the parameter list to be passed to the called form. 54. What are the built-in routines is available in forms 4.0 to create and manipulate a parameter list? Add_parameter Create_Parameter_list Delete_parameter Destroy_parameter_list Get_parameter_attr Get_parameter_list set_parameter_attr 55. What are the forms application?

two

ways

to

incorporate

images into a oracle

Boilerplate Images Image_items 56. How image_items can be populate to field in forms 4.0? A fetch from a long raw database column PL/Sql assignment to executing the read_image_file built_in procedure to get an image from the file system. 57. What are the triggers associated with the image item? When-Image-activated(Fires when the operator double clicks on an image Items) When-image-pressed(fires when the operator selects or deselects the image item) 58. List some built-in routines used to manipulate images in image_item? Image_add Image_and Image_subtract Image_xor Image_zoom 59. What are the built_in used to trapping errors in forms 4? Error_type return character Error_code return number Error_text return char Dbms_error_code return no. 401

Dbms_error_text

return char

60. What is a predefined exception available in forms 4.0? Raise form_trigger_failure 61. What are the menu items that oracle forms 4.0 supports? Plain, Check,Radio, Separator, Magic FORMS4.5 object groups 01. what ia an object groups? An object group is a container for a group of objects, you define an object group when you want to package related objects. so that you copy or reference them in another modules. 02. what are the different reference in object groups?

objects

that

you

cannot

copy

or

objects of differnt modules another object groups individual block dependent items program units. canvas views 03. what are different types of canvas views? content canvas views stacked canvas views horizontal toolbar vertical toolbar. 04. explain about content

canvas views?

Most Canvas views are content canvas views a content canvas view is the "base" view that occupies the entire content pane of the window in which it is displayed. 05. Explain about stacked canvas views? Stacked canvas view is displayed in a window on top of, or "stacked" on the content canvas view assigned to that same window. Stacked canvas views obscure some part of the underlying content canvas view, and or often shown and hidden programmatically. 06. Explain about horizontal, Vertical tool bar canvas views? Tool bar canvas views are used to create tool bars for individual windows Horizontal tool bars are display at the top of a window, just under its menu bar. Vertical Tool bars are displayed along the left side of a window 402

07. Name of the functions used to get/set canvas properties? Get_view_property, Set_view_property Windows 07. What is relation between the window and canvas views? Canvas views are the back ground objects on which you place the interface items (Text items), check boxes, radio groups etc.,) and boilerplate objects (boxes, lines, images etc.,) that operators interact with us they run your form . Each canvas views displayed in a window. 08. What are the different modals of windows? Modalless windows Modal windows 09. What are modalless windows? More than one modelless window can be displayed at the same time, and operators can navigate among them if your application allows them to do so . On most GUI platforms, modelless windows can also be layered to appear either in front of or behind other windows. 10. What are modal windows? Modal windows are usually used as dialogs, and have restricted functionality compared to modelless windows. On some platforms for example operators cannot resize, scroll or iconify a modal window. 11. How do you display console on a window ? The console includes the status line and message line, and is displayed at the bottom of the window to which it is assigned. To specify that the console should be displayed, set the console window form property to the name of any window in the form. To include the console, set console window to Null. 12. What is the remove on exit property? For a modelless window, it determines whether oracle forms hides the window automatically when the operators navigates to an item in the another window. 13. How many windows in a form can have console? Only one window in a form can display the console, and you cannot chage the console assignment at runtime. 14. Can you have more than one content canvas view attached with a window? Yes. 403

Each window you create must have atleast one content canvas view assigned to it. You can also create a window that has manipulate contant canvas view. At run time only one of the content canvas views assign to a window is displayed at a time. 15. What are the different window events activated at runtimes? When_window_activated When_window_closed When_window_deactivated When_window_resized Within this triggers, variable system.event_window for which the trigger fired.

you can examine to determine the

the built in system name of the window

Modules 27. What are different types of modules available in oracle form? Form module - a collection of objects and code routines Menu modules - a collection of menus and menu item commands that together make up an application menu library module - a collectio of user named procedures, functions and packages that can be called from other modules in the application 18. What are the default extensions of the files careated by forms modules? .fmb - form module binary .fmx - form module executable 19. What are the default extentions of the files created by menu module? .mmb, .mmx 20 What are the default extension of the files created by library module? The default file extensions indicate the library module type and storage format .pll - pl/sql library module binary Master Detail 21. What is a master detail relationship? A master detail relationship is an association between two base table blocks- a master block and a detail block. The relationship between the blocks reflects a primary key to foreign key relationship between the tables on which the blocks are based. 22. What is coordination Event? Any event that makes a different record in the master block the current record is a coordination causing event. 23. What are the two phases of block coordination? 404

There are two phases of block coordination: the clear phase and the population phase. During, the clear phase, Oracle Forms navigates internally to the detail block and flushes the obsolete detail records. During the population phase, Oracle Forms issues a SELECT statement to repopulate the detail block with detail records associated witjh the new master record. These operations are accomplished through the execution of triggers. 24. What are Most Common types of Complex master-detail relationships? There are three most common relationships: master with dependent details master with independent details detail with two masters 25. What are the different establish in Master-Details? Cascade Isolate Non-isolote

types

types

of

of

complex

Delete

master-detail

details

we

can

26. What are the different defaust triggers created when Master Deletes Property is set to Non-isolated? Master Delets Property Resulting Triggers ---------------------------------------------------Non-Isolated(the default) On-Check-Delete-Master On-Clear-Details On-Populate-Details 26. Whar are the different default triggers created when Master Deletes Property is set to Cascade? Ans: Master Deletes Property Resulting Triggers --------------------------------------------------Cascading On-Clear-Details On-Populate-Details Pre-delete 28. What are the different default triggers created when Master Deletes Property is set to isolated? Master Deletes Property Resulting Triggers --------------------------------------------------Isolated On-Clear-Details On-Populate-Details 29. What are the Coordination Properties in a Master-Detail relationship? The coordination properties are Deferred Auto-Query These Properties determine when the population phase of block coordination should occur. 405

30. What are the different types of Coordinations of the Master with the Detail block? 42. What is the User-Named Editor? A user named editor has the same text editing functionality as the default editor, but, becaue it is a named object, you can specify editor attributes such as windows display size, position, and title. 43. What are the Built-ins to display the user-named editor? A user named editor can be displayed programmatically with the built in procedure SHOW-EDITOR, EDIT_TETITEM independent of any particular text item. 44. What is the difference between SHOW_EDITOR and EDIT_TEXTITEM? Show editor is the generic built_in which accepts any editor name and takes some input string and returns modified output string. Whereas the edit_textitem built_in needs the input focus to be in the text item before the built_in is excuted. 45. What is an LOV? An LOV is a scrollable popup window that provides the operator with either a single or multi column selection list. 46. What is the basic data structure that is required for creating an LOV? Record Group. 47. What is the "LOV of Validation" Property of an item? What is the use of it? When LOV for Validation is set to True, Oracle Forms compares the current value of the text item to the values in the first column displayed in the LOV. Whenever the validation event occurs. If the value in the text item matches one of the values in the first column of the LOV, validation succeeds, the LOV is not displayed, and processing continues normally. If the value in the text item does not match one of the values in the first column of the LOV, Oracle Forms displays the LOV and uses the text item value as the search criteria to automatically reduce the list. 48. What are the built_ins used the display the LOV? Show_lov List_values 49. What are the built-ins programmatically to an item? set_item_property get_item_property (by setting the LOV_NAME property) 406

that

are

used

to

Attach

an

LOV

50. What are the built-ins properties at runtime?

that

are

used

for

setting

the

LOV

get_lov_property set_lov_property 51. What is a record group? A record group is an hs a column/row framework database tables, record the form module which they 52. How

internal Oracle Forms that structure that similar to a database table. However, unlike groups are separate objects that belong to are defined.

many number of columns a record group can have?

A record group can have an unlimited number of columns of type CHAR, LONG, NUMBER, or DATE provided that the total number of column does not exceed 64K. 53. What is the Maximum allowed length of Record group Column? Record group column names cannot exceed 30 characters. 54. What are the different types of Record Groups? Query Record Groups NonQuery Record Groups State Record Groups 55. What is a Query Record Group? A query record group is a record group that has an associated SELECT statement. The columns in a query record group derive their default names, data types, had lengths from the database columns referenced in the SELECT statement. The records in query record group are the rows retrieved by the query associated with that record group. 56. What is a Non Query Record Group? A non-query record group is a group that does not have an associated query, but whose structure and values can be modified programmatically at runtime. 57. What is a Static Record Group? A static record group is not associated with a query, rather, you define its structure and row values at design time, and they remain fixed at runtime. 58. What are the built-ins used for Creating and deleting groups? CREATE-GROUP (function) CREATE_GROUP_FROM_QUERY(function) DELETE_GROUP(procedure)

407

59.What are the built -ins used for Modifying a group's structure? ADD-GROUP_COLUMN (function) ADD_GROUP_ROW (procedure) DELETE_GROUP_ROW(procedure) 60.

POPULATE_GROUP(function) POPULATE_GROUP_WITH_QUERY(function) SET_GROUP_CHAR_CELL(procedure) SET_GROUP_DATE_CELL(procedure) SET_GROUP_NUMBER_CELL(procedure)

61. What are the built-ins used for Getting cell values? GET_GROUP_CHAR_CELL (function) GET_GROUP_DATE_CELL(function) GET_GROUP_NUMBET_CELL(function) 62. What are built-ins used for Processing rows? GET_GROUP_ROW_COUNT(function) GET_GROUP_SELECTION_COUNT(function) GET_GROUP_SELECTION(function) RESET_GROUP_SELECTION(procedure) SET_GROUP_SELECTION(procedure) UNSET_GROUP_SELECTION(procedure) 63. What are the built-ins used for finding Object ID function? FIND_GROUP(function) FIND_COLUMN(function) 64. Use the ADD_GROUP_COLUMN function to add a column to a record group that was created at design time. I) TRUE II)FALSE II) FALSE 65. Use the ADD_GROUP_ROW procedure to add a row to a static record group I) TRUE

61.

II)FALSE I) FALSE

What are the built-in used for getting cell values?

Get_group_char_cell(function) Get_group_date_cell(function) Get_group_number_cell(function) 62.

What are the built-ins used for processing rows?

Get_group_row_count(function) Get_group_selection_count(function) Get_group_selection(function) 408

Reset_group_selection(procedure) Set_group_selection(procedure) Unset_group_selection(procedure) 63.

What are the built-ins used for finding object ID functions?

Find_group(function) Find_column(function) 64. Use the add_group_column function to add a column to record group that was created at a design time? False. 65. Use the Add_group_row procedure to add a row to a static record group 1. true or false? False. parameters 66.

What are parameters?

Parameters provide a simple mechanism for defining and setting the values of inputs that are required by a form at startup. Form parameters are variables of type char,number,date that you define at design time. 67. What are the Built-ins used for sending Parameters to forms? You can pass parameter values to a form when an application executes the call_form, New_form, Open_form or Run_product. 68. What is the maximum no of chars the parameter can store? The maximum no of chars the parameter can store is only valid for char parameters, which can be upto 64K. No parameters default to 23Bytes and Date parameter default to 7Bytes. 69. How do you call other Oracle Products from Oracle Forms? Run_product is a built-in, Used to invoke one of the supported oracle tools products and specifies the name of the document or module to be run. If the called product is unavailable at the time of the call, Oracle Forms returns a message to the opertor. 70. How do you reference a Parameter? In Pl/Sql, You can reference and set the values of form parameters using bind variables syntax. Ex. PARAMETER name = '' or :block.item = PARAMETER Parameter name

409

71. How do you reference a parameter indirectly? To indirectly reference a parameter use the NAME IN, COPY 'builtins to indirectly set and reference the parameters value' Example name_in ('capital parameter my param'), Copy ('SURESH','Parameter my_param') 72. What are the different Parameter types? Text Parameters Data Parameters 73. When do you use data parameter type? When the value of a data parameter being passed to a called product is always the name of the record group defined in the current form. Data parameters are used to pass data to produts invoked with the run_product built-in subprogram. 74. Can you pass data parametrs to forms? No. IMAGES 75. What are different types of images? Boiler plate images Image Items 76.

What is the difference between boiler plat images and image items?

Boiler plate Images are static images (Either vector or bit map) that you import from the file system or database to use a grapical elements in your form, such as company logos and maps Image items are special types of interface controls that store and display either vector or bitmap images. Llike other items that store values, image items can be either base table items(items that relate directly to database columns) or control items. The definition of an image item is stored as part of the form module FMB and FMX files, but no image file is actualy associated with an image item until the item is populate at run time. 77. What are the trigger associated with image items? When-image-activated fires when the operators double clicks on an image item when-image-pressed fires when an operator clicks or double clicks on an image item 78. What is the use of image_zoom built-in? To manipulate images in image items.

410

WORKING WITH MULTIPLE FORMS 79. How do you create a new session while open a new form? Using open_form built-in setting the session option Ex. Open_form('Stocks ',active,session). when invoke the mulitiple forms with open form and call_form in the same application, state whether the following are true/False 80. Any attempt to navigate call_form stack is allowed?

programatically

to

disabled

form

in

a

False 81. An open form can not be execute the call_form procedure if you chain of called forms has been initiated by another open form? True 82. When a form is invoked with call_form, Does oracle forms issues a save point? True Mouse Operations 83. What are the various sub events a mouse double click event involves? Double clicking the mouse consists of mouse click, mouse down & mouse up events.

the mouse down, mouse up,

84, State any three mouse events system variables? System.mouse_button_pressed System.mouse_button_shift_state system.mouse_item system.mouse_canvas system.mouse_record OLE 85. What is an OLE? Object Linking & Embadding provides you with the capability to integrate objects from many Ms-Windows applications into a single compound document creating integrated applications enables you to use the features form . 86. What is Oracle forms?

the

difference between object embedding & linking in

In Oracle forms, Embedded objects become part of the form module, and linked objects are references from a form module to a linked source file.

411

87. What is the difference between OLE Server & Ole Container? An Ole server application creates ole Objects that are embedded or linked in ole Containers ex. Ole servers are ms_word & ms_excell. OLE containers provide a place to store, display and manipulate objects that are created by ole server applications. Ex. oracle forms is an example of an ole Container. 88. What are the different styles of actvation of ole Objects? In place activation External activation ViSUAL Attributes & property clauses 89. What are visual attributes? Visual attributes are the font, color, pattern proprities that you set for form and menu objects that appear in your application interface. 90. What is a property clause? A property clause is a named object that contains a list of properties and thier settings. Once you create a property clause you can base other object on it. An object based on a property can inherit the setting of any property in the clause that makes sense for that object. 91. Can a property clause itself be based on a property clause? Yes 92. What are the important difference between property clause and visual attributes? Named visual attributes differed only font, color & pattern attributes, property clauses can contain this and any other properties. You can change the appearance of objects at run time by changing the named visual attributes programatically , property clause assignments cannot be changed programatically. When an object is inheriting from both a property clause and named visual attribute, the named visual attribute settings take precedence, and any visual attribute properties in the class are ignored. Form Build-ins 93. What is a Text_io Package? It allows you to read and write information to a file in the file system. 94. What is an User_exit? Calls the user exit named in the user_exit_string. Invokes a 3Gl programe by name which has been properly linked into your current oracle forms executable. 412

95. What is synchronize? It is a terminal screen with the internal state of the form. It updates the screen display to reflect the information that oracle forms has in its internal representation of the screen. 96. What is forms_DDL? Issues dynamic Sql statements at run time, including server side pl/SQl and DDL Triggers 97. What is WHEN-Database-record trigger? Fires when oracle forms first marks a record as an insert or an update. The trigger fires as soon as oracle forms determines through validation that the record should be processed by the next post or commit as an insert or update. c generally occurs only when the operators modifies the first item in the record, and after the operator attempts to navigate out of the item. 98. What

are the master-detail triggers?

On-Check_delete_master On_clear_details On_populate_details 99. What is the difference between $$DATE$$ & $$DBDATE$$ $$DBDATE$$ retrieves the current database date $$date$$ retrieves the current operating system date. 100. What is system.coordination_operation? It represents the coordination causing event that occur on the master block in master-detail relation. 101. What are the difference between lov & list item? Lov is a property where as list item ias an item. A list item can have only one column, lov can have one or more columns. 102. What are the different display styles of list items? Pop_list Text_list Combo box 103. What is pop list? The pop list style list item appears initially as a single field (similar to a text item field). When the operator selects the list icon, a list of available choices appears. 413

104. What is a text list? The text list style list item appears as a rectangular box which displays the fixed number of values. When the text list contains values that can not be displayed, a vertical scroll bar appears, allowing the operator to view and select undisplayed values. 105. What is a combo box? A combo box style list item combines the features found in list and text item. Unlike the pop list or the text list style list items, the combo box style list item will both display fixed values and accept one operator entered value. 106. What are display items? Display items are similar to text items with the exception that display items only store and display fetched or assigned values.Display items are generaly used as boilerplate or conditional text. 107. What is difference between open_form and call_form? when one form invokes another form by executing open_form the first form remains displayed,and operators can navigate between the forms as desired. when one form invokes another form by executing call_form,the called form is modal with respect to the calling form.That is, any windows that belong to the calling form are disabled, and operators cannot navigate to them until they first exit the called form. 108. What is new_form built-in? When one form invokes another form by executing new_form oracle form exits the first form and releases its memory before loading the new form calling new form completely replace the first with the second. If there are changes pending in the first form,the operator will be prompted to save them before the new form is loaded. 109. What is a library? A library is a collection of procedures, functions and packages.

subprograms

including

user

named

110. What is the advantage of the library? Library's provide a convenient means of storing client-side program units and sharing them among multipule applications. Once you create a library, you can attach it to any other form,menu,or library modules. When you can call library program units from triggers menu items commands and user named routine, you write in the modules to which you have attach the library. when a library attaches another library ,program units in the first library can reference program units in the attached library. Library support dynamic loading-that is library program units are loaded into an application only when needed. This can 414

significantly applications.

reduce

the

run-time

memory

requirements

of

an

111. What is strip sources generate options? Removes the source code from the library file and generates a library files that contains only pcode.The resulting file can be used for final deployment, but can not be subsequently edited in the designer. ex. f45gen module=old_lib.pll userid=scott/tiger strip_source YES output_file 112.What are the vbx controls? Vbx control provide a simple mehtod of buildig and enhancing user interfaces.The controls can use to obtain user inputs and display program outputs.vbx control where originally develop as extensions for the ms visual basic environments and include such items as sliders,grides and knobs. 113. What is a timer? Timer is a "internal time clock" that you can programmatically create to perform an action each time the timer expires. 114. What are built-ins associated with timers? find_timer create_timer delete_timer 115. what are difference between post database commit and post-form commit? Post-form commit fires once during the post and commit transactions process, after the database commit occures. The postform-commit trigger fires after inserts,updates and deletes have been posted to the database but before the transactions have been finalished in the issuing the command.The post-database-commit trigger fires after oracle forms issues the commit to finalished transactions. 116. What is a difference between pre-select and pre-query? Fires during the execute query and count query processing after oracle forms constructs the select statement to be issued, but before the statement is actually issued. The pre-query trigger fires just before oracle forms issues the select statement to the database after the operator as define the example records by entering the query criteria in enter query mode. Pre-query trigger fires before pre-select trigger.

415

117. What is trigger associated with the timer? When-timer-expired. 118

What is the use of transactional triggers?

Using transactional triggers we can default functionality of the oracle forms.

control

or

modify

the

REPORTS 1. What are the oracle reports?

different

file

extensions

that are created by

Rep file and Rdf file. 2. From which the printed?

designation

is

it

preferred

to

send the output to

Previewer. 3. Is it possible to disable the parameter from while running the report? Yes 4. What is lexical reference?How can it be created? Lexical reference is place_holder for text that can be embedded in a sql statements.A lexical reference can be created using & before the column or parameter name. 5. What is bind reference and how can it carate? Bind reference are used to replace the single value in sql,pl/sql statements a bind reference can be careated using a (:) before a column or a parameter name. 6.What use of command line parameter cmd file? It is a command line argument that allows you to specify a file that contain a set of arguments for r20run. 7.Where is a procedure return in an external pl/sql library executed at the client or at the server? At the client. 8. Where is the external query executed at the client or the server? At the server. 416

9. What are the default parameter that appear at run time in the parameter screen? Destype and Desname. 10. Which parameter can across multiple queries?

be

used

to

set read level consistency

Read only. 11. What is term? The term is terminal definition file that describes the terminal form which you are using r20run. 12. What is use of term? The term file which key is correspond to which oracle report functions. 13. Is it possible to insert comments into sql statements the data model editor?

return in

Yes. 14. If the maximum record retrieved property of the query is set to 10 then a summary value will be calculated? Only for 10 records. 15. What are the sql clauses supported in the link property sheet? Where startwith having. 16. To execute row from being displayed that still use column in the row which property can be used? Format trigger. 17. Is it possible to set a filter condition in a cross product group in matrix reports? No. 18. If a break order is set on a column would it effect columns which are under the column? No. 19. With which options required?

function

of

percentage of total functions.

417

summary

item

is

the

compute at

20. What is the purpose of the product order option in the column property sheet? To specify products.

the

order

of

individual

group

evaluation

in

a

cross

21.Can a formula column be obtained through a select statement? Yes. 22.Can a formula column refered to columns in higher group? Yes. 23. How can a break order be created on a column in an existing group? By dragging the column outside the group. 24. What are the types of calculated columns available? Summary, Formula, Placeholder column. 25. What is the use of place holder column? A placeholder column is used to hold a calculated values at a specified place rather than allowing is to appear in the actual row where it has to appeared. 26. What is the use of hidden column? A hidden column is used to when a column has to embedded into boilerplate text. 27. What is the use of break group? A break group is used to display one record for one group ones.While multiple related records in other group can be displayed. 28. If two groups are not linked in the data model editor, What is the hierarchy between them? Two group that is above are the left most rank higher than the group that is to right or below it. 29.The join defined by the default data link is an outer join yes or no? Yes. 30. How can a text the report writer?

file

be attached to a report while creating in

By using the link file property in the layout boiler plate property sheet.

418

31. Can a repeating frame be careated without a data group as a base? No. 32. Can a field be used in a report wihtout it appearing in any data group? Yes. 33. For a field in a repeating frame, can the source come from the column which does not exist in the data group which forms the base for the frame? Yes. 34. Is it possible to center an object horizontally in a frame that has a variable horizontal size?

repeating

Yes. 35. If yes,how? By the use anchors. 36. What are the two repeating frame always associated object?

with matrix

One down repeating frame below one across repeating frame. 37. Is it possible to split the printpreviewer into more than one region? Yes. 38. Does a grouping done for objects the grouping done in the datamodel editor?

in the layout editor affect

No. 39. How can a square be drawn in the layout editor of the report writer? By using the rectangle tool while pressing the (Constraint) key. 40. To display the page no. for each page on a report what would be the source & logical page no. or & of physical page no.? & physical page no. 41. What does the term panel refer to with regard to pages? A panel is the no. of physical pages needed to print one logical page. 42. What is an anchoring object & what is its use? An anchoring object is a print condition object which explicitly or implicitly anchor other objects to itself. 419

used

to

43. What is a physical page ? & What is a logical page ? A physical page is a size of a page. That is output by the printer. The logical page is the size of one page of the actual report as seen in the Previewer. 44. What is the frame & repeating frame? A frame is a holder for a group of fields. A repeating frame is used to display a set of records when the no. of records that are to displayed is not known before. REPORT TRIGGERS. 45. What are the triggers available in the reports? Before report, Before form, After form , Between page, After report. 46. Does a suppressed.

Before

form

trigger

fire

when

the

parameter

form

is

Yes. 47. At what point of report execution is the before Report trigger fired? After the query is the records are displayed.

executed

but before the report is executed and

48. Is the After report trigger fired if the report execution fails? Yes. 49. Give the sequence of execution of the various report triggers? Before form , After form , Before report, Between page, After report. 50. Is contains it?

it possible to modify an external query in a report which

No. 51. What are the ways to monitor the performance of the report? Use reports profile executable statement. Use SQL trace facility.

420

52. Why is data model.

it

preferable

to

create a fewer no. of queries in the

Because for each query, report has to open a separate cursor and has to rebind, execute and fetch data. 53. What are the various methods of performing a calculation in a report ? 1. Perform the calculation in the SQL statements itself. 2. Use a calculated / summary column in the data model. 54. Which of the above methods is the faster method? performing the calculation in the query is faster. 55. Why is a Where clause faster than a group filter or a format trigger? Because, in a where clause the condition is applied during data retrieval than after retrieving the data. 56. What is the main diff. bet. Reports 2.0 & Reports 2.5? Report 2.5 is object oriented. 57. What is the diff. bet. setting up of parameters in reports 2.0 reports 2.5? LOVs can be attached to parameters in the reports 2.5 parameter form. 58. How is link tool operation different bet. reports 2 & 2.5? In Reports 2.0 the link tool has to be selected and then two fields to be linked are selected and the link is automatically created. In 2.5 the first field is selected and the link tool is then used to link the first field to the second field. REPORT 2.5 SPECIFIC ISSUES. 59.What are the navigator(specific to report 2.5)?

two

types

views

available

in

the

View by structure and view by type . 60. Which of the two views should objects according to possession? view by structure. 421

object

61.How is possible to restrict the user to a list of values while entering values for parameters? By setting the Restrict To List property to true in the parameter property sheet. 62. How is it possible to select generate a select ste. for the query in the query property sheet? By using the the column names.

tables/columns button and then specifying the table and

63. If a parameter is used in a query without being previously defined, what diff. exist betw. report 2.0 and 2.5 when the query is applied? While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a message that a bind parameter has been created. 64. Do user parameters appear in the data modal editor in 2.5? No. 65.What is the diff. when confine mode is on and when it is off? When confine parent in the layout.

mode

is on, an object cannot be moved outside its

66. What is the diff. when Flex mode is mode on and when it is off? When flex mode is the child is resized.

on, reports automatically resizes the parent when

67. How can a button be used in a report to give a drill down facility? By setting the action asscoiated with button to Execute pl/sql option and using the SRW.Run_report function. 68. What are the two ways by which data can be generated for a parameter's list of values? 1. Using static values. 2. Writing select statement. 69. What are the pl/sql interpreter?

two

panes

1.Source pane. 2. Interpreter pane 422

that

Appear

in

the

design

time

70. What are three panes that appear in the run time pl/sql interpreter? 1.Source pane. 2. interpreter pane. 3. Navigator pane. CROSS PRODUCTS AND MATRIX REPORTS 71. How can a cross product be created? By selecting the cross products surrounding the base group of the cross products.

tool

and

drawing

a

new

group

72. How can a group in a cross products be visually distinguished from a group that does not form a cross product? A group that forms part of a cross product will have a thicker border. 73. Atleast how many set of data must a data model have before a data model can be base on it? Four. 74. Is it possible to have a link from a group that is inside a cross product to a group outside ? (Y/N) No. 75. Is it possible to link two groups inside a cross products after the cross products group has been created? No. 76. What is an user exit used for? A way in which to pass control (and possibly arguments ) form Oracle report to another Oracle products of 3 GL and then return control ( and ) back to Oracle reprots. 77. What are the three types of user exits available ? Oracle Precompiler exits, Oracle call interface,NonOracle user exits. 78. How can call interface?

values

be

passed

bet.

precompiler

By using the statement EXECIAFGET & EXECIAFPUT. 423

exits

&

Oracle

79. How can I message to passed to the user from reports? By using SRW.MESSAGE function. Oracle DBA 1. SNAPSHOT is used for [DBA] a] Synonym, data replication

b]

Table space, c] System server, d] Dynamic

Ans : D 2. We can create SNAPSHOTLOG for [DBA] a] Simple snapshots, b] Complex snapshots, c] Both A & B, d] Neither A nor B Ans : A 3. Transactions per rollback segment is derived from [DBA] a] Db_Block_Buffers, b] Processes, c] Shared_Pool_Size, d] None of the above Ans : B 4. ENQUEUE resources parameter information is derived from [DBA] a] Processes or DDL_LOCKS and DML_LOCKS, b] LOG_BUFFER, c] DB__BLOCK_SIZE.. Ans : A 5. LGWR process writes information into a] Database files, b] Control files, c] Redolog files, d] All the above. Ans : C 6. SET TRANSACTION USE ROLLBACK SEGMENT objects in a particular Tablespace a] True, b] False Ans : False

is used to create user

7. Databases overall structure is maintained in a file called a] Redolog file, b] Data file, c] Control file, d] All of the above. Ans : C 8. These following parameters file DB_BLOCK_SIZE, PROCESSES a] True, b] False Ans : False 424

are

optional

in init.ora parameter

9. Constraints cannot be exported through EXPORT a] True, b] False Ans : False

command

10. It is very difficult to grant and manage common privileges needed by different groups of database users using the roles a] True, b] False Ans : False

11. What is difference between a DIALOG WINDOW and a DOCUMENT WINDOW regarding moving the window with respect to the application window a] Both windows behave the same way as far as moving the window is concerned. b] A document window can be moved outside the application window while a dialog window cannot be moved c] A dialog window can be moved outside the application window while a document window cannot be moved Ans : C 12. What is the difference between a MESSAGEBOX and an ALERT a] A messagebox can be used only by the system and cannot be used in user application while an alert can be used in user application also. b] A alert can be used only by the system and cannot be use din user application while an messagebox can be used in user application also. c] An alert requires an response from the userwhile a messagebox just flashes a message and only requires an acknowledment from the user d] An message box requires an response from the userwhile a alert just flashes a message an only requires an acknowledment from the user Ans : C 13. Which of the following is not an reason for the fact that most of the processing is done at the server ? a] To reduce network traffic. b] For application sharing, c] To implement business rules centrally, d] None of the above Ans : D 14. Can a DIALOG WINDOW have scroll bar attached to it ? 425

a] Yes, b] No Ans : B 15. Which of the following is not an advantage of GUI systems ? a] Intuitive and easy to use., b] GUI's can display multiple applications in multiple windows c] GUI's provide more user interface objects for a developer d] None of the above Ans :D 16. What is the difference between a LIST BOX and a COMBO BOX ? a] In the list box, the user is restricted to selecting a value from a list but in a combo box the user can type in a value which is not in the list b] A list box is a data entry area while a combo box can be used only for control purposes c] In a combo box, the user is restricted to selecting a value from a list but in a list box the user can type in a value which is not in the list d] None of the above Ans : A 17. In a CLIENT/SERVER environment , which of the following would not be done at the client ? a] User interface part, b] Data validation at entry line, c] Responding to user events, d] None of the above Ans : D 18. Why is it better to use an INTEGRITY CONSTRAINT to validate data in a table than to use a STORED PROCEDURE ? a] Because an integrity constraint is automatically checked while data is inserted into or updated in a table while a stored procedure has to be specifically invoked b] Because the stored procedure occupies more space in the database than a integrity constraint definition c] Because a stored procedure creates more network traffic than a integrity constraint definition Ans : A 19. Which of the following is not an advantage of a client/server model ? 426

a] A client/server model allows centralised control of data and centralised implementation of business rules. b] A client/server model increases developer;s productivity c] A client/server model is suitable for all applications d] None of the above. Ans : C 20. What does DLL stands for ? a] Dynamic Language Library b] Dynamic Link Library c] Dynamic Load Library d] None of the above Ans : B 21. POST-BLOCK trigger is a a] Navigational trigger b] Key trigger c] Transactional trigger d] None of the above Ans : A 22. The system variable that records the select statement that SQL * FORMS most recently used to populate a block is a] SYSTEM.LAST_RECORD b] SYSTEM.CURSOR_RECORD c] SYSTEM.CURSOR_FIELD d] SYSTEM.LAST_QUERY Ans: D 23. Which of the following is TRUE for the ENFORCE KEY field a] ENFORCE KEY field characterstic indicates the source of the value that SQL*FORMS uses to populate the field b] A field with the ENFORCE KEY characterstic should have the INPUT ALLOWED charaterstic turned off a] Only 1 is TRUE b] Only 2 is TRUE c] Both 1 and 2 are TRUE d] Both 1 and 2 are FALSE Ans : A 24. What is the maximum size of the page ? a] Characters wide & 265 characters length b] Characters wide & 265 characters length c] Characters wide & 80 characters length d] None of the above Ans : B 25. A FORM is madeup of which of the following objects a] block, fields only, 427

b] blocks, fields, pages only, c] blocks, fields, pages, triggers and form level procedures, d] Only blocks. Ans : C 26. For the following statements which is true 1] Page is an object owned by a form 2] Pages are a collection of display information such as constant text and graphics. a] Only 1 is TRUE b] Only 2 is TRUE c] Both 1 & 2 are TRUE d] Both are FALSE Ans : B 27. The packaged procedure the Database is a] Post b] Post form c] Commit form d] None of the above Ans : C 28. Which of the following a] Can be assigned to b] Can be assigned to c] Can be assigned to d] None of the above Ans : B

that

makes

data

in

form permanent in

is TRUE for the SYSTEM VARIABLE $$date$$ a global variable any field only during design time any variable or field during run time

29. Which of the following packaged procedure is UNRESTRICTED ? a] CALL_INPUT, b] CLEAR_BLOCK, c] EXECUTE_QUERY, d] USER_EXIT Ans : D 30. Identify the RESTRICTED packaged procedure from the following a] USER_EXIT, b] MESSAGE, c] BREAK, d] EXIT_FORM Ans : D 31. What is SQL*FORMS a] SQL*FORMS is a 4GL tool for developing & executing Oracle based interactive applications. b] SQL*FORMS is a 3GL tool for connecting to the Database. c] SQL*FORMS is a reporting tool d] None of the above. Ans : A 32. Name the two files that are created when you generate a form using Forms 3.0 a] FMB & FMX, b] FMR & FDX, c] INP & FRM, d] None of the above Ans : C 428

33. What is a trigger a] A piece of logic written in PL/SQL b] Executed at the arrival of a SQL*FORMS event c] Both A & B d] None of the above Ans : C 34. Which of the folowing is TRUE for a ERASE packaged procedure 1] ERASE removes an indicated Global variable & releases the memory associated with it 2] ERASE is used to remove a field from a page 1] Only 1 is TRUE 2] Only 2 is TRUE 3] Both 1 & 2 are TRUE 4] Both 1 & 2 are FALSE Ans : 1 35. All datafiles Tablespace is dropped a] TRUE b] FALSE Ans : B

related

to

a

Tablespace

are

removed

36. Size of Tablespace can be increased by a] Increasing the size of one of the Datafiles b] Adding one or more Datafiles c] Cannot be increased d] None of the above Ans : B 37. Multiple Tablespaces can share a single datafile a] TRUE b] FALSE Ans : B 38. A set of Dictionary tables are created a] Once for the Entire Database b] Every time a user is created c] Every time a Tablespace is created d] None of the above Ans : A 39. Datadictionary can span across multiple Tablespaces a] TRUE b] FALSE Ans : B

429

when

the

40.

What is a DATABLOCK a] Set of Extents b] Set of Segments c] Smallest Database storage unit d] None of the above Ans : C 41. Can an Integrity Constraint be enforced on a table if some existing table data does not satisfy the constraint a] Yes b] No Ans : B 42. A column defined as PRIMARY KEY can have NULL's a] TRUE b] FALSE Ans : B 43. A Transaction ends a] Only when it is Committed b] Only when it is Rolledback c] When it is Committed or Rolledback d] None of the above Ans : C 44. A Database Procedure is stored in the Database a] In compiled form b] As source code c] Both A & B d] Not stored Ans : C 45. A database definition of the trigger a] TRUE b] FALSE Ans : A

trigger

doesnot

apply

to

data

loaded

before

46. Dedicated server configuration is a] One server process - Many user processes b] Many server processes - One user process c] One server process - One user process d] Many server processes - Many user processes Ans : C 47. Which of the following does not affect the size of the SGA a] Database buffer b] Redolog buffer c] Stored procedure d] Shared pool Ans : C 430

the

48. What does a COMMIT statement do to a CURSOR a] Open the Cursor b] Fetch the Cursor c] Close the Cursor d] None of the above Ans : D 49. Which of the following is TRUE 1] Host variables are declared anywhere in the program 2] Host variables are declared in the DECLARE section a] Only 1 is TRUE b] Only 2 is TRUE c] Both 1 & 2are TRUE d] Both are FALSE Ans : B 50. Which of the following is NOT VALID is PL/SQL a] Bool boolean; b] NUM1, NUM2 number; c] deptname dept.dname%type; d] date1 date := sysdate Ans : B 51. Declare fvar number := null; svar number := 5 Begin goto << fproc>> if fvar is null then << fproc>> svar := svar + 5 end if; End; What will be the value of svar after the execution ? a] Error b] 10 c] 5 d] None of the above Ans : A 52. Which of the following is not correct about an Exception ? a] Raised automatically / Explicitly in response to an ORACLE_ERROR b] An exception will be raised when an error occurs in that block c] Process terminates after completion of error sequence. d] A Procedure or Sequence of statements may be processed. Ans : C 53. Which of the following is not correct about User_Defined Exceptions? a] Must be declared b] Must be raised explicitly c] Raised automatically in response to an Oracle error d] None of the above Ans : C 54. A Stored Procedure is a 431

a] Sequence of SQL or PL/SQL statements to perform specific function b] Stored in compiled form in the database c] Can be called from all client environmets d] All of the above Ans : D 55. Which of the following statement is false a] Any procedure can raise an error and return an user message and error number b] Error number ranging from 20000 to 20999 are reserved for user defined messages c] Oracle checks Uniqueness of User defined errors d] Raise_Application_error is used for raising an user defined error. Ans : C 56. Is it another procedure ? a] Yes b] No

possible

to

open

a

cursor which is in a Package in

Ans : A 57. Is it Database Triggers ? a] Yes b] No

possible

to

use Transactional control statements in

Ans : B 58. Is it possible to Enable or Disable a Database trigger ? a] Yes b] No Ans : A 59. PL/SQL supports datatype(s) a] Scalar datatype b] Composite datatype c] All of the above d] None of the above Ans C

432

60. Find the ODD datatype out a] VARCHAR2 b] RECORD c] BOOLEAN d] RAW Ans : B

61. Which of the following is not correct about the "TABLE" datatype ? a] Can contain any no of columns b] Simulates a One-dimensional array of unlimited size c] Column datatype of any Scalar type d] None of the above Ans : A 62. Find the ODD one out of the following a] OPEN b] CLOSE c] INSERT d] FETCH Ans C 63. Which of the following is not correct about Cursor ? a] Cursor is a named Private SQL area b] Cursor holds temporary results c] Cursor is used for retrieving multiple rows d] SQL uses implicit Cursors to retrieve rows Ans : B 64. Which of the following is NOT VALID in PL/SQL ? a] Select ... into b] Update c] Create d] Delete Ans : C 65. What is the Result of the following a] Error b] VIK RAM c] VIKRAM d] NULL Ans : C

433

'VIK'||NULL||'RAM' ?

66. Declare a number := 5; b number := null; c number := 10; Begin if a > b AND a < c then a := c * a; end if; End; What will be the value of 'a' after execution ? a] 50 b] NULL c] 5 d] None of the above Ans : C 67. Does the Database trigger will fire when the table is TRUNCATED ? a] Yes b] No Ans : B 68. SUBSTR(SQUARE ANS ALWAYS WORK HARD,14,6) will return a] ALWAY b} S ALWA c] ALWAYS Ans : C 69. REPLACE('JACK AND JUE','J','BL') will return a] JACK AND BLUE b] BLACK AND JACK c] BLACK AND BLUE d] None of the above Ans : C 70. TRANSLATE('333SQD234','0123456789ABCDPQRST','0123456789') return a] 333234 b] 333333 c] 234333 d] None of the above

will

Ans : A 71.

EMPNO A822 A812 A973 A500 Use these data

ENAME SAL RAMASWAMY 3500 NARAYAN 5000 UMESH 2850 BALAJI 5750 for the following Questions

Select SAL from EMP E1 where 3 > ( Select count(*) from Emp E2 where E1.SAL > E2.SAL ) will retrieve a] 3500,5000,2500 b] 5000,2850 c] 2850,5750 d] 5000,5750 Ans : A 434

72. Is it possible to modify a Datatype of a column when column contains data ? a] Yes b] No Ans B

73. Which of the following is not correct about a View ? a] To protect some of the columns of a table from other users b] Ocuupies data storage space c] To hide complexity of a query d] To hide complexity of a calculations Ans : B 74. Which is not part of the Data Definiton Language ? a] CREATE b] ALTER c] ALTER SESSION Ans : C 75. The a] b] c] d]

Data Manipulation Language statements are INSERT UPDATE SELECT All of the above

Ans : D 76.

EMPNO A822 A812 A973 A500

ENAME RAMASWAMY NARAYAN UMESH BALAJI

SAL 3500 5000 5750

Using the above data Select count(sal) from Emp will retrieve a] 1 b] 0 c] 3 d] None of the above Ans : C

435

77. If an UNIQUE KEY constraint on DATE column is created, will it accept the rows that are inserted with SYSDATE ? a] Will b] Won't Ans : B 78. What are the different events in Triggers ? a] Define, Create b] Drop, Comment c] Insert, Update, Delete d] All of the above Ans : C 79. What built-in subprogram is used to manipulate images in image items ? a] Zoom_out b] Zoom_in' c] Image_zoom d] Zoom_image Ans : C 80. Can we pass RECORD GROUP between FORMS ? a] Yes b] No Ans : A 81. SHOW_ALERT function returns a] Boolean b] Number c] Character d] None of the above Ans : B 82. What SYSTEM VARIABLE is used to refer DATABASE TIME ? a] $$dbtime$$ b] $$time$$ c] $$datetime$$ d] None of the above Ans : A 83. :SYSTEM.EFFECTIVE.DATE varaible is a] Read only b] Read & Write c] Write only d] None of the above Ans : C 436

84. How a] b] c] d]

can you CALL Reports from Forms4.0 ? Run_Report built_in Call_Report built_in Run_Product built_in Call_Product built_in

Ans : C 85. When do you get a .PLL extension ? a] Save Library file b] Generate Library file c] Run Library file d] None of the above Ans : A 86. What is built_in Subprogram ? a] Stored procedure & Function b] Collection of Subprogram c] Collection of Packages d] None of the above Ans : D 87. GET_BLOCK property is a a] Restricted procedure b] Unrestricted procedure c] Library function d] None of the above Ans : D 88. A CONTROL BLOCK can sometimes refer to a BASETABLE a] TRUE b] FALSE

?

Ans : B 89. What do you mean by CHECK BOX ? a] Two state control b] One state control c] Three state control d] none of the above Ans : answer is 2 )

C - Please check the Correcness of this Answer ( The correct

90. List of Values (LOV) supports a] Single column b] Multi column c] Single or Multi column d] None of the above Ans : C 437

91. What is Library in Forms 4.0 ? a] Collection of External field b] Collection of built_in packages c] Collection of PL/SQl functions, procedures and packages d] Collection of PL/SQL procedures & triggers Ans : C 92. Can we trigger ? a] Yes b] No

use

a

RESTRICTED

packaged

procedure

in

WHEN_TEXT_ITEM

Ans : B

93. Can we use GO_BLOCK package in a PRE_TEXT_ITEM trigger ? a] Yes b] No Ans : B 94. What type of file is used for porting Forms 4.5 applications to various platforms ? a] .FMB file b] .FMX file c] .FMT file d] .EXE file Ans : C 95. What built_in procedure is used to get IMAGES in Forms 4.5 ? a] READ_IMAGE_FILE b] GET_IMAGE_FILE c] READ_FILE d] GET_FILE Ans A 96. When a issues SAVEPOINT ? a] Yes b] No

form

is

invoked

with

CALL_FORM

does

Oracle forms

Ans : A 97. Can we attach the same LOV to different fields in Design time ? a] Yes b] No Ans : A

438

98. How a] b] c] d]

do you pass values from one form to another form ? LOV Parameters Local variables None of the above

Ans : B 99. Can you copy the PROGRAM UNIT a] Yes b] No

into an Object group ?

Ans : B 100. Can MULTIPLE DOCUMENT INTERFACE (MDI) be used in Forms 4.5 ? a] Yes b] No Ans : A 101. When is a .FMB file extension is created in Forms 4.5 ? a] Generating form b] Executing form c] Save form d] Run form Ans : C 102. What is a Built_in subprogram ? a] Library b] Stored procedure & Function c] Collection of Subprograms d] None of the above Ans : D 103. What is a RADIO GROUP ? a] Mutually exclusive b] Select more than one column c] Above all TRUE d] Above all FALSE Ans : A 104. Identify the Odd one of the following statements ? a] Poplist b] Tlist c] List of values d] Combo box Ans : C

439

105. What is an ALERT ? a] Modeless window b] Modal window c] Both are TRUE d] None of the above Ans : B 106. Can an Alert message be changed at runtime ? a] Yes b] No Ans : A 107. Can we create an LOV without an RECORD GROUP ? a} Yes b] No Ans : B

108. How many no of columns can a RECORD GROUP have ? a] 10 b] 20 c] 50 d] None of the above Ans D 109. Oracle precompiler translates the EMBEDDED SQL statemens into a] Oracle FORMS b] Oracle REPORTS c] Oracle LIBRARY d] None of the above Ans : D 110. Kind of COMMENT statements placed within SQL statements ? a] Asterisk(*) in column ? b] ANSI SQL style statements(...) c] C-Style comments (/*......*/) d] All the above Ans : D 111. What is the appropriate to a printer ? a] Screen b] Previewer c] Either of the above d] None of the above Ans : D 440

destination

type to send the output

112. What is TERM ? a] TERM is the terminal definition file that describes the terminal from which you are using R20RUN ( Reports run time ) b] TERM is the terminal definition file that describes the terminal from which you are using R20DES ( Reports designer ) c] There is no Parameter called TERM in Reports 2.0 d] None of the above Ans : A 113. If the maximum records retrieved property of a query is set to 10, then a summary value will be calculated a] Only for 10 records b] For all the records retrieved c] For all therecords in the referenced table d] None of the above Ans : A 114. With which function option required ? a] Sum b] Standard deviation c] Variance d] % of Total function

of

a

summary

item

in the COMPUTE AT

Ans : D 115. For a field in a repeating frame, can the source come from a column which does not exist in the datagroup which forms the base of the frame ? a] Yes b] No Ans : A 116. What Oracle Reports ? a] .RDF b] .RDX c] .REP d] None Ans : C

441

are

the

file & file & file & of the

different

.RPX file .RDF file .RDF file above

file extensions that are created by

117. Is it possible to Disable the Parameter form while running the report ? a] Yes b] No Ans : A 118.What are the SQL clauses supported in the link property sheet ? a] WHERE & START WITH b] WHERE & HAVING c} START WITH & HAVING d] WHERE, START WITH & HAVING Ans : D 119. What are the types of Calculated columns available ? a] Summary, Place holder & Procedure column b] Summary, Procedure & Formula columns c] Procedure, Formula & Place holder columns d] Summary, Formula & Place holder columns Ans.: D 120. If two groups are not linked in the data model editor, what is the hierarchy between them? a] There is no hierarchy between unlinked groups b] The group that is right ranks higher than the group that is to the left c] The group that is above or leftmost ranks higher than the group that is to right or below it d] None of the above Ans : C 121. Sequence of events takes place while starting a Database is a] Database opened, File mounted, Instance started b] Instance started, Database mounted & Database opened c] Database opened, Instance started & file mounted d] Files mounted, Instance started & Database opened Ans : B 122. SYSTEM TABLESPACE can be made off-line a] Yes b] No Ans : B

442

123. ENQUEUE_RESOURCES parameter information is derived from a] PROCESS or DDL_LOCKS & DML_LOCKS b] LOG BUFFER c] DB_BLOCK_SIZE d] DB_BLOCK_BUFFERS Ans : A 124. SMON process is used to write into LOG files a] TRUE b] FALSE Ans : B 125. EXP command is used a] To take Backup of the Oracle Database b] To import data from the exported dump file c] To create Rollback segments d] None of the above Ans : A 126. SNAPSHOTS cannot be refreshed automatically a] TRUE b] FALSE Ans : B 127. The User can set Archive file name formats a] TRUE b] FALSE Ans : A 128. The following file DB_BLOCK_SIZE, PROCESS a} TRUE b] FALSE Ans : B 129. NOARCHIEVELOG Archieve mode a] TRUE b] FALSE

parameters

are

parameter

is

optional

in init.ora parameter

used to enable the database in

Ans : B 130. Constraints cannot be exported through Export command? a] TRUE b] FALSE Ans : B

443

131. It is very difficult to grant and manage common priveleges needed by different groups of database users using roles a] TRUE b] FALSE Ans : B 132. The status of the Rollback segment can be viewed through a] DBA_SEGMENTS b] DBA_ROLES c] DBA_FREE_SPACES d] DBA_ROLLBACK_SEG Ans : D 133. Explicitly we can assign transaction to a rollback segment a] TRUE B] FALSE Ans : A 134. What file is read by ODBC to load drivers ? a] ODBC.INI b] ODBC.DLL c] ODBCDRV.INI d] None of the above Ans : A

444

J2EE 1. What exception is thrown when Servlet initialization fails ? (a) IOException (b) ServletException (c) RemoteException ANS: (b) ------------------------------------------------------------------2. How can a Servlet call a JSP error page ? (a) This capability is not supported. (b) When the servlet throws the exception, it will automatically be caught by the calling JSP page. (c) The servlet needs to forward the request to the specific error page URL. The exception is passed along as an attribute named "javax.servlet.jsp.jspException". (d) The servlet needs to redirect the response to the specific error page, saving the exception off in a cookie. ANS: (c) ------------------------------------------------------------------3. What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()? (a) forward executes on the client while sendRedirect() executes on the server. (b) forward executes on the server while sendRedirect() executes on the client. (c) The two methods perform identically. ANS: (b) ------------------------------------------------------------------445

4. Why beans are used in J2EE architecture in stead of writing all the code in JSPs ? (a) Allows separation of roles between web developers and application developers (b) Allows integration with Content Management tools ANS: (a) ------------------------------------------------------------------5. Why DB connections are not written directly in JSPs ? (a) Response is slow (b) Not a standard J2EE architecture (c) Load Balancing is not possible (d) All the above (e) Both (b) and (c) ANS: I think answer is (e). I am not sure whether response from database is slow just because we include the database access code in JSP page. ------------------------------------------------------------------6. How multiple EJB instances are managed ? (a) Connection Pooling (b) Caching of EJB instances (c) EJB Passivation (d) All the above ANS: I think answer is (d) ------------------------------------------------------------------7. At what stage, the life cycle of a CMP bean can be assumed to be started ? (a) before ejbCreate() method is executed (b) after ejbCreate() method is executed (c) in postCreate() method (d) after executing ejbStore() ------------------------------------------------------------------8. Lot of Questions on "EJB Transactions" and how to manage them. ------------------------------------------------------------------446

9. In JSP, how can you know what HTTP method (GET or POST) is used by client request ? (a) by using request.getMethod() (b) by using request.setMethod() (c) impossible to know ANS: (a) ------------------------------------------------------------------10. What is legal about JSP scriplets (a) A loop can begin in one Scriptlet and end in another (b) Statements in Scriptlets should follow Java Syntax (c) Semicolon is needed at the end of each statement in a Scriptlet (d) All the above ANS: (d) ------------------------------------------------------------------11. Which method is called first each time a Servlet is invoked ? (a) Start() (b) Run() (c) Servive() (d) init() ANS: (d) ------------------------------------------------------------------12. The time between Command Execution and Response is called ______ (a) Granularity (b) Latency (c) Lag time ANS: (c) EXPLANATION: Latency:

447

Latency is a measure of the temporal delay. Typically, in xDSL, latency refers to the delay in time between the sending of a unit of data at the originating end of a connection and the reception of that unit at the destination end. In a computer system, latency is often used to mean any delay or waiting that increases real or perceived response time beyond the response time desired. Within a computer, latency can be removed or "hidden" by such techniques as prefetching (anticipating the need for data input requests) and multithreading, or using parallelism across multiple execution threads. In networking, the amount of time it takes a packet to travel from source to destination. Together, latency and bandwidth define the speed and capacity of a network. Granularity: The extent to which a system contains separate components (like granules). The more components in a system -- or the greater the granularity -- the more flexible it is. Granularity is a term often used in parallel processing to indicate independent processes that could be distributed to multiple CPUs. Fine granularity is illustrated by execution of statements or small loop iterations as separate processes; coarse granularity involves subroutines or sets of subroutines as separate processes. The more processes, the "finer" the granularity and the more overhead required to keep track of them. Granularity can also be related to the temporal duration of a "task" at work. It is not only the number of processes but also how much work each process does, relative to the time of synchronization, that determines the overhead and reduces speedup figures. Lag Time: Lag Time is the amount of time between making an online request or command and receiving a response. A primary goal of advertising network efficiency is to minimize lag time. ------------------------------------------------------------------13. 2 Questions on RMI and EJB related (I don't reemember them) ------------------------------------------------------------------14. Purpose of <jsp:plugin> tag (a) used to incorporate Java applets into a Web page. (b) Downloads a plugin to the client Web browser to execute an applet or Bean. (c) Both (a) & (b) ANS: (c) EXPLANATION: 448

JSP Syntax : <jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [ name="instanceName" ] [ archive="URIToArchive, ..." ] [ align="bottom|top|middle|left|right" ] [ height="displayPixels" ] [ width="displayPixels" ] [ hspace="leftRightPixels" ] [ vspace="topBottomPixels" ] [ jreversion="JREVersionNumber | 1.1" ] [ nspluginurl="URLToPlugin" ] [ iepluginurl="URLToPlugin" ] > [ <jsp:params> [ <jsp:param name="parameterName" value="parameterValue" /> ]+ ] [ <jsp:fallback> text message for user ] Description : The <jsp:plugin> tag is replaced by either an or <embed> tag, whichever is most appropriate for the client Web browser (the tag is for browsers that use HTML 4.0). The <jsp:params> element sends parameter names and values to an applet or Bean at startup. The <jsp:fallback> element provides a message for the user if the plugin does not start. If the plugin starts but the applet or Bean does not, the plugin usually displays a popup window explaining the error to the user. The <jsp:plugin> tag takes most of its attributes from the HTML and tags ( is defined in HTML 3.2 and in HTML 4.0). You may want to refer to the official HTML specifications in which these tags are introduced: For HTML 3.2: http://www.w3.org/TR/REC-html32.html For HTML 4.0: http://www.w3.org/TR/REC-html40/ Attributes : type="bean|applet" 449

The type of object the plugin will execute. You must specify either bean or applet, as this attribute has no default value. code="classFileName" The name of the Java class file that the plugin will execute. You must include the .class extension in the name following code. The filename is relative to the directory named in the codebase attribute. codebase="classFileDirectoryName" The absolute or relative path to the directory that contains the applet's code. If you do not supply a value, the path of the JSP file that calls <jsp:plugin> is used. name="instanceName" A name for the Bean or applet instance, which makes it possible for applets or Beans called by the same JSP file to communicate with each other. archive="URIToArchive, ..." A comma-separated list of paths that locate archive files to be preloaded with a class loader located in the directory named in codebase. The archive files are loaded securely, often over a network, and typically improve the applet's performance. align="bottom|top|middle|left|right" The positioning of the image displayed by the applet or Bean relative to the line in the JSP result page that corresponds to the line in the JSP file containing the <jsp:plugin> tag. The results of the different values are listed below: bottom Aligns the bottom of the image with the baseline of the text line. top Aligns the top of the image with the top of the text line. middle Aligns the vertical center of the image with the baseline of the text line. left Floats the image to the left margin and flows text along the image's right side. right Floats the image to the right margin and flows text along the image's left side. height="displayPixels" width="displayPixels" The initial height and width, in pixels, of the image the applet or Bean displays, not counting any windows or dialog boxes the applet or Bean brings up. hspace="leftRightPixels" vspace="topBottomPixels" The amount of space, in pixels, to the left and right (or top and bottom) of the image the applet or Bean displays. Must be a small nonzero number. 450

jreversion="JREVersionNumber|1.1" The version of the Java Runtime Environment (JRE) the applet or Bean requires. The default value is 1.1. nspluginurl="URLToPlugin" The URL where the user can download the JRE plugin for Netscape Navigator. The value is a full URL, with a protocol name, optional port number, and domain name. iepluginurl="URLToPlugin" The URL where the user can download the JRE plugin for Internet Explorer. The value is a full URL, with a protocol name, optional port number, and domain name. <jsp:params> [ <jsp:param name="parameterName" value="parameterValue" /> ]+ The parameters and values that you want to pass to the applet or Bean. To specify more than one name and value, use multiple <jsp:param> tags within the <jsp:params> element. Applets read parameters with the java.applet.Applet.getParameter method. <jsp:fallback> text message for user A text message to display for the user if the plugin cannot be started.

Example: The <jsp:plugin> directive takes care of generating all the HTML code necessary to embed and activate a Java applet. Consider the following example: ---------- <jsp:plugin type="applet" code="NewsTicker.class" name="newsticker" height="100" width="100"> <jsp:params> <jsp:param name="x" value="10"/> <jsp:param name="y" value="25"/>

451

<jsp:fallback>Oops! Something bad happened and I can't display this applet ----------The code above sets up the applet contained in "NewsTicker.class", and passes it a bunch of name-value pairs of parameters. The <jsp:param> tag is used to pass these parameters to the applet, while the <jsp:fallback> directive contains error text, in the event that the applet cannot be found or displayed. When JSP compiles and renders the page, the code above is automatically converted to its HTML equivalent. <EMBED type="application/x-java-applet;" width="100" height="100" pluginspage="http://java.sun.com/products/plugin/" java_code="NewsTicker.class" y=25 x=10> Oops! Something bad happened and I can't display this applet ----------------------------------------------------------------------------15. Difference between <jsp:forward> and <jsp:include> tags 452

ANS: <jsp:forward> transfers the control to the mentioned destination page. <jsp:include> tag substitutes the output of the destination page. Control remains on the same page. ------------------------------------------------------------------16. Which of the following is true ? (a) Unlimited data transfer can be done using POST method (b) Data is visible in Browser URL when using POST method (c) When large amounts of data transfer is to be done, GET method is used. ANS: (a) ------------------------------------------------------------------17. EJB class should implement (a) javax.ejb.EntityBean (b) javax.ejb.rmi (c) javax.ejb.EJBHome (d) javax.ejb.EJBObject ANS: I think the answer is (a) ------------------------------------------------------------------18. Generally Servlets are used for complete HTML generation. If you want to generate partial HTMLs that include some static text (This should not be hard coded in Servlets) as well as some dynamic text, what method do you use ? (a) Serverside includes (b) JSP code in HTML (c) Not possible to generate incomplete HTMLs using Servlets (Note: I don't remember the question word to word. But it is similar to what I have given) ------------------------------------------------------------------19. Which of the following can not be used as the scope when using a JavaBean with JSP? (a) session (b) application 453

(c) request (d) response ANS: (d) ------------------------------------------------------------------20. Which is true about Servlets (a) Only one instance of Servlet is created in memory (b) Multi-Threading is used to service multiple requests (c) Both (a) & (b) ANS: I think the answer is (c) ------------------------------------------------------------------21. What is Temporary Servlet ? (a) Servlet that is destroyed at run time (b) Servlet that exists for a session (c) Servlet that is started and stopped for each request ANS: (c) EXPLANATION: A temporary servlet is started when a request arrives and shut down after the response is generated. A permanent servlet is loaded when the server is started and lives until the server is shut down. * This is useful when startup costs are high, such as a servlet that establishes a connection to a database. * Also useful for permanent server-side service, such as an RMI server. * Provides faster response to client requests when this is crucial. Being temporary or permanent is part of the server configuration. ------------------------------------------------------------------22. Although it is not commonly done, what will you do if you want to have multiple instances of Servlet in memory and if they have to share the execution of a user request ? (a) Defnie Single Thread model (b) Cannot be done 454

(Note: I don't remember the question & answers word to word. But it is similar to what I have given) ------------------------------------------------------------------23. In WebLogic 5.1, how can you make a JSP application work (a) By changing the root directory (b) By creating a vitual directory in Server console (c) By creating a vitual directory in client console -------------------------------------------------------------------

___________________________________________________________________ In the init(ServletConfig) method of Servlet life cycle, what method can be used to access the ServletConfig object ? (a) getServletInfo() (b) getInitParameters() (c) getServletConfig() ANS: (c) ___________________________________________________________________ The Page directive in JSP is defined as follows: <%@ page language="java" session="false" isErrorPage="false" %> Then which of the implicit objects won't be available ? (a) session, request (b) exception, request (c) exception, config (d) session, exception ANS: I think answer is (d) ___________________________________________________________________ ejbCreate() method of CMP bean returns (a) null (b) Primary Key class (c) Home Object (d) Remote Object ANS: (a) Explanation: ejbCreate() method of BMP bean returns the Primary Key, where as ejbCreate() method of CMP bean returns null. ___________________________________________________________________ How can a EJB pass it's reference to another EJB ? ___________________________________________________________________ Which of the following is correct syntax for an Abstract class ? (a) abstract double area() { } 455

(b) abstract double area() (c) abstract double area(); (d) abstract double area(); { } ANS: (c) ___________________________________________________________________ A JSP page is opened in a particular Session. A button is present in that JSP page onclick of which a new Window gets opened. (a) The Session is not valid in the new Window (b) The Session is valid in the new Window ANS: I think the answer is (b) ___________________________________________________________________ Which of the following JSP expressions are valid ? (a) <%= "Sorry"+"for the"+"break" %> (b) <%= "Sorry"+"for the"+"break"; %> (c) <%= "Sorry" %> (d) <%= "Sorry"; %> ANS: ___________________________________________________________________ A class can be converted to a thread by implementing the interface __________ (a) Thread (b) Runnable ANS: (b) ___________________________________________________________________ What is the output of following block of program ? boolean var = false; if(var = true) { System.out.println("TRUE"); } else { System.out.println("FALSE"); } (a) TRUE (b) FALSE (c) Compilation Error (d) Run-time Error ANS: (a) EXPLANATION: The code compiles and runs fine and the 'if' test succeeds because 'var' is set to 'true' (rather than tested for 'true') in the 'if' argument. ___________________________________________________________________ Which is not allowed in EJB programming ? (a) Thread Management (b) Transient Fields (c) Listening on a Socket ANS: ___________________________________________________________________ 456

What happens if Database Updation code is written in ejbPassivate() method and if this method is called ? (a) Exception is thrown (b) Successfully executes the Database Updation code (c) Compilation error occurs indicating that Database Updation code should not be written in ejbPassivate() (d) ejbStore() method is called ANS: ___________________________________________________________________ A Vector is declared as follows. What happens if the code tried to add 6 th element to this Vector new vector(5,10) (a) The element will be successfully added (b) ArrayIndexOutOfBounds Exception (c) The Vector allocates space to accommodate up to 15 elements ANS: (a) and (c) EXPLANATION: The 1 st argument in the constructor is the initial size of Vector and the 2 nd argument in the constructor is the growth in size (for each allocation) This Vector is created with 5 elements and when an extra element (6 th one) is tried to be added, the vector grows in size by 10. ___________________________________________________________________ Which is the data structure used to store sorted map elements ? (a) HashSet (b) Hashmap (c) Map (d) TreeMap ANS: I think the answer is (d) ___________________________________________________________________ SessionListerner defines following methods (a) sessionCreated, sessionReplaced (b) sessionCreated, sessionDestroyed (c) sessionDestroyed, sessionReplaced ANS: ___________________________________________________________________ Which of the following is true ? (a) Stateless session beans doesn't preserve any state across method calls (b) Stateful session beans can be accesses by multiple users at the same time ANS: (a) ___________________________________________________________________ Stateful Session beans contain (a) Home Interface (b) Remote Interface (c) Bean Class (d) All ANS: (d) ___________________________________________________________________ 457

What is the Life Cycle of Session bean ? ___________________________________________________________________ Stateless session bean is instantiated by (a) newInstance() (b) create() ANS: ___________________________________________________________________ A servlet implements Single Thread model public class BasicServlet extends HttpServlet implements SingleThreadModel { int number = 0; public void service(HttpServletRequest req, HttpServletResponse res) { } } Which is thread safe ? (a) Only the variable num (b) Only the HttpServletRequest object req (c) Both the variable num & the HttpServletRequest object req ___________________________________________________________________ If you are trying to call an EJB that is timed out, what will happen ? (a) Exception (b) It gets executed ___________________________________________________________________ A method is defined in a class as : void processUser(int i) { } If this method is overriden in a sub class,_____ (a) the new method should return int (b) the new method can return any type of values (c) the argument list of new method should exactly match that of overriden method (d) the return type of new method should exactly match that of overriden method ANS: (c) & (d) ___________________________________________________________________ In a JSP page, a statement is declared as follows: <%! String strTemp = request.getParameter("Name"); %> And below that, an _expression appears as: <% System.out.println("The Name of person is: "+strTemp); %> What is the output of this _expression, if this JSP page is invoked in browser using URL : http://localhost:8080/JSP/TrialPage.jsp?Name=Chetana (Assume that this URL is correct) (a) The Name of person is: Chetana (b) The Name of person is: (c) The Name of person is: null (d) None ANS: (a) ___________________________________________________________________ 458

Without the use of Cartesian product, how many joining conditions are required to join 4 tables ? (a) 1 (b) 2 (c) 3 (d) 4 ANS: ___________________________________________________________________ What is the output of following piece of code ? int x = 2; switch (x) { case 1:System.out.println("1"); case 2: case 3:System.out.println("3"); case 4: case 5:System.out.println("5"); } (a) No output (b) 3 and 5 (c) 1, 3 and 5 (d) 3 ANS: (b) ---------------------------------------------------EJB ---------------------------------------------------1) What is true about 'Primary Key class' in Entity Beans ? (a) Used to identify the entity bean based on EJB type, Home Interface and Container Context. (b) Used to identify the entity bean based on EJB type, Remote Interface and Container Context. (c) The definition of Primary Key class can be deferred till deployment -------------------2) The Home Interface in Entity beans (a) Provides at least one create() method (b) May not provide any create() method (c) Provides at least one findByPrimaryKey() method (d) May not provide any findByPrimaryKey() method -------------------459

3) In CMP of Entity beans (a) Constructor with no arguments is defined (b) Constructor is not defined -------------------4) What is the purpose of ejbLoad() -------------------5) What is the purpose of ejbStore() -------------------6) In EJB, when a system error occurs, which exception is thrown ? (a) EJBException (b) RemoteException -------------------7) In EJB, which of the following is an application level Exception ? (a) NullPointerException (b) ArrayOutOfBoundsException (c) CreateException (d) ObjectNotFoundException (e) All the above (f) None of the above -------------------8) CMP bean provides (a) Empty implementation of ejbLoad() and ejbStore() (a) Concrete implementation of ejbLoad() and ejbStore() ----------------------------------------------------

460

---------------------------------------------------JSP and Mislleneous ---------------------------------------------------1) What is the purpose of XSL (a) Convert XML to HTML (b) Convert HTML to XML ANS: (a) -------------------2) resultSet has the following methods (a) next() (b) first() (c) a & b (d) No methods -------------------3) In WebLogic clusters, what is the load balancing algorithm ? (a) RoundRobin (b) FIFO (c) LIFO ANS: (a) WebLogic uses a Round-Robin strategy as default algorithm for forwarding the HTTP requests inside a cluster. Weight-based and random algorithms are also available. -------------------4) How many Queues does a MDB listen to ? (a) 1 (b) 2 (c) Any Number (d) 10 ANS: (a) An MDB can be associated with only one Queue or Topic 461

-------------------5) Where is the Deployment Descriptor placed ? (a) WEB-INF directory (b) WEB-INF/CLASSES directory (c) It will be mentioned in CLASSPATH (d) The place can be specified in APPLICATION.xml -------------------6) To denote distributed applications, What is the tag used in Deployment Descriptor ? (a) distributable (d) distributed="true" (c) both a & b -------------------7) Can a JSP be converted to SERVLET and the vice versa always ? (a) YES (b) NO -------------------8) Empty JSP Tag definitions are given in Deployment Descriptor. Then which of the following syntaxes are correct ? (I don't remember the options) -------------------9) One small question on <jsp:useBean> tag ----------------------------------------------------

462

---------------------------------------------------JAVA ---------------------------------------------------1) Which of the following 2 methods executes faster ? class Trial { String _member; void method1() { for(int i=0;i<2048;i++) { _member += "test"; } } void method2() { String temp; for(int i=0;i<2048;i++) { temp += "test"; } _member = temp; } } (a) method1() (b) method2() (c) Both method1() and method2() takes same time for execution ANS: (b) Accessing method variables requires less overhead than accessing class variables. -------------------2) Integer.parseInt("12a") returns (a) Exception (b) 1 (c) 0 463

(d) -1 ANS: (a) -------------------3) By default, Strings to functions are passed using the method (a) Call by Value (b) Call by Reference (c) Strings cannot be passed to function ANS: (b) String is a class defined in java.lang and in java all classes are passed by reference. -------------------4) What is the difference between OVERRIDING and OVERLOADING -------------------5) What is the output of following program ? class Test { public static void main(String args[]) { for(int i=0;i<2;i++) { System.out.println(i--); } } } (a) Goes into infinite loop (b) 0,1 (c) 0,1,2 (d) None ANS: (a) -------------------6) 't' is the reference to a class that extends THREAD. Then how to suspend the execution of this thread ? (a) t.yield() 464

(b) yield(t) (c) yield() (d) yield(100) where 100 is the milli seconds of time -------------------7) What is the functionality of instanceOf() ? -------------------8) How many String objects are created by the following statements ? String str = " a+b=10 "; trim(str) str.replace(+,-); (a) 1 (b) 2 (c) 3 (d) 4 ANS: (c) Strings are immutable. So, for each String operation, one new object is generated. -------------------9) (A program is given. I don't remember exactly) An ABSTRACT class is declared and the code is tried to instantiate it. The Question was whether it's legal to do it or not ? -------------------10) A question on "interface" -------------------11) Cleaning operation in Java is done in the method (a) finally() (b) finalize() (c) final() -------------------12) Question on whether Static method can be overriden 465

-------------------13) How to prevent a class from being the Base Class ? (a) declare it as final (b) declare it as static -------------------14) If we want to read a very big text file with so many mega bytes of data, what shall we use ? (a) FileInputStream (b) InputStreamReader (c) BufferedReader -------------------15) One Question on Inner Classes. -------------------16) One program on Overloading and Overriding -------------------17) A program given using try, catch and finally and it is asked to find out which statements get executed ? -------------------18) What code, if written, below the (//code here) will display 0. class Test { public static void main(String argv[]) { int i=0; //code here } } (a) System.out.println(i++) (b) System.out.println(i+'0') (c) System.out.println(i--) 466

(d) System.out.println(i) ANS: (a),(c),(d) The option (b) displays the ASCII value of '0'. So, the output in this case is: 48 -------------------19) What is the better way of writing the Constructor with 2 parameters in the following code: class Test { int x,y; Test(int a) { //Code for very complex operations will be written //in this place x=a; } Test(int a, int b) { //Code for very complex operations will be written //in this place (same code as in above constructor) x=a; y=b; } } ----------------------------------------------------------------------1) Question on Static Methods, whether they can be overloaded or not -------------------2) A java program on nested (inner) loops and it is asked what is the output of the program. 467

-------------------3) Once a Servlet is initialized, how do you get the initialization parameters ? (a) Initialization parameters will not be stored (b) They will be stored in instance variables (c) using config.getInitParameters() ANS: I think answer is (c) -------------------4) A question on functionality of tag in JSP -------------------5) If the cookies are disabled, how can you maintain the Session. ANS: URL rewriting -------------------6) If there are strict timelines and if you want to get high performance for JSP to DB access, what method you suggest ? (a) Moving application server in to same manchine as Database (b) By storing results in Cache (c) By implementing Connection Pooling ANS: I think answer is (c) -------------------7) A question on MVC architecture and the functionality of Controller and View. -------------------8) Question on Design Pattern. (I don't remember it) -------------------9) Which Design Pattern hides the complexities of all sub-systems ? (I don't remember the options and also don't know answer.) -------------------468

10) In CMP bean, which method executes only once in life time (a) setEntityContext() (b) create() (c) remove() (d) find() ANS: I think answer is (b) -------------------11) Which bean can be called as Multi-Threaded bean ? (a) Entity beans (b) Stateless Session beans (c) Stateful Session beans (d) Pooled Stateless Session beans ANS: I think answer is (d) -------------------12) A question on Threads in Java, whether we need to mention the word "Daemon" explicitly to make a thread as Daemon. -------------------13) A question on Transactions of EJB. I think the question is something similar to "Which is faster ?" (a) TRANSACTION_UNREPEATABLE_READ (b) TRANSACTION_REPEATABLE_READ (c) TRANSACTION_COMMIT_READ (d) TRANSACTION_UNCOMMIT_READ (I don't know answer and also I am not sure of options. but the options are something similar to this.) -------------------14) Question on EJB Home Object, Remote Object and what functionalities will be performed by each. -------------------469

15) What is the difference between Server and Container (a) A Container can have multiple Servers (b) A Server can have multiple Containers (c) A Server can have only one Container ANS: I think answer is (b) -------------------16) ejbStore() method is equivalent to (a) SELECT (b) INSERT (c) UPDATE (d) DELETE ANS: I think answer is (c) -------------------17) A question on where the garbage collection is done. I think the answer is : "finalize()" method -------------------18) A question properties of Primary key in Entity Beans (I don't remember the options exactly.) (a) Primary key consists of only basic data types in java (b) Primary key can contain composite data types 1) What is diffrence between StateFul and Stateless Session Bean? A Stateful Session Bean is a bean that is designed to service business processes that span multiple method requests or transactions. Stateful Session beans retain state on behalf of an individual client. Stateless Session Beans do not maintain state. EJB containers pools stateless session beans and reuses them to service many clients. Stateful session beans can be passivated and reused for other clients. But this involves I/O bottlenecks. Because a stateful session bean caches client conversation in memory, a bean failure may result in loosing the entire client conversation. Therefore, while writing a stateful session bean the bean developer has to keep the bean failure and client conversation loss in mind. 470

In case of stateless session beans, client specific data has to be pushed to the bean for each method invocation which will result in increase in the network traffic. This can be avoided in a number of ways like persisting the client specific data in database or in JNDI. But this also results in I/O performance bottlenecks. If the business process spans multiple invocations thereby requiring a conversation then stateful session bean will be the ideal choice. On the other hand, if business process lasts only for a single method call, stateless session bean model suits. Stateful session beans remembers the previous request and responses. But stateless beans do not. stateful does not have pooling concept, whereas the stateless bean instances are pooled -------------------------------------------------------------------

2) What is difference between BeanMangedPersistance and ContainerMangedPersistance? CMP: Tx behaviour in beans are defined in transaction attributes of the methods BMP: Programmers has to write a code that implements Tx behaviour to the bean class. Tuned CMP entity beans offer better performance than BMP entity beans. Moving towards the CMP based approach provides database independence since it does not contain any database storage APIs within it. Since the container performs database operations on behalf of the CMP entity bean, they are harder to debug. BMP beans offers more control and flexibility that CMP beans. Diff 1) In BMP you will take care of all the connection and you write the SQL code inside the bean whereas in CMP the container will take care of it Diff 2) The BMP is not portable across all DB's.whereas the CMP is ------------------------------------------------------------------(3)Draw and explain MVC architecture? MVC Architecture is Module- View-Controller Architecture. Controller is the one which controls the flow of application / services the requests from the View. Module is the other layer which performs the exact operations. Each layer should be loosely coupled as much as possible. 471

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

(4)Difference between forward(request,response) and SendRedirect(url) in Servlet? With Forward, request & response would be passed to the destination URL which should be relative (means that the destination URL shud be within a servlet context). Also, after executing forward method, the control will return back to the same method from where the forward method was called. All the opposite to the above points apply to sendRedirect. (OR)The forward will redirect in the application server itself. It does not come to the client. whereas Response.sendredirect() will come to the client and go back ...ie. URL appending will happen. ------------------------------------------------------------------(5)What is Synchornize? Synchronize is a technique by which a particular block is made accessible only by a single instance at any time. (OR) When two or more objects try to access a resource, the method of letting in one object to access a resource is called sync ------------------------------------------------------------------(6)How to prevent Dead Lock? Using synchronization mechanism. For Deadlock avoidance use Simplest algorithm where each process tells max number of resources it will ever need. As process runs, it requests resources but never exceeds max number of resources. System schedules processes and allocates resoures in a way that ensures that no deadlock results. ------------------------------------------------------------------7)Explain different way of using thread? : The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help 472

------------------------------------------------------------------(8)what are pass by reference and passby value? Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. ------------------------------------------------------------------(9)How Servlet Maintain Session and EJB Maintain Session? Servlets maintain session in ServleContext and EJB's in EJBContext. ------------------------------------------------------------------(10)Explain DOM and SAX Parser? DOM parser is one which makes the entire XML passed as a tree Structure and will have it in memory. Any modification can be done to the XML. SAX parser is one which triggers predefined events when the parser encounters the tags in XML. Event-driven parser. Entire XML will not be stored in memory. Bit faster than DOM. NO modifications can be done to the XML. ------------------------------------------------------------------(11)What is HashMap and Map? Map is Interface and Hashmap is class that implements that and its not serialized HashMap is non serialized and Hashtable is serialized ------------------------------------------------------------------(12)Difference between HashMap and HashTable? The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. 473

------------------------------------------------------------------(12a) Difference between Vector and ArrayList? Vector is serialized whereas arraylist is not ------------------------------------------------------------------(13)Difference between Swing and Awt? AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT. ------------------------------------------------------------------14) Explain types of Enterprise Beans? Session beans -> Associated with a client and keeps states for a client Entity Beans -> Represents some entity in persistent storage such as a database ------------------------------------------------------------------15) What is enterprise bean? Server side reusable java component Offers services that are hard to implement by the programmer Sun: Enterprise Bean architecture is a component architecture for the deployment and development of component-based distributed business applications. Applications written using enterprise java beans are scalable, transactional and multi-user secure. These applications may be written once and then deployed on any server plattform that supports enterprise java beans specification. Enterprise beans are executed by the J2EE server. First version 1.0 contained session beans, entity beans were not included. Entity beans were added to version 1.1 which came out during year 1999. Current release is EJB version 1.2 ------------------------------------------------------------------16)Services of EJB? 474

Database management : –Database connection pooling –DataSource, offered by the J2EE server. Needed to access connection pool of the server. –Database access is configured to the J2EE server -> easy to change database / database driver Transaction management : –Distributed transactions –J2EE server offers transaction monitor which can be accessed by the client. Security management : –Authetication –Authorization –encryption

Enterprise java beans can be distributed /replicated into separate machines Distribution/replication offers –Load balancing, load can be divided into separate servers. –Failover, if one server fails, others can keep on processing normally. –Performance, one server is not so heavy loaded. Also, for example Weblogic has thread pools for improving performance in one server. ------------------------------------------------------------------17)When to choose EJB? Server will be heavy loaded : –Distribution of servers helps to achieve better performance. Server should have replica for the case of failure of one server: –Replication is invisible to the programmer Distributed transactions are needed " –J2EE server offers transaction monitor that takes care of transaction management. –Distributed transactions are invisible to the programmer Other services vs. money : Weblogic J2EE server ~ 80 000 mk and Jbuilder X Professional Edition ~ 5 000mk ------------------------------------------------------------------475

18)Why not to use free J2EE servers? –no tecnical support –harder to use (no graphical user interface ...) –no integration to development tools (for example, Jbuilder) –Bugs? Other problems during project? ------------------------------------------------------------------19) Alternative:Tuxedo Tuxedo is a middleware that offers scalability services and transaction monitors. C or C++ based. Can be used with Java client by classes in JOLT package offered by BEA. Faster that J2EE server? Harder to program? Harder to debug? Implementation is platform dependent. ------------------------------------------------------------------20) J2EE server offers DataSource: –Object that can be used to achieve database connection from the connection pool. –Can be accessed by the interface DataSource Transaction monitor: –Can be accessed by the interface UserTransaction. Java Naming and the Directory Service : ------------------------------------------------------------------21)Java Naming and the Directory Service Naming service is needed to locate beans home interfaces or other objects (DataSource, UserTransaction): –For example, jndi name of the DataSource Directory service is needed to store and retrieve properties by their name: 476

–jndi name: java:comp/env/propertyName ------------------------------------------------------------------22)XML – deployment descriptor ejb-jar.xml + server-specific xml- file Which is then Packed in a jar – file together with bean classes. Beans are packaged into EJB JAR file , Manifest file is used to list EJB’s and jar file holding Deployment descriptor. ------------------------------------------------------------------23) Session Bean Developer programs three classes: –Home interface, contains methods for creating (and locating for entity beans) bean instances. –Remote interface, contains business methods the bean offers. –Bean class, contains the business logic of the enterprise bean. ------------------------------------------------------------------24)Entity Beans Represents one row in the database: –Easy way to access database –business logic concept to manipulate data. Container managed persistence vs. bean managed persistence: Programmer creates three or four classes: –Home interface for locating beans –Remote interface that contains business methods for clients. –Bean class that implements bean’s behaviour. –Primary key class – that represents primary key in the database. Used to locate beans. Primary key class is not needed if primary key is a single field that could

477

------------------------------------------------------------------25) When to use which bean? Entity beans are effective when application wants to access one row at a time. If many rows needs to be fetched, using session beans can be better alternative ava class (for example, Integer). Entity beans are efficient when working with one row at a time Cause a lot of network trafic. Session Beans are efficient when client wants to access database directry. –fetching/updating multiple rows from the database -------------------------------------------------------------------

26) Explain J2EE Arch? Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle transaction and state management, multithreading, resource pooling, and other complex low-level details. The component-based and platform-independent J2EE architecture makes J2EE applications easy to write because business logic is organized into reusable components and the J2EE server provides underlying services in the form of a container for every component type. Because you do not have to develop these services yourself, you are free to concentrate on solving the business problem at hand. Containers and Services : Component are installed in their containers during deployment and are the interface between a component and the low-level platform-specific functionality that supports the component. Before a web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container. The assembly process involves specifying container settings for each component in the J2EE application and for the J2EE application itself. Container settings customize the underlying support provided by the J2EE Server, which include services such as security, transaction management, Java Naming and Directory InterfaceTM (JNDI) lookups, and remote connectivity.

478

Container Types : The deployment process installs J2EE application components in the following types of J2EE containers. The J2EE components and container addressed in this tutorial are shown in Figure 5. An Enterprise JavaBeans (EJB) container manages the execution of all enterprise beans for one J2EE application. Enterprise beans and their container run on the J2EE server. A web container manages the execution of all JSP page and servlet components for one J2EE application. Web components and their container run on the J2EE server. An application client container manages the execution of all application client components for one J2EE application. Application clients and their container run on the client machine. An applet container is the web browser and Java Plug-in combination running on the client machine. -------------------------------------------------------------------

479

PL\SQL What is PL/SQL and what is it used for? PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and data types are similar to that of ADA. The PL/SQL language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database.

Should one use PL/SQL or Java to code procedures and triggers? Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever desupport PL/SQL in favour of Java?". Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries. PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments: PL/SQL: Data centric and tightly integrated into the database Proprietary to Oracle and difficult to port to other database systems Data manipulation is slightly faster in PL/SQL than in Java Easier to use than Java (depending on your background) Java: Open standard, not proprietary to Oracle Incurs some data conversion overhead between the Database and Java type systems Java is more difficult to use (depending on your background)

How can one see if somebody modified any code? Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionary view. Example: SELECT OBJECT_NAME, TO_CHAR(CREATED, 'DD-Mon-RR HH24:MI') CREATE_TIME, TO_CHAR(LAST_DDL_TIME, 'DD-Mon-RR HH24:MI') MOD_TIME, 480

FROM WHERE

STATUS USER_OBJECTS LAST_DDL_TIME > '&CHECK_FROM_DATE';

How can one search PL/SQL code for a string/ key value? The following query is handy if you want to know where a certain table, field or expression is referenced in your PL/SQL source code. SELECT TYPE, NAME, LINE FROM USER_SOURCE WHERE UPPER(TEXT) LIKE '%&KEYWORD%';

How can one keep a history of PL/SQL code changes? One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from Oracle 8.1.7). This way one can easily revert to previous code should someone make any catastrophic changes. Look at this example: CREATE TABLE SOURCE_HIST -- Create history table AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.* FROM USER_SOURCE WHERE 1=2; CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table AFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema name DECLARE BEGIN if DICTIONARY_OBJ_TYPE in ('PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY', 'TYPE') then -- Store old code in SOURCE_HIST table INSERT INTO SOURCE_HIST SELECT sysdate, user_source.* FROM USER_SOURCE WHERE TYPE = DICTIONARY_OBJ_TYPE AND NAME = DICTIONARY_OBJ_NAME; end if; EXCEPTION WHEN OTHERS THEN raise_application_error(-20000, SQLERRM); END; / show errors

How can I protect my PL/SQL source code? PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand and know how to execute such scripts. Just be careful, there is no "decode" command available. The syntax is: wrap iname=myscript.sql oname=xxxx.plb

481

Can one print to the screen from PL/SQL? One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For example: set serveroutput on begin dbms_output.put_line('Look Ma, I can print from PL/SQL!!!'); end; / DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size 200000 If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block.

Can one read/write files from PL/SQL? Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command. Copy this example to get started: DECLARE fileHandler UTL_FILE.FILE_TYPE; BEGIN fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w'); UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n'); UTL_FILE.FCLOSE(fileHandler); EXCEPTION WHEN utl_file.invalid_path THEN raise_application_error(-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.'); END; /

Can one call DDL statements from PL/SQL? One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL). begin EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)'; end; NOTE: The DDL statement in quotes should not be terminated with a semicolon.

Can one use dynamic SQL statements from PL/SQL? Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements (statements created at run-time). Look at these examples. Note that statements are NOT terminated by semicolons: EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)'; 482

-- Using bind variables... sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)'; EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location; -- Returning a cursor... sql_stmt := 'SELECT * FROM emp WHERE empno = :id'; EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id; One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these examples: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END; / More complex DBMS_SQL example using bind variables: CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS v_cursor integer; v_dname char(20); v_rows integer; BEGIN v_cursor := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7); DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no); DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20); v_rows := DBMS_SQL.EXECUTE(v_cursor); loop if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then exit; end if; DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname); DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname); end loop; DBMS_SQL.CLOSE_CURSOR(v_cursor); EXCEPTION when others then DBMS_SQL.CLOSE_CURSOR(v_cursor); raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm); END; /

What is the difference between %TYPE and %ROWTYPE? The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs. %ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor. Example: 483

DECLARE v_EmpRecord

emp%ROWTYPE;

%TYPE is used to declare a field with the same type as that of a specified table's column. Example: DECLARE v_EmpNo

emp.empno%TYPE;

What is the result of comparing NULL with NULL? NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to NULL. Look at this code example to convince yourself. declare a number := NULL; b number := NULL; begin if a=b then dbms_output.put_line('True, NULL = NULL'); elsif a<>b then dbms_output.put_line('False, NULL <> NULL'); else dbms_output.put_line('Undefined NULL is neither = nor <> to NULL'); end if; end;

How does one get the value of a sequence into a PL/SQL variable? As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason) prohibits this: i := sq_sequence.NEXTVAL; However, one can use embedded SQL statements to obtain sequence values: select sq_sequence.NEXTVAL into :i from dual; Thanks to Ronald van Woensel

Can one execute an operating system command from PL/SQL? There is no direct way to execute operating system commands from PL/SQL in Oracle7. However, one can write an external program (using one of the precompiler languages, OCI or Perl with Oracle access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put requests to run commands in the pipe, the listener picks it up and run the requests. Results are passed back on a different database pipe. For an Pro*C example, see chapter 8 of the Oracle Application Developers Guide. In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL makes it executable. Look at this External Procedure example.

How does one loop through tables in PL/SQL? Look at the following nested loop code example. DECLARE CURSOR dept_cur IS SELECT deptno FROM dept ORDER BY deptno; 484

-- Employee cursor all employees for a dept number CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS SELECT ename FROM emp WHERE deptno = v_dept_no; BEGIN FOR dept_rec IN dept_cur LOOP dbms_output.put_line('Employees in Department '|| TO_CHAR(dept_rec.deptno)); FOR emp_rec in emp_cur(dept_rec.deptno) LOOP dbms_output.put_line('...Employee is '||emp_rec.ename); END LOOP; END LOOP; END; /

How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy? Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new transactions, causing ORA-1555 errors. To fix this problem one can easily rewrite code like this: FOR records IN my_cursor LOOP ...do some stuff... COMMIT; END LOOP; ... to ... FOR records IN my_cursor LOOP ...do some stuff... i := i+1; IF mod(i, 10000) THEN -- Commit every 10000 records COMMIT; END IF; END LOOP; If you still get ORA-1555 errors, contact your DBA to increase the rollback segments.

I can SELECT from SQL*Plus but not from PL/SQL. What is wrong? PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence is that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions: • •

Grant direct access on the tables to your user. Do not use roles! GRANT select ON scott.emp TO my_user;

• •

Define your procedures with invoker rights (Oracle 8i and higher); Move all the tables to one user/schema.

485

What is a mutating and constraining table? "Mutating" means "changing". A mutating table is a table that is currently being modified by an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and raises an error since Oracle should not return data that has not yet reached its final state. Another way this error can occur is if the trigger has statements to change the primary, foreign or unique key columns of the table off which it fires. If you must have triggers on tables that have referential constraints, the workaround is to enforce the referential integrity through triggers as well. There are several restrictions in Oracle regarding triggers: • • •

A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the trigger) . A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE delete. Etc.

Can one pass an object/table as an argument to a remote procedure? The only way the same object type can be referenced between two databases is via a database link. Note that it is not enough to just use the same type definitions. Look at this example: -- Database A: receives a PL/SQL table from database B CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS BEGIN -- do something with TabX from database B null; END; / -- Database B: sends a PL/SQL table to database A CREATE OR REPLACE PROCEDURE pcalling IS TabX DBMS_SQL.VARCHAR2S@DBLINK2; BEGIN pcalled@DBLINK2(TabX); END; /

Is it better to put code in triggers or procedures? What is the difference? In earlier releases of Oracle it was better to put as much code as possible in procedures rather than triggers. At that stage procedures executed faster than triggers as triggers had to be re-compiled every time before executed (unless cached). In more recent releases both triggers and procedures are compiled when created (stored p-code) and one can add as much code as one likes in either procedures or triggers.

Is there a PL/SQL Engine in SQL*Plus? No. Unlike Oracle Forms, SQL*Plus does not have an embedded PL/SQL engine. Thus, all your PL/SQL code is sent directly to the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and sent to the database individually.

Is there a limit on the size of a PL/SQL block? Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when you compile the code. You can run the following select statement to query the size of an existing package or procedure: SQL> select * from dba_object_size where name = 'procedure_name';

486

Where can one find more info about PL/SQL? • • • • • • •

487

Oracle FAQ: PL/SQL code examples Oracle FAQ: PL/SQL Books PLNet.org - An open source repository for PL/SQL developers RevealNet PL/SQL Pipeline - A free community for Oracle developers worldwide The PL/SQL Cellar - Free Oracle PL/SQL scripts including a bitwise operations package and message digest algorithms PLSolutions.com - PL/Solutions provides consulting and training services for the Oracle PL/SQL language and PL/Vision The DMOZ PL/SQL Directory

Oracle SQL FAQ What is SQL and where does it come from? Structured Query Language (SQL) is a language that provides an interface to relational database systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL. In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and other database structures. The development of SQL is governed by standards. A major revision to the SQL standard was completed in 1992, called SQL2. SQL3 support object extensions and are (partially?) implemented in Oracle8 and 9.

What are the difference between DDL, DML and DCL commands? DDL is Data Definition Language statements. Some examples: • • • • • • •

CREATE - to create objects in the database ALTER - alters the structure of the database DROP - delete objects from the database TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed COMMENT - add comments to the data dictionary GRANT - gives user's access privileges to database REVOKE - withdraw access privileges given with the GRANT command

DML is Data Manipulation Language statements. Some examples: • • • • • • •

SELECT - retrieve data from the a database INSERT - insert data into a table UPDATE - updates existing data within a table DELETE - deletes all records from a table, the space for the records remain CALL - call a PL/SQL or Java subprogram EXPLAIN PLAN - explain access path to data LOCK TABLE - control concurrency

DCL is Data Control Language statements. Some examples: 488

• • • •

COMMIT - save work done SAVEPOINT - identify a point in a transaction to which you can later roll back ROLLBACK - restore database to original since the last COMMIT SET TRANSACTION - Change transaction options like what rollback segment to use

How does one escape special characters when building SQL queries? The LIKE keyword allows for string searches. The '_' wild card character is used to match exactly one character, '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL. Example: SELECT name FROM emp WHERE id LIKE '%\_%' ESCAPE '\'; Use two quotes for every one displayed. Example: SELECT 'Franks''s Oracle site' FROM DUAL; SELECT 'A ''quoted'' word.' FROM DUAL; SELECT 'A ''''double quoted'''' word.' FROM DUAL;

How does one eliminate duplicates rows from a table? Choose one of the following queries to identify or remove duplicate rows from a table leaving only unique records in the table: Method 1: SQL> DELETE FROM table_name A WHERE ROWID > ( 2 SELECT min(rowid) FROM table_name B 3 WHERE A.key_values = B.key_values); Method 2: SQL> create table table_name2 as select distinct * from table_name1; SQL> drop table_name1; SQL> rename table_name2 to table_name1; SQL> -- Remember to recreate all indexes, constraints, triggers, etc on table... Method 3: (thanks to Dennis Gurnick) SQL> delete from my_table t1 SQL> where exists (select 'x' from my_table t2 SQL> where t2.key_value1 = t1.key_value1 SQL> and t2.key_value2 = t1.key_value2 SQL> and t2.rowid > t1.rowid); Note: One can eliminate N^2 unnecessary operations by creating an index on the joined fields in the inner loop (no need to loop through the entire table on each pass by a record). This will speed-up the deletion process. Note 2: If you are comparing NOT-NULL columns, use the NVL function. Remember that NULL is not equal to NULL. This should not be a problem as all key columns should be NOT NULL by definition.

How does one generate primary key values for a table? Create your table with a NOT NULL column (say SEQNO). This column can now be populated with unique values: SQL> UPDATE table_name SET seqno = ROWNUM; or use a sequences generator: 489

SQL> CREATE SEQUENCE sequence_name START WITH 1 INCREMENT BY 1; SQL> UPDATE table_name SET seqno = sequence_name.NEXTVAL; Finally, create a unique index on this column.

How does one get the time difference between two date columns? Look at this example query: select floor(((date1-date2)*24*60*60)/3600) || ' HOURS ' || floor((((date1-date2)*24*60*60) floor(((date1-date2)*24*60*60)/3600)*3600)/60) || ' MINUTES ' || round((((date1-date2)*24*60*60) floor(((date1-date2)*24*60*60)/3600)*3600 (floor((((date1-date2)*24*60*60) floor(((date1-date2)*24*60*60)/3600)*3600)/60)*60))) || ' SECS ' time_difference from ... If you don't want to go through the floor and ceiling math, try this method (contributed by Erik Wile): select to_char(to_date('00:00:00','HH24:MI:SS') + (date1 - date2), 'HH24:MI:SS') time_difference from ... Note that this query only uses the time portion of the date and ignores the date itself. It will thus never return a value bigger than 23:59:59.

How does one add a day/hour/minute/second to a date value? The SYSDATE pseudo-column shows the current system date and time. Adding 1 to SYSDATE will advance the date by 1 day. Use fractions to add hours, minutes or seconds to the date. Look at these examples: SQL> select sysdate, sysdate+1/24, sysdate +1/1440, sysdate + 1/86400 from dual; SYSDATE SYSDATE+1/24 SYSDATE+1/1440 SYSDATE+1/86400 -------------------- -------------------- --------------------------------------03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12 03-Jul-2002 08:32:13 The following format is frequently used with Oracle Replication: select sysdate NOW, sysdate+30/(24*60*60) NOW_PLUS_30_SECS from dual; NOW NOW_PLUS_30_SECS -------------------- -------------------03-JUL-2002 16:47:23 03-JUL-2002 16:47:53

How does one count different data values in a column? Use this simple query to count the number of data values in a column: select my_table_column, count(*) from my_table group by my_table_column; A more sophisticated example... select dept, sum( decode(sex,'M',1,0)) MALE, 490

from group

sum( decode(sex,'F',1,0)) FEMALE, count(decode(sex,'M',1,'F',1)) TOTAL my_emp_table by dept;

How does one count/sum RANGES of data values in a column? A value x will be between values y and z if GREATEST(x, y) = LEAST(x, z). Look at this example: select f2, sum(decode(greatest(f1,59), least(f1,100), 1, 0)) "Range 60-100", sum(decode(greatest(f1,30), least(f1, 59), 1, 0)) "Range 30-59", sum(decode(greatest(f1, 0), least(f1, 29), 1, 0)) "Range 00-29" from my_table group by f2; For equal size ranges it might be easier to calculate it with DECODE(TRUNC(value/range), 0, rate_0, 1, rate_1, ...). Eg. select ename "Name", sal "Salary", decode( trunc(f2/1000, 0), 0, 0.0, 1, 0.1, 2, 0.2, 3, 0.31) "Tax rate" from my_table;

Can one retrieve only the Nth row from a table? Shaik Khaleel provided this solution to select the Nth row from a table: SELECT * FROM ( SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 ) WHERE RN = 100; Note: Note: In this first it select only one more than the required row, then it selects the required one. Its far better than using MINUS operation. Ravi Pachalla

provided this solution:

SELECT f1 FROM t1 WHERE rowid = ( SELECT rowid FROM t1 WHERE rownum <= 10 MINUS SELECT rowid FROM t1 WHERE rownum < 10); Alternatively... SELECT * FROM emp WHERE rownum=1 AND rowid NOT IN (SELECT rowid FROM emp WHERE rownum < 10); Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even help in the odd situation.

Can one retrieve only rows X to Y from a table?

Shaik Khaleel provided this solution to the problem: SELECT * FROM ( SELECT ENAME,ROWNUM RN FROM EMP WHERE ROWNUM < 101 ) WHERE RN between 91 and 100 ; Note: the 101 is just one greater than the maximum row of the required rows (means x= 90, y=100, so the inner values is y+1).

491

Another solution is to use the MINUS operation. For example, to display rows 5 to 7, construct a query like this: SELECT * FROM tableX WHERE rowid in ( SELECT rowid FROM tableX WHERE rownum <= 7 MINUS SELECT rowid FROM tableX WHERE rownum < 5); Please note, there is no explicit row order in a relational database. However, this query is quite fun and may even help in the odd situation.

How does one select EVERY Nth row from a table? One can easily select all even, odd, or Nth rows from a table using SQL queries like this: Method 1: Using a subquery SELECT * FROM emp WHERE (ROWID,0) IN (SELECT ROWID, MOD(ROWNUM,4) FROM emp); Method 2: Use dynamic views (available from Oracle7.2): SELECT * FROM ( SELECT rownum rn, empno, ename FROM emp ) temp WHERE MOD(temp.ROWNUM,4) = 0; Please note, there is no explicit row order in a relational database. However, these queries are quite fun and may even help in the odd situation.

How does one select the TOP N rows from a table? Form Oracle8i one can have an inner-query with an ORDER BY clause. Look at this example: SELECT * FROM (SELECT * FROM my_table ORDER BY col_name_1 DESC) WHERE ROWNUM < 10; Use this workaround with prior releases: SELECT * FROM my_table a WHERE 10 >= (SELECT COUNT(DISTINCT maxcol) FROM my_table b WHERE b.maxcol >= a.maxcol) ORDER BY maxcol DESC;

How does one code a tree-structured query? Tree-structured queries are definitely non-relational (enough to kill Codd and make him roll in his grave). Also, this feature is not often found in other database offerings. The SCOTT/TIGER database schema contains a table EMP with a self-referencing relation (EMPNO and MGR columns). This table is perfect for tesing and demonstrating tree-structured queries as the MGR column contains the employee number of the "current" employee's boss. The LEVEL pseudo-column is an indication of how deep in the tree one is. Oracle can handle queries with a depth of up to 255 levels. Look at this example: 492

select LEVEL, EMPNO, ENAME, MGR from EMP connect by prior EMPNO = MGR start with MGR is NULL; One can produce an indented report by using the level number to substring or lpad() a series of spaces, and concatenate that to the string. Look at this example: select lpad(' ', LEVEL * 2) || ENAME ........ One uses the "start with" clause to specify the start of the tree. More than one record can match the starting condition. One disadvantage of having a "connect by prior" clause is that you cannot perform a join to other tables. The "connect by prior" clause is rarely implemented in the other database offerings. Trying to do this programmatically is difficult as one has to do the top level query first, then, for each of the records open a cursor to look for child nodes. One way of working around this is to use PL/SQL, open the driving cursor with the "connect by prior" statement, and the select matching records from other tables on a row-by-row basis, inserting the results into a temporary table for later retrieval.

How does one code a matrix report in SQL? Look at this example query with sample output: SELECT * FROM (SELECT job, sum(decode(deptno,10,sal)) sum(decode(deptno,20,sal)) sum(decode(deptno,30,sal)) sum(decode(deptno,40,sal)) FROM scott.emp GROUP BY job) ORDER BY 1;

DEPT10, DEPT20, DEPT30, DEPT40

JOB DEPT10 DEPT20 DEPT30 DEPT40 --------- ---------- ---------- ---------- ---------ANALYST 6000 CLERK 1300 1900 950 MANAGER 2450 2975 2850 PRESIDENT 5000 SALESMAN 5600

How does one implement IF-THEN-ELSE in a select statement? The Oracle decode function acts like a procedural statement inside an SQL statement to return different values or columns based on the values of other columns in the select statement. Some examples: select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown') from employees; select a, b, decode( abs(a-b), a-b, 'a > b', 0, 'a = b', 'a < b') from

tableX;

select decode( GREATEST(A,B), A, 'A is greater OR EQUAL than B', 'B is greater than A')... select decode( GREATEST(A,B), 493

THAN B'),

A, decode(A, B, 'A NOT GREATER THAN B', 'A GREATER

'A NOT GREATER THAN B')... Note: The decode function is not ANSI SQL and is rarely implemented in other RDBMS offerings. It is one of the good things about Oracle, but use it sparingly if portability is required. From Oracle 8i one can also use CASE statements in SQL. Look at this example: SELECT ename, CASE WHEN sal>1000 THEN 'Over paid' ELSE 'Under paid' END FROM emp;

How can one dump/ examine the exact content of a database column? SELECT DUMP(col1) FROM tab1 WHERE cond1 = val1;

DUMP(COL1) ------------------------------------Typ=96 Len=4: 65,66,67,32 For this example the type is 96, indicating CHAR, and the last byte in the column is 32, which is the ASCII code for a space. This tells us that this column is blank-padded.

Can one drop a column from a table?

From Oracle8i one can DROP a column from a table. Look at this sample script, demonstrating the ALTER TABLE table_name DROP COLUMN column_name; command. Other workarounds: 1. SQL> update t1 set column_to_drop = NULL; SQL> rename t1 to t1_base; SQL> create view t1 as select <specific columns> from t1_base; 2. SQL> create table t2 as select <specific columns> from t1; SQL> drop table t1; SQL> rename t2 to t1;

Can one rename a column in a table? No, this is listed as Enhancement Request 163519. Some workarounds: 1. -- Use a view with correct column names... rename t1 to t1_base; create view t1 as select * from t1_base; 2. -- Recreate the table with correct column names... create table t2 as select * from t1; drop table t1; rename t2 to t1; 3. -- Add a column with a new name and drop an old column... alter table t1 add ( newcolame datatype ); update t1 set newcolname=oldcolname; alter table t1 drop column oldcolname;

How can I change my Oracle password? Issue the following SQL command: ALTER USER <username> IDENTIFIED BY / 494

From Oracle8 you can just type "password" from SQL*Plus, or if you need to change another user's password, type "password user_name".

How does one find the next value of a sequence? Perform an "ALTER SEQUENCE ... NOCACHE" to unload the unused cached sequence numbers from the Oracle library cache. This way, no cached numbers will be lost. If you then select from the USER_SEQUENCES dictionary view, you will see the correct high water mark value that would be returned for the next NEXTVALL call. Afterwards, perform an "ALTER SEQUENCE ... CACHE" to restore caching. You can use the above technique to prevent sequence number loss before a SHUTDOWN ABORT, or any other operation that would cause gaps in sequence values.

Workaround for snapshots on tables with LONG columns You can use the SQL*Plus COPY command instead of snapshots if you need to copy LONG and LONG RAW variables from one location to another. Eg: COPY TO SCOTT/TIGER@REMOTE CREATE IMAGE_TABLE USING SELECT IMAGE_NO, IMAGE FROM IMAGES; Note: If you run Oracle8, convert your LONGs to LOBs, as it can be replicated.

Where can one get more info about SQL? • • • •

495

The SQL FAQ Introduction to Structured Query Language SQL Tutorial Tina London's SQL Guide

VB 6.0 .. revisited 1.

Dim x, y as integer. What is x and y data type?

X as variant and y as integer. 2.

What is the size of the variant data type?

The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length), and can store any character text. 3.

What is the return type of Instr and Strcmp?

Instr – integer (Numeric position) Strcmp - integer ( if both the string are equal they result = 0) Strcmp (Str1, Str2, Comparetype) Comparing mode = 0 – Binary Comparing 1 – Textual Comparing 4. What is the max size allowed for Msgbox Prompt and Input Box? 1024 5.

Max label caption length. –

2,048 6.

Max Text box length –

32,000 7.

Max Control Names length –

255. 8.

Extension in Visual Basic

Frm, bas, cls, res, vbx, ocx, frx, vbp, exe 496

9.

What is frx?

When some controls like grid and third party control placed in our application then it will create frx in run time. 10.

Name some date function

Dateadd(), Datediff(), Datepart(), Cdate() 11.

what will be the result for

15/4 = 3.75 and 15\4 = 3 12.

What is keyword used to compare to objects?

ISOperator – Returns Boolean. 13.

How many procedures are in VB?

2. function and sub procedures (Ask what is the diff. Between them?) Function Will return value but a sub procedure wont return values…

14. Where will we give the option explicit keyword and for what? In the general declarations section. To trap undeclared variables. 15.

What is Friend Variable?

Scope sharable between projects. 16.

What is binding? What are types of binding?

Assigning variable with defined memory space. Late Binding - Memory size is allotted in later stage. Ex:- Dim x as object Early Binding - Memory size is allotted while declaring itself. New Key word is important. Ex:- Dim x as New Object 17. What is the difference between Property Get, Set and Let. Set – Value is assigned to ActiveX Object from the form. Let – Value is retried to ActiveX Object from the form. 497

Get- Assigns the value of an expression to a variable or property. 18.

What is Mask Edit and why it is used?

Control. Restricted data input as well as formatted data output. 19.

Drag and Drop state numbers and functions.

State 0 – Source control is being dragged with the range of a target. 1 – Out of the range of a target. 2 – One positon in the target to another. 20.

What are the type of validation available in VB?

Field, Form 21. With in the form we want to check all the text box control are typed or not? How? For each currentcontrol in controls if typeof currentcontrol is TextBox then end if next 22.

What is the result of Null * Any value = 0 (Zero).

23. What is control array and How many we can have it with in the form? Group of control share the same name. Max 32, 767. 24. What is the default model of the form? And what is it number? VbModaless – 0 (Zero) – We can able to place another window above this form. 25. Suppose from form1 to form2 object property settings will arise to ? Invalid procedure call or argument (Run time error – 5) 26. What is the diff between the Std and Class Module? Std Global with in the project. Cls Global through out the all project only thing is we want to set the type lib. Class Modules can be Instantiated. 498

27.

Different type of Instantiation?

Private – Only for the Specific Module. Public not creatable – Private & Public Multi Use - Variable we have to declare. Single Use – Not possible through dll. Global Multiuse – Have variable not Required to Declare. Global Single Use - Only for exe. 28. How to declare Dll Procedure? Declare function "" lib "" Alias "" (Arg, …..) as Return type. 1.

What is MDI form? MDI Styles?

We can have only one MDI form Document Interface. This form set the Child property of the forms inside this MDI. Style availables 1. VbCascade

for a project. Multiple type is VBModal. We have forms to True to place 2. VbTitle Horizontal

2.

How many images can be placed in the image list ?

64 3.

What is Inprocess and Out of Process?

Inprocess – It will run with in the memory. ( Local Machine). Out of Process – It will run out of the memory Normally in the server side. 4.

Diff type of Datatypes?

LOB (Large Object Data type). CLOB (Stores Character Objects). BLOB ( Store Binary Objects such as Graphic, Video Chips and Sound files). BFILE(Store file pointers to LOB It may Contain filename for photo’s store on CD_ROM). 5.

What is Zorder Method?

Object.Zorder = 1 or 0 Place a Specified mdiform form or control at the front or back of the z-order with n its Graphical Level. 6. What is diff between the Generic Variable and Specific Variable? Generic Variable: Create Object Ex:-Ole-Automation . No need refer the object library. Specific Variable: 499

Binding Procedure Early and Late Binding ( Can be Remove from the Memory). 7. What are properties available in Clip Board? No Properties Available. Only the methods they are SetText, GetText, Setdata(), Getformat(), Clear. 8.

What is Dll?

Libraries of procedure external to the application but can be called from the application. 9. What is Tabstrip control? What is the starting Index value? How to locate it? It is tab control to place our controls with in the form in multiple sheets. Index starts with 1. And to identify If Tabstrip1.SelectedItem.Index = 1 Then ….. End if 10.

Why we use Treeview Control?

To list the hierarchial list of the node objects. Such of files and Directories. 11.

Why we need OLE-Automation?Advantages?

Enables an application to exposes objects and methods to other Applications. No need to reserve memory. No need to write functions. Object library that simplify programming tasks. i.e., No need to Object library. (OLB, TLB). 12. What is the diff between the Create Object and Get object? Create Object - To create an instance of an object. Get Object – To get the reference to an existing object. 13. Have you create Properties and Methods for your own Controls? Properties – Public variable of a Class Method – Public procedure of a class 14.

What is Collection Objects?

Similarly to arrays but is preferred over an array because of the following reasons. 1. A collection objects uses less Memory than an array. 500

2. It provides methods to add and delete members. 3. It does not required reason statement when objects are added or deleted. 4. It does not have boundary limitations. 15.

What is Static Variable?

Its Scope will be available through out the life time. 16.

Private Dim x as integer.

Private cannot be used in front of DIM. 17.

What is Implicit?

Instance of specific copy of a class with its own settings for the properties defined in that class. Note: The implicity defined variable is never equal to nothing. 18.

What are the scope of the class?

Public , private, Friend 19. Can we able to set Instancing properties like Singleuse, GlobalSingleuse to ActiveXDll? No. 20. In project properties if we set Unattended what is it mean? This cannot have user interface. This can be used for the COM creation. 21.

What are the Style Properties of Combo Box?

Simple, Dropdown list – We can type and select. Dropdown Combo – Only Drop Down. 22.

What are the Style properties of List Box?

Simple –Single Select , Extended. – Multiple Select. 23.

What are the different types of Dialog Box?

Predefined, Custom, User Defined. 24.

What is Parser Bug?

It is difficult to use database objects declared in a module from within a form. 25.

What is the Dll required for running the VB?

Vbrun300.dll 501

26.

Can We create CGI scripts in VB?

Yes. 27.

How to change the Mouse Pointer?

Screen.MousePointer = VBHourGlass/VBNormal. 28.

How to check the condition in Msgbox?

If(Msgbox("Do you want to delete this Record",VbYesNo)=VbYes)Then End if VB Questions (Client Server) 1. What is difference between datagrid and flexgrid? Datagrid – Editable. Flexigrid – Non-Editable. (Generally used for Read only purpose.) 2.

What is ADO? What are its objects ?

ActiveX Data Object. ADO can access data from both flat files as well as the databases. I.e., It is encapsulation of DAO, RDO, and OLE that is why we call it as OLE-DB Technology. Objects are Connection, Record Set, Command, Parameter, field, Error, Property. 3.

What is Dataware Control?

Any control bound to Data Control. Ex:- Textbox, Check Box, Picture Box, Image Control, Label, List box, Combo Box, DB Combo, 4.

What are two validate with Data Control?

Data_Validate, Data_Error. 5.

Record set types and Number available in VB?

3. 1- Dynaset, 0 – Table, 2 – Snap Shot. 6. Referential Integrity (Take care By jet database Engine). Cascade Delete, Cascade Update – is done setting property of Attributes. DbRelationDeleteCascade, DbRelationUpdateCascade. 7.

Basic?

What are the locks available in Visual

Locking is the process by which a DBMS restricts access to a row in a multi-user environment 502

1. 2. 3. 4.

4 types of locks. They are Batch Optimistic Optimistic Pessimistic ReadOnly

Operations in a relational database act on a complete set of rows. The set of rows returned by a SELECT statement consists of all the rows that satisfy the conditions in the WHERE clause of the statement. This complete set of rows returned by the statement is known as the result set. Applications, especially those that are interactive and online, cannot always work effectively with the entire result set as a unit. These applications need a mechanism to work with one row or a small block of rows at a time. Cursors are an extension to result sets that provide that mechanism.

Cursor or lock type Advantages Disadvantages AdOpenForwardOnly (Default) · Low resource requirements · Cannot scroll backward · No data concurrency AdOpenStatic · Scrollable (Wont detect changes made at the same time by another application) · No data concurrency AdOpenKeyset · Some data concurrency · Scrollable Higher resource requirements · Not available in disconnected scenario AdOpenDynamic · High data concurrency · Scrollable Highest resource requirements · Not available in disconnected scenario AdLockReadOnly · Low resource requirements · Highly scalable · Data not updatable through cursor AdLockBatchOptimistic · Batch updates · Allows disconnected scenarios · Other users able to access data · Data can be changed by multiple users at once AdLockPessimistic · Data cannot be changed by other users while locked · Prevents other users from accessing data while locked AdLockOptimistic · Other users able to access data Data can be changed by multiple users at once 8.What is the diff between RDO and ADO? RDO is Hierarchy model where as ADO is Object model. ADO can access data from both flat files as well as the data bases. I.e., It is encapsulation of DAO, RDO , OLE that is why we call it as OLE-DB Technology. 7. How can we call Stored procedure of Back End in RDO and ADO ? In RDO – We can call using RDO Query Objects. 503

· ·

·

In ADO – We can call using Command Objects. 8. What is the different between Microsoft ODBC Driver and Oracle OBDC Driver? Microsoft ODBC driver will support all the methods and properties of Visual Basic. Where as the Oracle not. 9. What are the Technologies for Accessing Database from Visual Basic? DAO, Data Control, RDO, ODBCDIRECT, ADO, ODBC API , 0040. 10.

Calling Stored Procedures in VB?

1. Calling Simply the Procedure with out Arguments "Call ProcedureName}" 2. If it is with Arguments Means then Declare the Query Def qy Set Qy as New Query def Qy.SQL = "{Call ProcedureName(?,?,?)}" qy(0)=val(Txt1.Text) qy(1)=val(Txt2.Text) qy(2)=val(Txt3.Text) Set Rs = Qy.OpenresultSet Txt(1)=Rs.RdoColumns(0) 11.

What is MAPI ?

Messaging Application programing Interface. 12.

Different type of Passing Value?

By value, By ref, Optional, Param Array. Note:- Optional keyword cannot be used while declaring arguments for a function using param array. 13.

What are the different types of error?

Syntax Errors, Runtime , Logic. 14. What is Seek Method which type of record set is available this? Only in DbOpenTables. Syntax: rs.index = "empno" rs.seek "=" , 10 If with our setting the rs.index then run time error will occur. 15. 504

What is Centralization Error Handling?

Writing funciton and calling it when error occurs. 16.

Handling Error in Calling chain.

This will call the top most error where the error is handled. 17. To connect the Data Control with Back end What are all the properties to be set? Data source Name, Record Source Name 18.

How to trap Data Base Error?

Dim x as RDOError X(0).Des X(1).Number 19.

What is view Port?

The area under which the container provides the view of the ActiveX Document is known as a view port. 20.

What methods are used for DBGrid in unbound mode?

AddData, EditData, Readdata, WriteData. 21. How to increase the Date corresponding with month,date,year? DateSerial(year(Now),Month(Now)+1,1) Hour, min, sec, month, year, DateSerial, dateadd, datediff, weekday, datevalue, timeserial,timevalue. 22.

Setting the Cursors.

Default Cursor – 0 ODBC Cursor (Client side) – 1 ServerSide Cursors (More Network traffic) - 2 23.

Cursor management

Client Batch – Batch up the Multiple SQL Statements in a single string and Send them to the Server at one time. 24.

What are the record set types?

RdOpenFowardOnly 0 (Default used only for the read only purpose) RdOpenStatic 1 RdOpenDynamic 2 RdOpenKeySet 3 (Normally used for the live project) 505

25.

Diff types of Lock Types?

RdConcurReadOnly 0 (Default) RdConcurLock 1 (Pessimistic Locking) RdConcurRowver 2 (Optimistic Lociking) RdConcurValues 3 RdConcurBatch 4 26.

What the RDO Methods and Events?

Methods Events Begin Trans Validate Commit Trans Reposition Rollback Trans Error Cancel Query Complied Refresh Update Controls Update row 27.

What is Static Cursor?

In ADO Snap Shot is called so. 28.

What is Mixed Cursors?

Static + Keyset 29.

What is FireHouse Cursors?

Forward Only Some time Updateable 30.

What is DBSqlPassThrough?

It will By Passing the Jet Query Processor. 31.

What is DBFailError?

Rolls Back updates if any errors Occurs. 32.

DSN Less Connection?

"Server=Oracle; Driver={Microsoft ODBC for Oracle};" 33.

What is RdExecDirect?

Bypasses the Creation of a stored procedure to execute the query. Does not apply to Oracle. 34.

RdoParameter Object RdoParameterConstant

Direction RdparamInput RdparamInputOutput RdParamOutput Name Type Value 506

. *********************************************************************** ****************

ASP – 1. <SCRIPT LANGUAGE="VBScript" RUNAT=Server> a = 1 <SCRIPT LANGUAGE="VBScript"> a = 2 <% Response.Write a %> In the sample code shown above, what will be written to the screen? A. 1 B. 2 C. 1, 2 D. 1&2 E. Nothing. 2. <% Set Application("Thing") = Server.CreateObject("THINGDOER.thingy") %> The above code appears in the global.asa file. What would it accomplish? A. It would create a "Thing" object and place it in Contents Collection of the Application object. B. It would create a "Thing" object and place it in StaticObjects Collection of the Application object. C. It would create a "Thing" object and place it in the Application.Buffer Collection Of the Application object. D. It would create an application-level variable named "Thing" with the value of the object property "THINGDOER.thingy". E. It would fail to create a "Thing" object because the code requires the Application.Lock and Application.Unlock methods. 3. <% iPos = Instr("Hello World","r") %> Referring to the above, what is the value of iPos? A. 0 B. 1 C. 2 507

D. 8 E. 9 4. <% varType = rsTest("field1").type %> In the database table, if the datatype for field1 (shown above) is Number, what is the value of varType? A. B. C. D. E.

The field value. A string description. The field name. NULL. An enumerator.

5. What is the program ID (ProgID) for ActiveX Data Objects in 2-tier and 3-tier database applications? A. B. C. D. E.

ADO RDODB ADODB RDS OLEDB

6. Which choice is NOT an ADO collection? A. B. C. D. E.

Properties Records Fields Errors Parameters

7. Which will NOT set the scope of an Active Server Component? A. Setting the [component name].scope property. B. Using the Server.CreateObject method. C. Placing it in the Session or Application OnStart event handler. D. Instantiating the component in the global.asa file. E. Using the tag. 8. How to handle Error in ASP A. B. C. D.

Using Using Using Using

On On On On

Error Error Error Error

Goto <ErrorPart> Resume Resume Next Goto 0

9. <% intA = 3 sStrA = "Hello World" sStrB = "Hello World" + intA Response.Write sStrB %> What would be the result of the above code? 508

A. B. C. D. E.

Type mismatch error "Hello World, Hello World, Hello World" 0 "Hello World 3" "Hello World"

10. What happens when a client submits a form which changes the value of an Application variable? A. Client actions cannot change Application variables. B. The change is not visible to any client until the application is stopped and started. C. The change is only visible to future requests made by that client during their current session. D. The change is visible to all clients, but only after they complete their current sessions and begin a new session. E. The change is visible to all clients immediately after the form is processed by the server. 11. ADO is an object model for accessing which of the following? A. B. C. D. E.

Relational data via Jet. Local or SQL data via Jet. Relational data via ODBC. Non-relational data via DSN-less ODBC. All types of data via OLE DB.

12. Which of the following are Server Object methods ( Choose Two) A. HTMLEncode,MapPath B. URLEncode,ScriptTimeout C. URLEncode,CreateObject D. ScriptTimeout,Abandon 13. Following is the code Server.MapPath (".") consider the path is C:\Inetpub\WWWRoot\MAT\Default.asp. What will be the output A. B. C. D.

C:\InetPUb C:\InetPUb\WWWroot C:\InetPUb\wwwroot\MAT Error

14. ClientCertificate is a collection of A. Server B. Response C. Request D. ObjectContext 509

15. IsClientConnected is a property of A. B. C. D.

Server Response Request Sesssion

16) What happens to a HTML page? The browser makes a HTTP request; the server gives a HTTP response to the browser and the browser converts into a HTML page. 17) What happens to ASP pages? The browser makes a HTTP request; the server does the processing and gives a HTML response to the browser. 18) What are the Web Servers supporting ASP? · Internet Information Server (IIS) on Windows NT · Personal Web Server (PWS) on Windows 95 · Peer Web Services on Windows NT 19) Explain the POST & GET Method or Explain the difference between them. POST METHOD: The POST method generates a FORM collection, which is sent as a HTTP request body. All the values typed in the form will be stored in the FORM collection. GET METHOD: The GET method sends information by appending it to the URL (with a question mark) and stored as A Querystring collection. The Querystring collection is passed to the server as name/value pair. The length of the URL should be less than 255 characters. 20) What is the command to display characters to the HTML page? Response.Write 21) What is a variable? Variable is a memory location through which the actual values are stored/retrieved. Its value can be changed. 22) What are LOCAL and GLOBAL variables? Local variables lifetime ends when the Procedure ends. Global variables lifetime begins at the start of the script and ends at the end of the script and it can be used by any procedure within the script. Declaring a 510

variable by using the keyword PRIVATE makes the variable global within the script, but if declared using PUBLIC, then all scripts can refer the variable. 23) Naming constraints for a variable. It can be up to 255 characters Must start with an alphabet Must not contain an embedded period or full-stop 24) VBScript/ JavaScript is case- insensitive JavaScript is case sensitive 25) What are the special sub-types in VBScript? EMPTY: has no value NULL: Value does not exist (conjunction with database) OBJECT: 26) What is the Order of precedence for LOGICAL Operators. NOT, AND, OR, XOR, EQV, IMP 27) What is Response Object? It controls the information sent to the user. The various methods are: Response.Write – Sends information directly to a browser Response.Redirect – Directs a user to a URL other than the requested URL Response.ContentType – Controls the type of content sent Response.Cookies – Sets cookie values Response.Buffer – To Buffer information 28) How will you set the values for cookies? <% Response.Cookies("variable name ")="value" %>. 29) What is the function of Buffer in Response Object? Buffer controls the HTML output stream manually. 30) What are the methods by which output stream is controlled? · Flush – sends previous buffered output to the client immediately, but continues processing the script. · Clear – erases any already-buffered HTML. · End – causes the server to stop processing the script. 31) What are the properties used to control the expiration of the page? 511

· Expires – specifies the number of minutes before a page cached on a browser expires. · ExpiresAbsolute – sets the date and time at which a page cached on a browser expires. 32) What are the methods in Application Object? · Lock – prevents clients from modifying the variables stored in the Application object. · Unlock – removes the lock from variables stored in the Application object. 33) What are the event handlers of Application Object? · Application_OnStart – This event will be fired when the first visitor hits the page. · Application_OnEnd – This event runs when the server is stopped. 34) What is Session Object? It stores information about a User’s session. Gives a notification when a user session begins or ends. 35) What is a session? A user accessing an application is known as a session. 36) What are the collections of Session Object? · Contents collection – contains all the variables established for a session without using the tag. · Static collection – contains all the objects created with the tag within session scope. 37) What are the properties of Session Object? · SessionID – returns the session identification number for each user. · Timeout – sets the timeout period assigned to the Session object for any application, in minutes. · CodePage – determines the code page that will be used to display content. · LCID – a locale identifier, which determines time zone and language, rules for the system. 38) What are the methods in Session Object? The Session Object has only one method, which is Abandon. It destroys all the objects stored in a Session Object and releases the server resources they occupied. 39) Name some of the ASP components? 512

· Ad Rotator component – a way to manage advertisements on the web site. · Content Linker component – a technique to direct users through a set of pages on a web site by creating a list of URLs and description of the next and previous pages. · Browser Capabilities component – allows to customize the page to the ability of the browser viewing it. · Database Access component – allows to access data from the database 40) What are Scripting Objects? Objects that can enhance the application are known as the Scripting Objects. 41) What are the ASP Scripting Objects? The Dictionary object, the FileSystemObject object, TextStream object. 42) What is a Dictionary object? It lets you store and retrieve information in a flexible data structure. Each value or information stored in a Dictionary is associated with a key through which the information can be retrieved. 43) What is a FileSystemObject object? It provides access to the physical file system of the web server. It gets and manipulates information about all drives in a server, folders and sub-folders on a drive and files inside a folder. 44) What is Server-Side includes? It provides extra information by which it makes the site easier to manage. It can include text files using the #include statement, retrieve the size and last modification date of a file, defines how variables and error messages are displayed and inserts the values of HTTP variables in the page sent back to the browser. ASP – Grade C 1. What is the result of using Option Explicit? A. This applies only to Visual Basic, not VBScript. B. All variables must be dimensioned before use. C. All variables are dimensioned at run-time. D. Forces all <SELECT> controls to have a SELECTED option. E. Requires all variables be cast as specific DataTypes. 513

2. What should be used in order to determine if the cookie "FavoriteFlavors" in the request object contains more than one entry? A. B. C. D. E.

Request.Cookies("FavoriteFlavors").HasItems Request.Cookies("FavoriteFlavors").Collection.Count Request.Cookies("FavoriteFlavors").Dictionary Request.Cookies("FavoriteFlavors").HasKeys Request.Cookies("FavoriteFlavors").Count

3. When is the Session_OnStart event fired? A. Upon every request from an application by a client for an .asp document. B. Upon the first request from an application by a client for any file in the application. C. Upon the first request for an .asp document from an application by a client. D. Upon the first request for the global.asa file, in which the event handler is located. E. Upon the first request for an. html or .asp document from an application by client 4. What does Internet Information Server (IIS) assume to be the default language for Active Server Pages? A. B. C. D. E.

Jscript JavaScript JAVA VBScript ECMAScript

5. What should the developer use in order to have an Active Server Page (ASP) invokes a stored procedure on a SQL Server database? A. B. C. D. E.

ADO RDO RDS OLEDB None of the above.

6. ‘onStart' and 'onEnd' are events of what object(s)? A. B. C. D. E.

Application only. Session only. Server only. Application and Session only. Application, Session, and Server.

7. What must be installed on an IIS4 machine to use the CDONTS e-mail server object? A. FTP service B. SMTP service 514

C. IIS administrator D. Exchange Server E. IPX/SPX protocol 8. Which line of code would instantiate the Browser Capabilities component? A. objBrowser = Server.CreateObject("MSWC.BrowserType") B. Set objBrowser = Server.CreateObject("MSWC.BrowserType") C. var objBrowser = Server.CreateObject("MSWC.BrowserType") D. var objBrowser = CreateObject("MSWC.BrowserType") E. var objBrowser = Server.CreateObject("BrowserType") 9. What is the Default ScriptTimeOut for Server Object? A. B. C. D.

20 30 60 90

Sec Sec Sec Sec

10. How many Max Cookies can we create in Server? A. B. C. D.

10 20 30 40

11. How Many Types of Cookies A. 3 B. 2 C. 1 D. 4 12.What is ASP (Active Server Pages)? ASP is a server side-scripting environment for building dynamic and interactive web pages. Since the scripts run on the server side, the web server does all the processing. 13. What are the advantages of using ASP? · Minimizes network traffic by limiting the need for the browser and server to talk to each other · Makes for quicker loading time since HTML pages are only downloaded · Allows to run programs in languages that are not supported by the browser · Can provide the client with data that does not reside on the client’s machine · Provides improved security measures since the script cannot be viewed by the browser 515

14. What is HTML(Hypertext Markup Language)? It’s a method by which web pages can be built and generally used for formatting and linking text. 15. What are the types of HTML? · Static HTML – Browser uses HTTP to request HTML file from the Web Server · Dynamic HTML – Browser uses HTTP to request an executable application rather than a Static HTML file 16. What is the difference between ASP and HTML? Or Why ASP is better than HTML? · ASP executes code on the server side whereas the browser interprets HTML. · ASP can use any scripting languages · Gets feedback from the user and return information to the user · Create pages that will be customized to display only things that will be of interest to a particular user · Can edit contents of a web page by updating a text file or a database rather than the HTML code itself 17. What is a Web Server? It’s a Computer that provides Web services on the Internet or on a local Intranet. It is designed to locate, address and send out simple HTML pages to all other users who access these pages. 18. What is IIS? IIS is a Web Server that provides Web services, not only for web pages but also for ftp sites and video and audio services. It integrates with the database facilities of SQL Server. 19. What do you need to run ASP? A browser and a Web server. 20. What is a Scripting Language? It permits to create more interactive Web Pages. Validation, formatting of web pages can be done. VBScript, JavaScript are some examples. 21. Which is the default Scripting Language of ASP (server-side)? VBScript 22. Which is the default Scripting Language on the client side? 516

JavaScript 23. What is Global.asa file? It is text file that contains details about an ASP application, such as when it should begin and end. 24. Which is the default Data types in VBScript? Variant is the default data type in VBScript, which can store a value of any type. 25. What is the Order of precedence for ARITHMETIC Operators. ^, -(negation), *or /, \, mod, + or – 26. Where will you code OPTION EXPLICIT in an ASP application? WHY? It should be the first statement before the tag because ASP script is processed before the HTML statements. 27. What are Constants? How will you declare a constant? Constants have values that do not change during the execution of the program. It can be declared using the term CONST. (e.g.) Const pi = 3.143 28. What are ARRAYS? Arrays are variables that store items of similar information.DIM ARRAY1(4) (declares an array with the name array1 with 5 elements) 29. Arrays can be resized by using the keyword REDIM 30. What is the maximum size of an array? Up to 60 dimensions. ASP OBJECTS 31. Name the ASP Objects? · · · · ·

Request Object Response Object Server Object Session Object Application Object

32. What is Request Object? 517

Gets information from the user. It has five collections by which values can be accessed. They are: Querystring, Form, Cookies, Server Variables & ClientCertificate 33. What is Collection? Collection is a set of name/value pairs where the information supplied by the client is stored. 34. What is application Object? Shares information among users of an application. Gives a notification when an application starts or ends. 35. What is Application-scope? Application-scope means that variables (and objects) can be accessed from any ASP pages that is part of the application. 36. How many global.asa files can an Application have? Only one global.asa file and it’s placed in the virtual directory’s root. 37. What are the collections of Application Object? * Contents collection – contains all variables added via scripts in global.asa. * Static collection – contains the names of all objects added via the tag in global.asa. ASP - Grade A

1. <% strName="John Smith" %> Referring to the above, if you want to pass the contents of the strName variable in a hyperlink, which line of code would you use? A. This cannot be done. The anchor is on the client and the variable is on the server. B. href="Encode.asp?name=<%=Server.URLPathEncode(strName)%>">click here C. ">click here 518

D. ">click here E. ">click here 2. <%@ Language=VBScript %> <%If false then> <%Else> <%End If> What would the above code load? A. Only the FunctionTwo.inc file into the ASP page. B. Both files, since Server Side Includes are processed before ASP interpreting. C. Only the FunctionOne.inc file into the ASP page. D. Neither file, since Server Side Includes are processed before ASP interpreting. E. Neither file, since the #INCLUDE statements are commented out. 3. <% Response.Redirect("http://www.sql.com") %> What does the above code accomplish? A. It sends the browser the line of sample code, and the browser executes it. B. It sends the response to "http://www.matsystems.com" instead of to the Requesting browser. C. It sends a redirection header back to the browser, and the browser then requests the new target document. D. The redirection occurs on the server-side, and the first response the browser gets is the head and body of the new target document. E. It causes the server to send a request to the target URL and passes the response to the requesting browser. 4. How are sessions maintained? A. The browser sends a cookie to the server request. B. The browser sends a Querystring variable server with each request. C. The browser sends a hidden Form variable server with each request. D. The browser sends a long variable to the the BODY of each request. E. None of the above.

with each to the to the server in

5. When does the application OnEnd event handler fire? A. After every request for an application document, 519

since web servers are stateless servers. B. As soon as there are no open connections to any application document. C. When the web server is stopped in an orderly fashion. D. Twenty minutes after the last request for a document in the application. E. When there are no application requests for the amount of time defined by the SessionTimeout variable. 6. How long is a SessionID guaranteed to be unique? A. It is unique for the web server, whether it is restarted or not. B. Only until the web server is restarted. C. It is like a GUID in that it is for any web server at any time. D. Only until the session expires, then it can be reissued to another client. E. It is unique per client. A client cannot have two sessions with the same SessionID 7.Which-code sample will report whether the client's browser supports cookies? A. <% var objFSO = Server.CreateObject("Scripting.FileSystemObject") Response.Write objFSO.cookiesSupported %> B. You can only use JavaScript for this. C. <% var objFSO = Server.CreateObject("Scripting.FileSystemObject") Response.Write objFSO.cookies %> D. <% var objBrowser = Server.CreateObject("MSWC.BrowserType") Response.Write objBrowser.cookies %> E. <% var objBrowser = Server.CreateObject("MSWC.BrowserType") Response.Write objBrowser.cookiesSupported %> 8. Male Female Referring to the above, which line of code would retrieve the selected radio button value? A. For cnt=0 to rbSex.count - 1 If rbSex(cnt).value = selected Then strSex = rbSex(cnt).value exit for End If Next B. strSex = Request("rbSex").selected.value C. strSex = Request("rbSex") D. strSex = Request.rbSex.value 520

E. For Each value in rbSex If rbSex.selected = true strSex = value exit for Next 9. The FileSystemObject provides an object interface to drives, directories, and files for which of the following? A. Any local or mapped drive on either the server or the client. B. Only files and subdirectories in the web site's home directory. C. Any local physical drive or mapped drive on the web server. D. Any file system physically located on the web server. E. The client's computer. 10. What purpose is served by the Application.Lock method? A. It locks the Application object, preventing other clients from altering any values in the Contents collection. B. It locks the application, preventing the server from responding to any requests for application documents. C. It locks the application, preventing non-SSL requests from being processed. D. It locks the Application object, preventing other clients from reading any values in the Content collection. E. It locks other clients from reading the Contents collection. 11. How to Display images using Response object? A. B. C. D.

Contenttype=Application/Brush Contenttype=Image/JPG Contenttype=Application/paint Contenttype=Image/WMF

12.What is the use of following Statement Response.Expires=120 A.The B.The C.The D.The

page page page page

will will will will

be be be be

removed removed removed removed

form form form form

cache cache cache cache

after 120 Hours after 120 Sec before 120 Min after 2 Hours

13. Which choice is NOT a property of Dictionary Object? A. Key() 521

B. C. D. E.

CompareMode Item () Exists () Count

14. Using VBScript, which of the following Scripting Object(s) is NOT available from scrrun.dll? A. B. C. D. E.

TextStream Dictionary Object Err Object FileSystemObject All are available from scrrun.dll.

15. What is a .ASP file? It is a Text File that contains the combination of the following: · Text · HTML tags · Script Commands 16.How are scripts executed? ASP provides scripting engines that execute the corresponding scripting languages on the server side. Scripts should be encoded within the <%…. %> Delimiters. 17. What are the browsers that can access ASP pages? · Internet Explorer (supports VBScript, JavaScript) · Netscape Communicator/ Navigator (supports only JavaScript, VBScript can be also added too) 18. What is a "Virtual Directory"? Virtual directories are aliases for directory paths on the server. It allows moving files on the disk between different folders, drives or even servers without changing the structure of web pages. It avoids typing an extremely long URL each time to access an ASP page. 19. What is the difference between client-side script and server-side script? Scripts executed only by the browser without contacting the server is called client-side script. It is browser dependent. The scripting code is visible to the user and hence not secure. Scripts executed by the web server and processed by the server is called server-side script. 20. Give the comment Tags for the following: VBScript 522

:

REM & ‘(apostrophe)

JavaScript : // (single line comment) /* */ (Multi-line comments) 21.How can you disable the browser to view the code? Writing codes within the Tag. 22. How does the server identify and execute the server-side scripts within HTML code? · Including the RUNAT=SERVER attribute in the <SCRIPT> tag · Use <% … %> server script delimiter 23. How can you change the primary scripting language for a page? Specify <%@ LANGUAGE = Scripting language %> 24. What is the order of execution for an ASP application? 1) Global.asa 2) Server-side Includes 3) Jscript scripts tagged within <SCRIPT> tags 4) HTML together with scripts tagged within <% … %> delimiters 5) VBScripts tagged within <SCRIPT> tags 25. What are the tasks performed by
tags? · tags provides space for the user to input values · the form has a button to submit information back to the server · It transfers control to another ASP page · It carries the information in the fields to another ASP page 26. What are the attributes of the tags? What are their functions? The two attributes are ACTION and METHOD The ACTION gives the name of the ASP file that should be opened next by which this file can access the information given in the form The METHOD determines which of the two ways (POST or GET) the browser can send the information to the server 27. What are the tags necessary to be present within the tag? tag: Provides input spaces (text boxes, combo boxes, radio button, etc.) on a form called fields. It has three attributes TYPE, NAME and VALUE. TYPE provides the characteristics of the field and the NAME specifies a name to the field by which it can be referred. 523

28. What is Querystring collection? This collection stores any values that are provided in the URL. This can be generated by three methods: · By clicking on an anchor tag · By sending a form to the server by the GET method · Through user-typed HTTP address 29. What The Form elements only way

is a Form collection? collection holds the values of the form submitted with the POST method. This is the to generate a Form collection.

30. What is the difference between Querystring collection and Form collection? The main difference is that the Querystring collection gets appended to a URL(with a ?) and can be generated by three ways whereas the Form collection is sent as part of the HTTP request body and there is only way to generate a Form collection. 31. What is Cookies collection? Cookies are text files that store information about the user by which the web server identifies and marks each different visitor to a web site and determines where a user has been before. A cookie can store information only when the user sends it. Individual cookies are limited to 4KB of data. The maximum number of cookies allowed is 300. Cookies are stored on client’s machine. 32. What is the difference between Cookies collection and Form/Querystring collection? Cookie collection does not have the Count property. Cookies can have multiple values for the same cookie name but each value can be referred using a key whereas in a Form/Querystring cookie each value has to be referred using a index value. 33. What is ServerVariables collection? The ServerVariables collection holds all of the HTTP headers and also additional items of information about the server. 34. What is ClientCertificate collection? A ClientCertificate is an encrypted number that is stored in a file on the user’s computer. This stores details of any security certificates included with the request. 35. What are the event handlers of Session Object? · Session _OnStart – This event will be fired when a new user begins a session with the web site. · Session_OnEnd – This event is called whenever a session terminates. 524

36. What are the advantages of Object?

Cookies over Session

· It informs each page what session the request belongs to when a user accesses during a session. · It retrieves all the session information stored on the server. · Cookies can persist for a much longer period of time than session that has a timeout value usually of 20 minutes and hence can store information even when a user is off the site. 37. How will you delete a Cookie? By setting its Expires property to any date prior to today Response.Cookies("cookie name").Expires = Date – 1. 38. What is Server Object? Controls the ASP execution environment. It can set the amount of time script can run before an error occurs. Converts a virtual path to a physical path on the server. Takes a user supplied string and encode it into proper format for a URL string. 39. What is a TextStream object? It allows you to access(read/write) the contents of text files stored on the web server. 40. What is an Err Object? Name it’s properties and methods? An object used to trap errors in the application. Description, Number, Source, HelpFile and HelpContext are its properties and Raise and Clear are its method. 41. What is Extranet? An area of a web site available only to a set of registered visitors.

525

------------------------------------------------------------------------------------1)3 main differences between flexgrid control and dbgrid(Data bound Grid) control ------------------------------------------------------------------------------------The Microsoft FlexGrid (MSFlexGrid) control displays and operates on tabular data. It allows complete flexibility to sort, merge, and format tables containing strings and pictures. When bound to a Data control, MSFlexGrid displays read-only data.Adaptation to existing Visual Basic code for the data-bound grid (DBGrid). dbgrid id A spreadsheet-like bound control that displays a series of rows and columns representing records and fields from a Recordset object. The data grids are bound controls; that is, they require a data source that actually connects to a database and retrieves their data. And it seems that the root of the problem with DBGrid is that there's no data source that can be readily included along with the DBGrid control. In Visual Basic, the solution is simply to include the Data Control on the same form as DBGrid. But the Data Control is an intrinsic control; it's unavailable to anything outside of the Visual Basic environment itself. and VB 6.0 has a new set of data controls (DataGrid, DataList, DataCombo, MSHFlexGrid, MSFlexGrid) that once again are bound controls. Unlike DBGrid, though, they support OLE DB, and therefore rely on the an ADO Data Source (and in particular the ActiveX Data Objects Data Control, or ADO DC) for data access. Unlike the Data Control, the ADO DC is a custom control (that is, an .OCX) that can be added to any project. In short, if you add ADO DC to your project along with the DataGrid control. ------------------------------------------------------------------------------------2)ActiveX and Types of ActiveX Components in VB ? ------------------------------------------------------------------------------------Standard EXE ActiveX EXE ActiveX DLL ActiveX document ActiveX Control Project Group ------------------------------------------------------------------------------------3)diff between inprocess and out of process ? ------------------------------------------------------------------------------------526

An in-process component is implemented as a DLL, and runs in the same process space as its client app, enabling the most efficient communication between client and component.Each client app that uses the component starts a new instance of it. An out of process component is implemented as an EXE, and unlike a dll, runs in its own process space. As a result, exe's are slower then dll's because communications between client and component must be marshalled across process boundaries. A single instance of an out of process component can service many clients. ------------------------------------------------------------------------------------3)Advantage of ActiveX Dll over Active Exe ? ------------------------------------------------------------------------------------ACTIVEX DLL: ============= An in-process component, or ActiveX DLL, runs in another application’s process. In-process components are used by applications or other in-process components. this allows you to wrap up common functionality (like an ActiveX Exe). ACTIVEX EXE: ============= An out-of-process component, or ActiveX EXE, runs in its own address space. The client is usually an application running in another process.The code running in an ActiveX Exe is running in a separate process space. You would usually use this in N-Tier programming. An ActiveX EXE runs out of process while an ActiveX DLL runs in the same process space as VB app. Also, and ActiveX EXE can be run independent of your application if desired. ------------------------------------------------------------------------------------4)single thread and multithread thread aprtments ------------------------------------------------------------------------------------All components created with Visual Basic use the apartment model, whether they’re single-threaded or multithreaded. A single-threaded component has only one apartment, which contains all the objects the component provides.

527

This means that a single-threaded DLL created with Visual Basic is safe to use with a multithreaded client. However, there’s a performance trade-off for this safety. Calls from all client threads except one are marshaled, just as if they were out-of-process calls. ------------------------------------------------------------------------------------5)What is a Component? ------------------------------------------------------------------------------------If you compile an ActiveX dll, it becomes a component. If you compile an ActiveX Control, it becomes both a component and a control. Component is a general term used to describe code that's grouped by functionality. More specifically, a component in COM terms is a compiled collection of properties/methods and events. Typically a component is loaded into your project via the References whereas an ActiveX Control is loaded into your project via "components". ------------------------------------------------------------------------------------6)What is meant by "Early Binding" and "Late Binding"? Which is better? ------------------------------------------------------------------------------------Early binding and late binding refer to the method used to bind an interface's properties and methods to an object reference (variable). Early binding uses type library information at design time to reference procedures, while late binding handles this at run time. Late binding handles this by interrogating the reference before each call to insure that it supports a particular method. Since every call to a late bound object actually requires two calls ("Do you do this?" followed by "Okay, do it then"), late binding is much less efficient than early binding. Except where early binding is not supported (ASP, scripting, etc.), late binding should only be used in very special cases. It is a common misconception that any code using the CreateObject function instead of Set = New is using late binding. This is not the case. The type declaration of the object variable determines whether it is late or early bound, as in the following: Dim A As Foo Dim B As Foo Dim C As Object Dim D As Object Set A = New Foo 'Early Bound Set B = CreateObject("FooLib.Foo") 'Early Bound Set C = CreateObject("FooLib.Foo") 'Late Bound 528

Set D = New Foo

'Late Bound

------------------------------------------------------------------------------------7)Advantages of disconnected recordsets ------------------------------------------------------------------------------------A disconnected Recordset, as its name implies, is a Recordset that lacks a connection. This may seem a bit confusing at first - how can a Recordset lack a connection to a data store? - but will hopefully become more clear as the article progresses. seen that a Recordset that does not have a database connection can be very useful as a tool in your programming. It can save you time and effort and make your code more scalable. In order to create a disconnected Recordset two Recordset properties must be set appropriately. It is a requirement that the CursorLocation property is set to adUseClient and the LockType property is set to adLockBatchOptimistic. Note that the CursorType will default to adUseStatic if we don't explicitly state that it should be set to adUseClient.) i.e rst.LockType = adLockBatchOptimistic rst.CursorLocation = adUseClient However, we've recently discovered that these steps aren't necessary. VB automatically assigns batch optimistic locking to newly created, connectionless recordsets. And, of course, without a connection, a recordset can't have any other cursor but a client-side one. To create one of these structures, then, the only thing you need do is create the object variable instance. After that, you can simply begin adding fields to the construct. To add fields, you use the Fields collection's Append method. This method requires two parameters , the field name and the field data type. So, to create a connectionless recordset with two fields,you'd use code similar to: Dim rst As ADODB.Recordset Set rst = New ADODB.Recordset rst.Fields.Append "CustID", adVarChar rst.Fields.Append "CustName", adVarChar 529

Additional, optional Append method parameters include DefinedSize and Attrib. The DefinedSize argument takes the size of the field. Fill the Attrib parameter with constants that define additional field characteristics, such as whether it will allow null values or is updatable. Since, in our technique, we want the fields to mirror the structure of the original recordset, we'll simply use existing values for these parameters. Disconnected Recordsets, first available with ADO 2.0, are the most commonly used mechanism to retrieve a Recordset and open a connection for only the necessary amount of time, thus increasing scalability. They are call disconnected because the connection to the database is closed. The collections, properties, and methods of a disconnected Recordset are still available even though the connection is closed. This frees up server resources, given that the number of open connections is limited and database locking is a non-issue. ------------------------------------------------------------------------------------8)Benefit of wrapping database calls into MTS transactions? ------------------------------------------------------------------------------------If database calls are made within the context of a transaction, aborting the transaction will undo and changes that occur within that transaction. This removes the possibility of stranded, or partial data. Transaction that uses the Microsoft® Transaction Server (MTS) environment. MSMQ implicitly uses the current MTS transaction if one is available. BENIFTIS OF USING MTS : *********************** Database Pooling, Transactional operations, Deployment, Security, Remote Execution This allows MTS to reuse database connections. Database connections are put to ?sleep? As opposed to being created and destroyed and are activated upon request. ------------------------------------------------------------------------------------9)How to register a component? ------------------------------------------------------------------------------------Compiling the component, running REGSVR32 MyDLL.dll ------------------------------------------------------------------------------------10)Controls which do not have events ? ------------------------------------------------------------------------------------Shape and line controls are useful for drawing graphical elements on the surface of a form. These controls don't support any events; they are strictly for decorative purposes. 530

EXTRA INFO:: ************* The image, shape and line controls are considered to be lightweight controls; that is, they support only a subset of the properties, methods, and events found in the picture box. Because of this, they typically require less system resources and load faster than the picture box control. ------------------------------------------------------------------------------------11)Control Categories ------------------------------------------------------------------------------------a)Intrinsic controls: ********************** such as the command button and frame controls. These controls are contained inside the Visual Basic .exe file. Intrinsic controls are always included in the toolbox b)ActiveX controls: ********************** which exist as separate files with a .ocx file name extension. These include controls that are available in all editions of Visual Basic (DataCombo, DataList controls, and so on) and those that are available only in the Professional and Enterprise editions (such as Listview, Toolbar, Animation, and Tabbed Dialog). Many third-party ActiveX controls are also available. c)Insertable Objects: ********************** such as a Microsoft Excel Worksheet object containing a list of all your company's employees, or a Microsoft Project Calendar object containing the scheduling information for a project. Since these can be added to the toolbox, they can be considered controls.Some of these objects also support Automation (formerly called OLE Automation),which allows you to program another application's objects from within a Visual Basic application. ------------------------------------------------------------------------------------12)DIFF between Image and Picture box controls ------------------------------------------------------------------------------------The sizing behavior of the image control differs from that of the picture box. It has a Stretch property while the picture box has an AutoSize property. Setting the AutoSize property to True causes a picture box to resize to the dimensions of the picture; setting it to False causes the picture to be cropped (only a portion of the picture is visible). When set to False (the default) 531

, the Stretch property of the image control causes it to resize to the dimensions of the picture. Setting the Stretch property to True causes the picture to resize to the size of the image control, which may cause the picture to appear distorted. ------------------------------------------------------------------------------------13)Default property of datacontrol ?... ------------------------------------------------------------------------------------connect property......(not sure..) ------------------------------------------------------------------------------------14)Define the scope of Public, Private, Friend procedures? ------------------------------------------------------------------------------------The set of public variables, methods, properties, and events described in a class module define the interface for an object. The interface consists of the object members that are available to a programmer who's using the object from code.<=====> You can create private variables, methods, properties, and events that are used by other procedures within the class module but are not part of the object's public interface. Additionally, constants user-defined types, and Declare statements within a class module must always be private.<====> The Friend keyword makes a procedure private to the project: The procedure is available to any code running within the project, but it is not available to a referencing project. ------------------------------------------------------------------------------------15)Describe Database Connection pooling relative to MTS ? ------------------------------------------------------------------------------------This allows MTS to reuse database connections. Database connections are put to ?sleep? as opposed to being created and destroyed and are activated upon request. Object pooling is an important design concept required for high-performance applications. A performance optimization based on using collections of preallocated resources, such as objects or database connections. Pooling results in more efficient resource allocation. ------------------------------------------------------------------------------------16)Difference between a function and a subroutine ? ------------------------------------------------------------------------------------A function accepts any number of parameters (possibly zero), does something with them, and returns a value. A subroutine is performs an action, but doesn't return a value. There are two differences between a function and a subroutine: A)How they are invoked. B)How they are accessed. A function call has the following syntax ::function (arg1, arg2, ...) where: function -->Is the name of the function. arg1, arg2, ... Are the arguments. 532

A subroutine call has the following syntax ::subroutine (arg1, arg2, ... {outputfield|'format'}) where: subroutine -->Is the name of the subroutine. arg1, arg2, ... Are the arguments. {outputfield|'format'} Is the name of the output field or its format. In addition, on some platforms, the functions are available immediately; whereas, the subroutines are available in a special subroutine library that you must access. ------------------------------------------------------------------------------------17)Difference between Linked Object and Embedded Object? ------------------------------------------------------------------------------------Embedding objects ******************* When you embed an object, a copy of the object is inserted into the destination document. There's no link to the original file. When you change information in the source document, no changes will be reflected in the destination document. The actual data for the object is stored within the destination file. To make changes to the embedded object, double click it and it will launch the original application the source file was in. Linking objects ***************** Information is updated when you modify the original source file when you use a linked object. This dynamic updating is very handy for things such as the aforementioned monthly report. You can open up the Excel spreadsheet that is referenced within your Word document.Make changes to the spreadsheet, close Excel, and when you open your Word document... viola! The changes are already there. If that object is linked to ten other Word files, the changes are already in those ten files, too! actually linking or embedding an object is fast and easy. ------------------------------------------------------------------------------------18)Difference between listbox and combo box? ------------------------------------------------------------------------------------A LISTBOX CONTROL displays a list of items from which the user can select one or more. If the number of items exceeds the number that can be displayed, a scroll bar is automatically added to the ListBox control. A COMBOX CONTROL combines the features of a text box and a list box. This control allows the user to select an item either by typing text into the combo box, or by selecting it from the list. 533

DIFF::Generally, a combo box is appropriate when there is a list of suggested choices, and a list box is appropriate when you want to limit input to what is on the list. A combo box contains an edit field, so choices not on the list can be typed in this field. ------------------------------------------------------------------------------------19)Difference between Dynaset and Snapshot? ------------------------------------------------------------------------------------All Recordset objects are constructed using records (rows) and fields (columns). There are five types of Recordset objects: Table-type Recordset :: ******************** representation in code of a base table that you can use to add, change, or delete records from a single database table (Microsoft Jet workspaces only). Dynaset-type Recordset :: ********************** the result of a query that can have updatable records. A dynaset-type Recordset object is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables. A dynaset-type Recordset object can contain fields from one or more tables in a database. This type corresponds to an ODBC keyset cursor. Snapshot-type Recordset :: ********************** a static copy of a set of records that you can use to find data or generate reports. A snapshot-type Recordset object can contain fields from one or more tables in a database but can't be updated. This type corresponds to an ODBC static cursor. Forward-only-type Recordset:: *************************** identical to a snapshot except that no cursor is provided. You can only scroll forward through records. This improves performance in situations where you only need to make a single pass through a result set. This type corresponds to an ODBC forward-only cursor. Dynamic-type Recordset :: ********************** a query result set from one or more base tables in which you can add, change, or delete records from a row-returning query. Further, records other users add, delete, or edit in the base tables also appear in your Recordset. This type corresponds to an ODBC dynamic cursor (ODBCDirect workspaces only). ------------------------------------------------------------------------------------534

20)Difference Listindex and Tab index? ------------------------------------------------------------------------------------LIST INDEX:: Returns or sets theindex of the currently selected item in the control. Not available at design time.Default LIST INDEX IS -1 for ComboBox, DirListBox, and DriveListBox controls TAB INDEX:: Returns or sets thetab order of most objects within their parent form. Visual Basic automatically renumbers the TabIndex of other controls to reflect insertions and deletions. You can make changes atdesign time using theProperties window or atrun time in code.The TabIndex property isn't affected by the ZOrder method. ------------------------------------------------------------------------------------21)Difference modal and moduless window? ------------------------------------------------------------------------------------MODAL forms are forms which require user input before any other actions can be taken place. In other words, a modal form has exclusive focus in that application until it is dismissed. When showing a modal form, the controls outside this modal form will not take user interaction until the form is closed. The internal MsgBox and InputBox forms are examples of modal forms. To show a form modally, use the syntax: MyForm.SHOW.vbModal ' a predeclared constant for 1 MODELESS forms are those which are shown but do not require immediate user input. MDI child forms are always modeless. To show a form modeless, use the syntax:: MyForm.SHOW ------------------------------------------------------------------------------------22)Difference Object and Class? ------------------------------------------------------------------------------------Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.1)A Class is static. All of the attributes of a class are fixed before,during, and after the execution of a program. The attributes of a class don't change.The class to which an object belongs is also (usually) static. If a particular object belongs to a certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed. 2)An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.So basically the difference between a class and an object is that a class is a general concept while objects are the specific and real instances that embody that concept. When creating 535

an object oriented program we define the classes and the relationships between the classes . We then execute the program to create, update, and destroy the objects which are the specific realization of these classes. ------------------------------------------------------------------------------------23)Difference Query unload and unload in form? ------------------------------------------------------------------------------------Occurs before a form or application closes. When an MDIForm object closes, the QueryUnload event occurs first for the MDI form and then in all MDI child forms. If no form cancels the QueryUnload event, the Unload event occurs first in all other forms and then in an MDI form. When a child form or a Form object closes, the QueryUnload event in that form occurs before the form's Unload event. ------------------------------------------------------------------------------------24)Difference Declaration and Instantiation an object? ------------------------------------------------------------------------------------Dim obj as OBJ.CLASS with either Set obj = New OBJ.CLASS or Set obj = CreateObject(?OBJ.CLASS?) or Set obj = GetObject( ,? OBJ.CLASS?) or Dim obj as New OBJ.CLASS Set object = Nothing ensure the object is release from the memory. If this object is a form, you can add set myform = nothing and Form_Unload() event.Maintain a habit of remove the object by using set object = nothing which will benefit at last. Visual Basic is supposed to automatically release objects when they go out of scope. To free up some memory usage, you can set the object to nothing. ------------------------------------------------------------------------------------25)Draw and explain Sequence Modal of DAO ------------------------------------------------------------------------------------Connection,Container,Database,DBEngine,Document,Error,Field,Group,Index Parameter Property,QueryDef,Recordset,Relation,TableDef,User,Workspace ------------------------------------------------------------------------------------536

26)Version |Year |Significant Changes and New Features ------------------------------------------------------------------------------------1 1991 initial release, with drag and drop GUI creation 2 1992 ODBC, object variables 3 1993 Access Engine, OLE 2.0, Crystal Reports, new tools and controls 4 1995 classes, OCXs 5 1997 compiler, ActiveX controls 6 1998 web support, windowless controls, designers, data sources .NET 2001 XML, SOAP, inheritance, structured exception handling ------------------------------------------------------------------------------------27)How can objects on different threads communicate with one another? ------------------------------------------------------------------------------------Processes communicate with one another through messages, using Microsoft's Remote Procedure Call (RPC) technology to pass information to one another.There is no difference to the caller between a call coming from a process on a remote machine and a call coming from another process on the same machine. Multithreaded applications must avoid two threading problems: deadlocks and races.A deadlock occurs when each thread is waiting for the other to do something ------------------------------------------------------------------------------------28)How can you force new objects to be created on new threads? ------------------------------------------------------------------------------------The CreateThread function creates a thread to execute within the virtual address space of the calling process. To create a thread that runs in the virtual address space of another process Creating a new thread is as easy as declaring it and supplying it with a delegate to the method where the thread is to start. When you are ready to begin execution on the thread, call the Thread.Start Method. There are special considerations involved when working with multiple threads of execution. To create a new thread of execution ==================================== Declare the thread. ****************** ' Visual Basic Dim myThread as System.Threading.Thread // C# 537

System.Threading.Thread myThread; Instantiate the thread with the appropriate delegate for the starting point of the thread. Use the AddressOf operator to create the delegate in Visual Basic, or create a new ThreadStart object in C#. ******************* ' Visual Basic myThread = New System.Threading.Thread(AddressOf myStartingMethod) // C# myThread = new System.Threading.Thread(new System.Threading.ThreadStart(myStartingMethod)); call the Thread.Start method to start the thread. ******************* ' Visual Basic myThread.Start() // C# myThread.Start(); ------------------------------------------------------------------------------------29)How does a DCOM component know where to instantiate itself? ------------------------------------------------------------------------------------To create a remote instance of a script component, call the CreateObject method, passing it the name of the remote computer as a parameter. If the remotable attribute of a script component's element has been set to "true," the script component can be instantiated remotely from another computer using Distributed COM (DCOM). Both computers must have basic DCOM installed. Note The ability to use CreateObject for instantiating remote script components requires Visual Basic 6.0 or later or VBScript 5.0 or later. The following Visual Basic example shows how to do this on a computer named "myserver": Set newS = CreateObject("Component.MyComponent", "myserver") Note There can be a slight delay when you first instantiate a remote script component while DCOM establishes communication between the computers. 1. You can specify the machine on which you want to create the remote server object in DCOM config ('dcomcnfg'). 2. You can specify the machine name when instantiating the remote server object. In C you can do this with a call to CoGetClassObject or CoCreateInstanceEx (instead of CoCreateInstance, 538

which does not allow you to specify the name of the machine). In VB you can specify the name in one of the parameters in the call to CreateObject ------------------------------------------------------------------------------------30)What type of multi-threading does VB6 implement? ------------------------------------------------------------------------------------Apartment model threading ------------------------------------------------------------------------------------31)How to register a component? ------------------------------------------------------------------------------------Compiling the component, running REGSVR32 MyDLL.dll ------------------------------------------------------------------------------------32)What is Database Connection pooling (relative to MTS) ------------------------------------------------------------------------------------This allows MTS to reuse database connections. Database connections are put to "sleep" As opposed to being created and destroyed and are activated upon request. ------------------------------------------------------------------------------------33)What is the tool used to configure the port range and protocols for DCOM communications? ------------------------------------------------------------------------------------DCOMCONFIG.EXE ------------------------------------------------------------------------------------34)What is a Type Library and what is it's purpose ? ------------------------------------------------------------------------------------The type library may represent another Visual Basic project, or any other executable component that exposes a type library. Visual Basic creates type library information for the classes you create, provides type libraries for the objects it includes, and lets you access the type libraries provided by other applications. ------------------------------------------------------------------------------------35)What are binary and project compatibility? ------------------------------------------------------------------------------------Visual Basic’s Version Compatibility feature is a way of enhancing your components while maintaining backward compatibility with programs that were compiled using earlier versions. The Version Compatibility box, located on the Component tab of the Project Properties dialog box, contains three options: ,sandhya2_001(Re) 539

No Compatibility: ***************** Each time you compile the component, new type library information is generated, including new class IDs and new interface IDs. There is no relation between versions of a component, and programs compiled to use one version cannot use subsequent versions. Project Compatibility: ********************** Each time you compile the component the type library identifier is kept, so that your test projects can maintain their references to the component project. All class IDs from the previous version are maintained; interface IDs are changed only for classes that are no longer binary-compatible with their earlier counterparts. Note This is a change in Project Compatibility from Visual Basic 5.0, where all class IDs and interface IDs in the project changed if any one class was no longer binary-compatible. Important For the purpose of releasing compatible versions of a component, Project Compatibility is the same as No Compatibility. Binary Compatibility: ********************* When you compile the project, if any binary-incompatible changes are detected you will be presented with a warning dialog. If you choose to accept the warning, the component will retain the type library identifier and the class IDs. Interface IDs are changed only for classes that are no longer binary-compatible. This is the same behavior as Project Compatibility. If, however, you choose to ignore the warning, the component will also maintain the interface IDs .This option is only available when the compiler determines that the change was in the procedure ID or signature of a method. Note:: When people talk about Version Compatibility, they’re usually referring to Binary Compatibility. ------------------------------------------------------------------------------------38)How to set a shortcut key for label? ------------------------------------------------------------------------------------object.KeyLabel(keycode) [= string] You would probably create the menu item as follows: .Add "keyFile", , , "E&xit", , vbAltMask + vbCtrlMask, vbKeyEnd The default key label for vbKeyEnd is "End". Thus, the shortcut string will be created by default as "Ctrl+Alt+End". 540

------------------------------------------------------------------------------------39)Name the four different cursor and locking types in ADO and describe them briefly ? ------------------------------------------------------------------------------------CURSORS:: ********* The cursor types are listed from least to most resource intensive. Forward Only - Fastest, can only move forward in recordset Static - Can move to any record in the recordset. Data is static and never changes. KeySet - Changes are detectable, records that are deleted by other users are unavailable, and records created by other users are not detected Dynamic - All changes are visible. LOCKING TYPES:: **************** LockPessimistic - Locks the row once after any edits occur. LockOptimistic - Locks the row only when Update is called. LockBatchOptimistic - Allows Batch Updates. LockReadOnly - Read only. Cannot alter the data. ------------------------------------------------------------------------------------40)Name the different compatibility types when creating a COM component. ------------------------------------------------------------------------------------No Compatibility - New GUID (Globally Unique Identifier) created, references from other components will not work Project Compatibility - Default for a new component Binary Compatibility - GUID does not change references from other components will work ------------------------------------------------------------------------------------41)Why is it important to use source control software for source code? ------------------------------------------------------------------------------------Modification history. Code ownership: Multiple people cannot modify the same code at the same time. ------------------------------------------------------------------------------------42)List the ADO objects? ------------------------------------------------------------------------------------Connection - Connects to a data source; contains the Errors collection Command - Executes commands to the data source. The only object that can accept parameters for a stored procedure Recordset - The set of data returned from the database. Under the ADO Command Object, The Parameters collection. collection is responsible for input to stored procedures? ------------------------------------------------------------------------------------541

43)What two methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful? ------------------------------------------------------------------------------------SetComplete and SetAbort. ------------------------------------------------------------------------------------44)What is the benefit of wrapping database calls into MTS transactions? ------------------------------------------------------------------------------------Aborting the transaction will undo and changes that occur within that transaction. This removes the possibility of stranded, or partial data ------------------------------------------------------------------------------------45)Describe and In Process vs. Out of Process component. Which is faster? ------------------------------------------------------------------------------------An in-process component is implemented as a DLL, and runs in the same process space as its client app, enabling the most efficient communication between client and component. Each client app that uses the component starts a new instance of it. An out of process component is implemented as an EXE, and unlike a dll, runs in its own process space. As a result, exe's are slower then dll's because communications between client and component must be marshaled across process boundaries. A single instance of an out of process component can service many clients. ------------------------------------------------------------------------------------46)How would you declare and raise custom events in a class? ------------------------------------------------------------------------------------a) Public Event OnVarChange(); b) RaiseEvent OnVarChange[(arg1, arg2, ... , argn)] ------------------------------------------------------------------------------------47)What is the difference between a Property Let and Property Set procedure? ------------------------------------------------------------------------------------Let - for simple variable Set - for object ------------------------------------------------------------------------------------48)What is the difference between ANSI and UNICODE strings when passed as arguments to a DLL? ------------------------------------------------------------------------------------ANSI - one byte for a char UNICODE - two bytes per char - works only on NT ------------------------------------------------------------------------------------49)What is the difference in passing values ByRef or ByVal to a procedure? ------------------------------------------------------------------------------------ByRef -pass the address (for string -address of address of first byte) BY REF IS VERY USEFULL When the contents itself are being modified, when there is large data. Multiple arguments are needed to be returned, instead they can be passed as reference. 542

ByVal -pass the value (for string -it is the address of first byte) ------------------------------------------------------------------------------------50)What is the purpose of the DoEvents command? ------------------------------------------------------------------------------------Fields execution so that the operating system can process other events. Returns number of open forms. Useful for things like ‘cancel search’ in windows ------------------------------------------------------------------------------------51)Name and define the logical tiers in a traditional 3-tiered architecture? ------------------------------------------------------------------------------------Presentation logic - front end (HTML, Visual Basic forms) Business Logic - Applications and components that encapsulate business logic Data end - databases to store data ------------------------------------------------------------------------------------52)What is the difference between a PictureBox and Image control? ------------------------------------------------------------------------------------Image Control - Use this to display a picture. Use it over the PictureBox because it takes less operating system resources PictureBox- While it can display pictures, it also acts as an area on which you can print text and graphics. Use it for home-grown graphics or print previews ------------------------------------------------------------------------------------53)Under which circumstance does a VB application ignore a Timer event? ------------------------------------------------------------------------------------When the system is really busy doing something else and when DoEvents is being executed ------------------------------------------------------------------------------------54)What does the NewIndex property return? ------------------------------------------------------------------------------------Used to retrieve the index of the item most recently added to a ListBox or ComboBox control ------------------------------------------------------------------------------------55)What is the purpose of the ClipControls property on a form or container? ------------------------------------------------------------------------------------Returns or sets a value that determines whether graphics methods in Paint events repaint the entire object or only newly exposed areas. Also determines whether the Microsoft Windows 543

operating environment creates a clipping region that excludes non-graphical controls contained by the object. Read-only at run time. ------------------------------------------------------------------------------------56)What is the purpose of the AutoRedraw property on a form or container? ------------------------------------------------------------------------------------Setting AutoRedraw to True automatically redraws the output from these methods in a Form object or PictureBox control when, for example, the object is resized or redisplayed after being hidden by another object ------------------------------------------------------------------------------------57)Have you ever used Collections? Collection Classes? ------------------------------------------------------------------------------------A collection is a set of Repository objects that are all connected to a common source object via a relationship collection. A collection provides a way to connect a group of dependent objects with an object that ‘contains’ them. For example, an Invoice object might have a collection of LineItem objects. ------------------------------------------------------------------------------------58)What version control systems have you used? ------------------------------------------------------------------------------------TLIB 16-Bit add-in ------------------------------------------------------------------------------------59)? How about any other database engines? ------------------------------------------------------------------------------------Apollo OLE DB ,Apollo Server ,Apollo SQL ,FUNCky ,R&R Report Writer ------------------------------------------------------------------------------------36)What kind of components can you use as DCOM servers? ------------------------------------------------------------------------------------actve-x components, Com -------------------------------------------------------------------------------------

544

SQL * PLUS Fill in the blanks : 1. No of User variables in sql*plus is 1024. 2. User can have 100 many number of variables per sql command. 3. User can have 500 many number of lines (assuming 80 characters per line) per sql command. 4. The size of PL/SQL buffer in Oracle 7 is 2k and in Oracle6 is 512k 5. Start command is used to run the contents of the specified command file. 6. The intersect operator is used to get only those rows that returned by both the query. 7. The Grand command is used to set the System privileges, Object privileges. 8. The Savepoint command is used to identify the point in a transaction to which you can later Rollback. 9. To perform one of these operations on your current transaction: * Establish your current transaction as either a read only or a read-write transaction * Assign your current transaction to a specified rollback segment The Set Transaction command is used. 10. The to-char function is used to convert the number datatype to a value of varchar2 datatype. 545

11. The Truncate command is used to remove all rows in a Table or Cluster instantly. Note : We can not truncate rows from a table which is part of a cluster. We cannot truncate rows from a table which has a referenced integrity constraint. 12. The Cluster is a schema object that contains one or more tables that have one or more columns in common. 13. The Create Role command is used to set a set of privileges that can be granted to users or to other roles. 14. To perform one of these functions on an index,table, or cluster: * To collect statistics about the object used by the optimizer and store them in the data dictionary. * To delete statistics about the object from the data dictionary. * To validate the structure of the object. * To identify migrated and chained rows of the table or cluster. The Analyze Command is used.

Select the Correct Answer: 1. An index can have as many as

Columns.

a] 255 b] 21 c] 16 2. A number of columns in a table ranges from 1 to ____ a] 255 b] 254 c] 030 d] None of the above 546

3. The maximum number of components in the Decode expression , including searches, results and default is a] No limitation b] 255 4. ___________ is an alternative name for a table, view, sequence, procedure, stored function, package, snapshot or another synonym. a] Synonym b] Data block c] View d] None of the above 5. The _________ operator is used in character string comparisons with pattern matching a] Between.. And b] Equal operator c] Set operator d] Like 6. __________ returns only one copy of each set of duplicate rows selected. a] Unique b] Distinct c] Group By d] None of the above 7. _____________ is used to lock the selected rows a] Lock table b] For update of c] Object privileges d] Row share 8. _____________ Clause restricts the groups of rows returned to those groups for the specified condition id True a] Where clause b] Having Clause c] Distinct d] Exists 547

9. The ________ option is used to return rows in a hierarchial order a] Connect by start with b] Order by 10. The ________ function is used to return the number of bytes in the internal representation of expression a] Length b] Vsize c] LengthLB ORACLE * FORMS TEST PAPER 1. The _______ built-in is used to Exits the current form and enter the indicated form Ans: NEW_FORM 2. The ___________canvas_view can be used to display items or boilerplate graphics that operators need to see only in certain situations Ans: Stacked 3. The ________ package contains constructs that provides ways to write and read information to and from files Ans: Text_IO 4. On MS-Windows the lookup path for icon files is defined by the _______ environment variable in the ORACLE.INI file Ans: TK21_ICONS 5. If user receive an error in the ORA-3100 to ORA-3199 range when you try to log on to Developer/2000 product, there may not be enough real-mode memory to establish a Communication buffer with an Oracle server.______________ solves this problem by reserving memory for server communications. 548

Ans: NETINIT7.EXE 7. The ____________ property is used When queried records have been marked for inserts , updates, specifies that only columns whose values were actually changed which should be included in the SQL UPDATE statement that is sent to the database during a COMMIT. Ans: Update Changed Columns. 8. The _________ property specifies whether Oracle Forms should validate the value of the text item against the values in the attached LOV. Ans: LOV for Validation 9. A _____________ is an internal Oracle Forms data structure that has the column/row frame work similar to a database. Ans: Record Group. 10. There a three types are___________________________.

of

Record

Group

they

Ans: Static, Query record group, Non_query record group. 11.The ______ built-in is used to write data in the Forms to the Database, but does not perform a database Commit. Ans: Post. 12. Two types of Windows are _________________________ Ans: Document Window and Dialog Window. 13. The _____________ built-in is used to copy the values of each item in the record with the next lower sequence number to the corresponding item in the current record. Ans: Duplicate record. 549

14. An _______ is a container for a group of objects that can be used to copy or reference them in another module. Ans: Object Group. 15. Form the Firing hierarcial for the Given triggers a] When-New-Item-Instance b] When-validate-Item c] Key-Next-Item d] Post-change e] Post-Text-Item f] Pre-Text-Item

Ans: F,A,C,D,B,E.

16. Form the hierarchial for the Given Triggers a] When-New-Record-Instance b] Pre-Record c] Post-Record d] When-Validate-Item e] When-Create-record

Ans: E,B,A,D,C.

17. Use an _________ Trigger for the following purposes: a] To trap and respond to an informative message. b] To replace a standard informative message with a custom message. c] To exclude an in appropriate message. Ans: On_Message. 18. Oracle Forms performs the following steps when the ______ trigger fails a] Sets the error location b] Rolls back to the recently issued Savepoint Ans: On_Update or On_Insert or Pre_Insert or Pre_update or Post_Insert or Post_Update. 19. The _____ command is used to Execute the indicated Operating System Command. Ans: Host. 20. The maximum Number of Procedures and Functions in a Package is _____. Ans: 255. 550

21. Oracle uses work areas called ______ to execute SQL Statement and store processing Information. Ans: Private SQL Area. 22. Two Types of Cursors are ______________________. Ans: 1] Implicit Cursor, 2] Explicit Cursor. 23. The variables declared in a subprogram specification and referenced in the subprogram body are____ parameters. Ans: Formal. 24. The __________ and ___________ are called Assignment Statements. Ans: 1] Select .. into .. 2] Fetch .. into .. 3] :=

551

ORACLE QUESTIONS & ANSWERS Questions What is a Database ?

What is a Database system ?

Answers A Database can be one of the two definitions: •

A set of dictionary tables and user tables that are treated as a unit.



One or more operating system files in which ORACLE stores the tables,views,and other objects:also, the set of database objects used by a given application.



A database is a collection of interrelated data that are to be stored in a single location. It enables sharing of data among various users as and when required.

A Database system is a combination of an Instance and a Database. If the instance is started and connected to an open database, then the database is available for access by the users. A DBMS is a software system with capabilities to organise, manipulate and manage the data. Note:A DBMS must be able to reliably manage a large amount of data in a multi-user environment so that many users can concurrently access the same data.

What is an RDBMS ?

What are the differnt Database models ? What is SQL ? 552

A DBMS must also be secure from unauthorised access and provides eficient solutions for failure recovery. A relational database Mangement System (RDBMS) is a computer program for general purpose data storage and retrieval that organizes data into tables consisting of one or more units of information (rows), each containing the same set of data items (columns). ORACLE is a relational database management system. • Hierarchial. • Networking. • Relational. • S.Q.L - Structured Query Language.SQL is the ANSI industry standard language, used to manipulate

553

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 554

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 555

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 556

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 557

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 558

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 559

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 560

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 561

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 562

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 563

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 564

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 565

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 566

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 567

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 568

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 569

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 570

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 571

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 572

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 573

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 574

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 575

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 576

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 577

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 578

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 579

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 580

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 581

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 582

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 583

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 584

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 585

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 586

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 587

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 588

No 1 2

3 4 5 6

Oracle Questions & Answers What are the different modules of FORMS 4.5 ? Form, Menu and Library modules. What are the differences between FORMS 3.0 and FORMS 4.5 ? FORMS 3.0 FORMS 4.5 1] Mode Character GUI 2] System Variables 20 42 3] Session Single Multiple 4] Blocks, Canvas 255 No limit 5] Triggers 75 121 6] Items types 10 7] Relation Design Time Run Time ( Using SET_RELATION_PROPERTY ) 8] Inheritance Not Available Available 9] Property Class - DO - DO 10] Object Groups - DO - DO 11] Library - DO - DO 12] Attached Libraries - DO - DO 13] Visual Attributes - DO - DO What is the maximum limit for creating BLOCKS and CANVAS in FORMS 4.5 ? NO LIMIT In a MULTI RECORD BLOCK can we have an item displayed once ? Yes, By setting the ITEMS DISPLAYED property for the respective item in the Properties Window. After creation of the block can we create a BUTTON PALETTE ? No. What are the different types of triggers that will be created for MASTER DELETES properties such as a] ISOLATED, b] NON - ISOLATED, c] CASCADING ? Master Deletes Property NON - ISOLATED

Resulting Triggers On-Check-Delete-

Master On-Clear-Details On-Populate-Details CASCADING

ISOLATED

7

On-Clear-Details On-Populate-Details Pre-Delete

On-Clear-Details On-Populate-Details What is the difference between creating a MASTER-DETAIL relationship in NEW BLOCK window and creating relations after creation of the blocks ? When you create the relation in the NEW BLOCK window, Oracle forms also alters the properties of the FOREIGN KEY items(s) in the DETAIL BLOCK by doing the 589

1. What is a View ? Why is it required to define a View ? A View is a database object that is a logical representation of a table. It is derived from a table but has no storage space of its own and often may be used in the same manner as a table. Advantage: 1. Security 2. Complex query can be replaced. 2. Can we create a View without a table ? Yes, Using the FORCE option in the CREATE VIEW syntax. Ex: CREATE FORCE VIEW view_name as SELECT name,columnname.. FROM table_name;

column

3. What is the difference between a SYNONYM and a VIEW ? A SYNONYM is a name assigned to a table or view that may thereafter be used to refer it. If you access to another user’s table, you may create a synonym for it and refer to it by the synonym alone, without entering the user’s name as a qualifier. A View is a database object that is a logical representation of a table. It is derived from a table but has no storage space of its own and often may be used in the same manner as a table. Difference: A View can be based on MULTIPLE Tables whereas a SYNONYM is based on a single object only. 4. What is SNAPSHOT ? What is a SNAPSHOT LOG ? A SNAPSHOT is a means of creating a local copy of remote data. A snapshot can be used to replicate all or part of a single table, or to replicate the result of a query against multiple tables. The refreshes of the replicated data can be done automatically by the database ( at time intervals you specify ) or manually.Snapshot Log is the table associated with the Master Table of the Snap shot. 5. What is a DATABASE trigger ? What is a DATABASE Procedure ? A DATABASE TRIGGER is a stored procedure associated with a table that ORACLE7 automatically executes on one or more specified events (BEFORE or AFTER an INSERT,UPDATE or DELETE) affecting the table. Triggers can execute for the table as a whole or for each affected row in the table.

590

A PACKAGED PROCEDURE is a built-in PL/SQL procedure that is available in all forms. Each packaged procedure executes a SQL*FORMS function, such as moving to a field or executing a query. 6. How to show MESSAGES in PROCEDURES for debugging purposes ? DBMS_OUTPUT_PACKAGE allows you to use 3 debugging functions within your package. You must use “SET SERVER OUTPUT ON” before executing the procedure object you will be debugging. PUT Puts multiple O/P’s on same line. PUT_LINE Puts each O/P on a separate line. NEW_LINE Used with PUT; Signals the end of current O/P line. 7. What is the difference between DATABASE trigger and DATABASE procedure ? DATABASE triggers are executed automatically in response to specific events. But the DATABASE procedures are to be explicitly invoked to execute the code contained in them. 8. What is a CURSOR ? A work area in memory where ORACLE stores the current SQL statement. For a query , the area in memory also includes column headings and one row retrieved by the SELECT statement. 9. What are the attributes of IMPLICIT CURSOR ? %ISOPEN, %ROWCOUNT, %FOUND and %NOTFOUND. Attribute RETURNS ROW

DML STATEMENT RETURNS

NO

ROW %ISOPEN %ROWCOUNT ( ZERO ) %FOUND %NOTFOUND

FALSE

FALSE

TRUE TRUE

FALSE FALSE

FALSE

TRUE

10. Can we pass a PARAMETER to CURSOR ? What is SQL%ROWCOUNT ? We can pass parameter to CURSOR. Eg: OPEN CUSOR(‘VASAN’). SQL%ROWCOUNT is used to count the number of rows returned by an SQL DML statement.It will return zero if the DML statement doesn’t return any row. 591

11. How to write a SQL statement that should have a best RESPONSE TIME ? Use the ___________________ in the optimizer hint inorder to obtain a best response time. Use “FIRST_ROW” - Cost based Optimizer Hint. 12. What are OPTIMIZER HINTS ? Specifies a hint string that Oracle Forms passes on to the RDBMS optimizer when constructing queries. Using the optimizer can improve the performance of database transactions. 13. What is the difference between %TYPE and %rowtype ? %TYPE provides the datatype of a varible,constant or column. It is useful when you declare a variable that refers to a database column in the table. %ROWTYPE attribute is based on a record variable that has the same structure as a row in a table or view or as a row fetched from a cursor. 14. Can we define structure like objects in PL/SQL ? [ If the structure is what we define in ‘C’ then we can create objects of type structure using RECORD variable available in PL/SQL. ] Yes, Using the PL/SQL tables. PL/SQL tables are temporary array like objects used in a PL/SQL block. PL/SQL tables can have one column and a primary key. The column data type can belong to any scalar data type, but the primary key must only belong to the type binary_integer. Size - UNLIMITED. 15. Can we use a funtion inside an INSERT statement ? Yes. Eg: INSERT INTO EMP(COMM ) VALUES ( SAL*0.05 ) WHERE DEPTNO = 20; 16. What is TRUNCATE table ? TRUNCATE table is a DDL command used to remove all the rows from the specified table or cluster instantly. Eg: TRUNCATE TABLE table_name; Advantage over DELETING: a] It is a DDL statement and generates NO ROLLBACK information. b] Doesn’t fire the tables DELETE TRIGGER. c] Truncating the master table of a snapshot doesn’t record any changes in the tables snapshot log. d] It’s more convinient than dropping and recreating the table. e] D/R invalidates the table’s dependent objects than truncating the object. f] D/R requires you to REGRANT the privileges on the table while truncating doesn’t. g] D/R requires you to RECREATE the INDEXES, INTEGRITY CONSTRAINTS, TRIGGERS and STORAGE PARAMETER while truncating doesn’t. 592

17. What is ROWID ? What are its components ? ROWID is the logical address of a row, and it is unique within the database.The ROWID is broken into three sections: left,middle,, and right (corresponding to 00001F20,000C, AND 0001, just shown). The numbering is in hexadecimal notation. The left section is the block in the file, the middle is the row sequence number within the block(numbering starts with 0, not 1), and the right is the file number within the database. Note that the file numbers are uniquewithin the whole database. The tablespace they are in is not relevant to the ROWID. ROWID can be selected, or used in a where clause, but cannot be changed by an insert, update, or delete. However it can changeif the table it is in is exported and imported. 18. What is the differnce between REPLACE and TRASLATE ? Syntax : REPLACE(string,if,then) REPLACE replaces a character or characters in a string with 0 or more characters, if is a character or characters. Everytime it appears in a string, it is by the contents of then. Eg: REPLACE(‘ADAH’,’A’,’BLAH’) - BLAHDBLAHH (Result) Syntax: TRANSLATE(string,if,then) TRANSLATE looks at each character in string, and then checks if to see if that character is there, if it is, TRANSLATE notes the position in if where it found the character, and then looks the same position in then. Whatever character it finds there it substitutes the character in string Eg: TRANSLATE(‘RAMESH’,’RAM’,’SUR’) - SURESH(Result) 19. What is a LEVEL ? LEVEL is a pseudo column, used with CONNECT BY. It is equal to 1 for a root, 2 for a child of root, 3 for a child of a child of a root and so on. 20. What is anonymous block in PL/SQL ? The text of an Oracle Forms trigger is an anonymous PL/SQL block. It consists of three sections : • A declaration of variables, constants,cursors and exceptions which is optional. • A section of executable statements. • A section of exception handlers, which is optional. Syntax: DECLARE --- declarartive statements ( optional ) BEGIN 593

--- executable statements ( required ) EXCEPTION --- exception handlers ( optional ) END; 21. Name any ORACLE defined EXCEPTION ? CURSOR_ALREADY_OPEN, NO_DATA_FOUND, INVALID_NUMBER. 22. Can we define our OWN EXCEPTION ? How to raise it ? In the DECLARATION part define a variable of type exception. In the excecution part call the exception using RAISE exception_name. In the exception part handle the exception using WHEN exception_name. 23. What is a PRAGMA ? It is a directive to the COMPILER, rather than a piece of executable code. Eventhough it appears in the program, it is not executable. It gives instructions to the compiler. 24. Difference between CHAR and VARCHAR2 ? CHAR(size) - It is a fixed length character data, size characters long. It is padded with BLANKS ON RIGHT to the full length of size. DEFAULT - 1 bytes, MAXIMUM - 255 bytes. VARCHAR2(size) - It is a varable length char string having a maximum of size bytes. MAXIMUM - 2000 bytes. 25. What is a CURSOR FOR LOOP ? The CURSOR FOR LOOP lets you implicitly OPEN a cursor, FETCH each row returned by the query associated with the cursor and CLOSE the cursor when all rows have been processed. 26. What are the possible CONSTRAINTS defined on a TABLE ? NOT NULL, UNIQUE KEY, PRIMARY KEY, FOREIGN KEY and CHECK constraints. 27. What is APPLICATION PARTITIONING ? PL/SQL is the language used for both client-side Oracle forms applications and server-side database triggers and stored procedures and there is a PL/SQl engine in both Oracle forms Runform and the Oracle7 Server. This means that you can take advantage of application patitioning to execute application code on either the client or the server. Application partitioning allows you to optimize performance and resource usage by storing and executing procedures either locally or at the server, which makes the most sense for your particular application and configuration. 594

28. Difference between a STORED PROCEDURE and a STORED FUNCTION ? Unlike procedures, FUNCTIONS returns a VALUE to the caller. This value is returned thro’ the RETURN command/keyword within the function. Functions don’t use the IN, OUT | IN OUT arguments, which are available for PROCEDURES. 29. How to RUN PROCEDURES from SQL PROMPT ? Use EXECUTE Procedure_name command. 30. How to TRAP ERRORS in procedures ? Use SHOW_ERRORS. this will display all the errors associated with the most recently created procedural object. This command will check the VIEW_ERRORS data dictionary for the ERRORS associated with the most recent compilation attempt for that procedural object. SHOW_ERRORS will display the LINE and COLUMN NO. for each error, as well as the text of the error message. Eg: SELECT LINE, POSITION,TEXT FROM USER_ERRORS WHERE NAME = ‘balance_check’ AND TYPE = PROCEDURE/FUNCTION/PACKAGE ORDER BY SEQUENCE; NOTE: We can use ALL_ERRORS & DBA_ERRORS to view errors. TRAPPING ERORS: DBMS_OUTPUT package allows you to use 3 debugging functions within your package. You must set ‘SERVER OUTPUT ON’ before executing the procedure object you will be debugging. PUT - Puts multiple o/p’s on same line. PUT_LINE - Puts each o/p on a separate line. NEW_LINE - Used with PUT; Signals the END of current o/p line. 31. When do we get a MUTATING ERROR ? This happens with TRIGGERS. It occurs because the trigger is trying to update a row it is currently using. The usual fix involves either use of VIEWS or TEMPORARY TABLES so the database is selecting from one while updating the other. 32. How to DISABLE REFERENTIAL INTEGRITY ? Use the DIABLE option in CREATE TABLE or ALTER TABLE or using DISABLE { { UNIQUE (column) (column)... PRIMARY KEY | CONSTRAINT } [CASCADE] | ALL TRIGGERS; NOTE : For diabling REFERENTIAL INTEGRITY we have to include CASCADE option. 595

33. How to know what all CONSTRAINTS are present in a table ? Using the USER_CONSTRAINTS view we can get the type of constaints declared on a table. Use ALL_CONSTRAINTS to list the constraints on all of the tables that the user have access. DBA_CONSTRAINTS lists all of the constraints in the database. 34. What is MASTER - DETAIL relationship ? Can we write a master-detail relationship programs without using the setings at design time. If so how ? It is an association between TWO BASE TABLE blocks - a MASTER block and a DETAIL block. The relationship between the blocks reflects a PRIMARY KEY - FOREIGN KEY relationship between the tables on which the blocks are based. Yes. Using the SET_RELATION property. 35. What does BUFFER RECORDS option and ARRAY SIZE parameter ? ARRAY SIZE - Specifies the minimum no. of records that get fetched each time forms goes to the database. BUFFER RECORDS - Specifies the minimum no of records that should be placed in memory when records are fetched from the database. Even if you specify a low value of 3, the minimum per form is slightly over 300. 36. During VALIDATION WHAT CHECKS are done with respective to FIELDS / ITEMS ? 1] Data type, 2] Maximum length, 3] Fixed length, 4] Required and 5] Range Low value / Range High value. 37. What is the difference between PRIMARY KEY and UNIQUE KEY ? The UNIQUE KEY column restricts entry of duplicate values but entry of NULL value is allowed. In case of PRIMARY KEY columns entry of duplicate as well as NULL value is restricted. 38. What is the DIFFERENCE between PRE-QUERY and POST-QUERY ? PRE-QUERY fires ONLY ONCE during EXECUTE-QUERY or COUNTQUERY processing, just before Oracle Forms constructs and issues the SELECT statement to identify rows that match the query criteria. POST-QUERY fires each time for records placed on the blocks list of records. 39. When do you use ON-DATABASE-RECORD triigger ? Use an ON-DATABASE-RECORD to perform an action every time a record is first marked as an INSERT or UPDATE.

596

This trigger fires, as soon as Oracle Forms determines thro’ validation that the record should be processed by the next post or commit as an INSERT or UPDATE 40. What are RESTRICTED PACKAGED PROCEDURES ? Why are they restricted from using ? Any PACKAGED PROCEDURE that affects the basic functions of SQL*FORMS is a RESRICTED PACKAGED PROCEDURE. You should use restricted packaged procedure only in KEY-TRIGGERS, USER-NAMED TRIGGERS that are invoked by KEY-TRIGGERS, and ON_NEW_FIELD_INSTANCE triggers. You should not use restricted packaged procedures in any of the following types of triggers. • On-error,On-Database-Record,On-delete,On-insert,On-Lock, • On-Message,On-New-Record,On-Remove-record,On-Update, • On-Validate-Field, and On-validate-Record triggers. • Post-Change triggers. • Pre- and Post- Field, Pre- and Post- Record, Pre- and PostBlock, Pre- and Post-Form triggers. • Pre- and Post-Query triggers. • Pre- and Post-Insert, Pre- and Post-Update, Pre- and PostDelete, Pre- and Post-Commit triggers. • User-Named triggers that are invoked by any of the above triggers. 41. What is the DIFFERENCE between EXPLICIT CURSOR & IMPLICIT CURSOR ? IMPLICIT CURSORS are automatically opened by issuing a SELECT statement. But the EXPLICIT cursors are to be opened using OPEN, fetching is done using FETCH and closing using CLOSE. 42. What is the difference between ROWID and ROWNUM ? ROWID is the logical address of the row, whereas ROWNUM returns the sequence no. in which the row was retrieved when first feched from a table. 43. What is the RESULT of the statement ? SELECT EMPNO, NAME,SAL FROM EMP WHERE ROWNUM >2; Result : 0, No rows will be selected. 44. How do you evaluate performance ? Using SQL TRACE. It is an utility that can monitor and report on database performance when one or more queries are run against the database. It is used to gather statistics when running the query (i.e) reports on CPU time spent on the query, the total no. of rows processed and statistics related to parsing and cache performance. 597

45. What will EXPLAIN PLAN give ? It is an utility that shows how Oracle will access data for a given query. Use EXPLAIN PLAN to determine the effective way to write queries and decide whether to INDEX CERTAIN COLUMNS or TO USE CLUSTERS. It shows : 1] The type of query processed; SELECT, INSERT,UPDATE or DELETE. 2] The cost assigned by the COST BASED OPTIMIZER if it is in use. 3] The steps that are necessary to return the data. 4] The internal operations that were performed for each step. 5] The object accessed for each step. 46. How do you analyse TKPROF ? TKPROF filename.tra O/P file EXPLAIN = USR/PWD0 47. what parameter variables to be set to use TKPROF ? SQL PROF 48. How many types of lockings are there ? 5 types of locks. To lock is to temporarily restrict other user’s access to data. The restriction is placed on such data is called “a lock”. The modes are SHARE, SHARE UPDATE,EXCLUSIVE,ROW SHARE AND ROW EXCLUSIVE. Not all locks can be acquired in all modes. 49. What is a SHARE LOCK ? A SHARE lock is one that permits other users to query data, but not to change it. 50. What is a SHARE UPDATE LOCK ? A SHARE UPDATE lock is one that permits other users to both query and lock data. 51. What is an EXCLUSIVE LOCK ? An EXCLUSIVE LOCK is one that permits other users to query data, but not to change it. It differs from the SHARE lock because it does not permit another user to place any type of lock on the same data; several users may place SHARE locks on the same data at the same time. 52 What is ROWSHARE, SHAREUPDATE and ROW EXCLUSIVE locks ? With a ROW SHARE or SHARE UPDATE lock, no users can lock the whole table for exclusive access, allowing concurrent access for all users to the table. The two types of locks are synonymous, and SHARE UPDATE exists for compatibility with previous versions of ORACLE. 598

ROW EXCLUSIVE locks are similar to ROW SHARE but they prohibit shared locking, so only one user user may access the table at the same time. 53. What is a DEAD LOCK ? A DEAD lock is a rare situation in which two or more user processes of a database cannot complete their tansactions.This occurs because each process is holding a resource that the other process requires (such as a row in a table) in order to complete.Although these situations occur rarely, ORACLE detects and resolves deadlocks by rolling back the work of one of the processes. 54. How do you analyse which resources has locked for what ? Use MONITOR SESSION. 55. How to kill a SESSION ? ALTER SESSION KILL ID, NUMBER FROM SQLDBA; 56. What are USER_EXITS ? It is an utility in SQL*FORMS for making use of HOST 3 GL languages for the purpose like ONLINE PRINTING etc. 57. When will you use the trigger WHEN-NEW-FORM-INSTANCE ? At FORMS STARTUP Oracle navigates to the first navigable item in the first navigable block. This trigger fires after successful completion of any Navigational trigger (i.e) It will not fire if the control retuns to the CALLING FORM from the CALLED FORM. Usage: For initialization at FORMS STARTUP. 58. What is an INDEX ? Why are indexes used in a table ? INDEX is a general term for an ORACLE / SQL feature used primarily to speed execution an impose UNIQUENESS upon certain data. INDEX provides a faster access method to one table’s data than doing a full table scan. There are several types of Indexes : UNIQUE INDEX, COMPRESSED INDEX, CONCATENATED INDEX. An Index has an entry for each value found in the table’s Indexed field(s) ( except those with a NULL value ) and pointer(s) to the rows having that value. 59. What is an UNIQUE INDEX ? An UNIQUE INDEX ia an index that imposes uniqueness on each value in indexes. The index may be one column or concatenated columns. 60 What is an COMPRESSED INDEX ? A COMPRESSED INDEX is an index for which only enough index information is stored to identify unique enrties; information that an index stores with the previous or following key is “compressed” (truncated) and not stored to reduce the storage overhead required by an index. 599

61. What is an CONCATENATED INDEX ? A CONCATENATED INDEX is one that is created on more than one column of a table. It can be used to guarentee that those columns are unique for every row in the table and to speed access to rows via those columns 62. What is a UNION, UNION ALL,INTERSECTION and MINUS operator ? The UNION operator returns ALL DISTINCT ROWS selected by either query. The UNION ALL operator returns ALL ROWS selected by either query including duplicates. The INTERSECTION operator returns ONLY ROWS that are COMMON to both the queries. The MINUS operator returns ALL DISTINCT ROWS selected only by the first query and not by the second. 63. What does ‘GROUP BY’ statement do ? GROUP BY statement causes a SELECT statement to produce ONE SUMMARY ROW for all selected rows that have identical values in one or more specified column or expressions. Each expe\ressionin the SELECT clause must be one of the following : 1] A CONSANT 2] A Function without parameters 3] A GROUP function like SUM , AVG. 4] Matched IDENTICALLY to a expression in the ‘GROUP BY’ clause. 64. In 2 SELECT statements SELECT A FROM DUAL; and SELECT B FROM DUAL; What will be the difference in using ‘UNION’ and ‘UNION ALL’ ? UNION returns all distinct rows selected by either of the query, whereas UNION ALL returns ALL ROWS selected by either query including duplicates. 64. Give one example where you will use DATABASE TRIGGERS ? For AUDITING purposes we use database triggers. 65. Do you have any idea about ROW-CHAINING ? How will you resolve the issue if there is rowchaining in a table ? When a row NO LONGER FITS WITHIN THE DATABLOCK, it is stored in more than one database block, and that therefore have several row pieces. Resolving: Use ANALYZE to identify chained rows and also provides statistics on the chained rows. Eg: ANALYZE ledger LIST CHAINED ROWS INTO CHAINED_ROWS: (CHAINED_ROWS is a user defined table) For creating chained_rows run the UTLCHAIN.SQL script. 600

66. What is an OPTIIMIZER ? OPTIMIZER is an utility used to determine how to access data requested in the query by the USER or APPLICATION PROGRAM. The output of an optimizer is EXECUTION PLAN. 67. How OPTIMIZATION is done by the Oracle in case of a query ? 1] RULE based, and 2] COST based. 68. What is a] RULE based optimization, b] COST based optimization ? RULE based optimization USES A FIXED SET OF RULES to determine how to access the data. COST based optimization USES STASTISTICS STORED IN THE DATA DICTIONARY WITH CERTAIN RULES to determine how to access the data. Two modes - a] ALL_ROWS, B] FIRST_ROW. With the help of ALTER SESSION SET OPTIMIZER_GOAL = ALL_ROWS / FIRST_ROW, We can alter the modes of cost based optimizer. 69. The KEYWORD comes into the mind immediately when we talk about security ?????? in ORACLE 7.0 ? GRANT. Syntax GRANT privileges( SELECT,INSERT,UPDATE,DELETE,ALTER,INDEX) ON object TO user WITH GRANT OPTION; 70 What KEWORD is used to withdraw the PRIVILEGE you have granted to other user ? REVOKE Syntax: REVOKE privileges ON object FROM users; 71 What is SINGLE INSTANCE ? A single instance can run on a single machine. 72 What is MULTIPLE INSTANCES ? A SINGLE MACHINE can run more than one instance at a time. Each instance is connected to its own database. 73 What is DISTRIBUTED PROCESSING ? Different instances on different machines can communicate with each other using DATABASE LINKS and the DISTRIBUTED option. Oracle supports full two-phase commits which means that inserts, updates and deletes can occur on REMOTE database via a network running SQL*Net. 74 What is PARALLEL PROCESSING ? The Oracle parallel server allows muliple instances to share a single database on a shared disk system. The instance can run on a parallel computer or on different computers in a cluster. 601

75. Difference between SQL and PL/SQL ? SQL is the ANSI industry standard language, used to manipulate information in a relational database. PL/SQL is the procedural language extension to Oracle’s SQL language. SQL PL/SQL 1. It is flexible, Powerful and easy to 1. PL/SQL block can contain any no. of learn. SQL statements combined with the following : 2. It is a non-procedural language. It a] Flow of control statements such as a] Processes set of records rather IF..THEN, ELSE, EXIT and GOTO. than just one at a time and b] Repetition statements such as FOR b] Provides automatic navigation to .. LOOP and WHILE .. LOOP. the data. c] Assignment statements such as X := Y+Z 3. It provides commands for avariety of tasks including : 2. PL/SQL allows you to logically group a] Querying data a set of statements and send them to b] Creating,Updating and Replacing the RDBMS as a single block. objects and Inserting, Updating and Deleting rows. 3. Procedural capabilities. 4] All RDBMS supports SQL Thus one can transfer the skills gained with SQL from one RDBMS to another. Programs written in SQL are portable, they can often be moved from one database to another with little modification.

4. Improved performance. 5. Enhanced productivity 6. Portability 7. Integration with the RDBMS.

76. How to fetch description of a code in the base table block where code is a base table field and the description is a non-base table field ? Use SELECT with INTO clause to fetch the decription value into the NONBASE table field. 77. What is the purpose of OUTER JOIN ? An OUTER JOIN returns all the rows returned by simple join as well as those rows from one table that do not match any row from the other table. The symbol (+) represents the outer join. 78. Difference between EQUI JOIN and OUTER JOIN ?

602

EQUI JOIN returns rows from both the tables provided they both have the same column_name in the where clause. The symbol (=) represents the EQUI JOIN. For OUTER JOIN see previous answer. 79. Define NORMALIZATION ? NORMALIZATION is the process of putting things right, making them normal. It is a part of analysis necessary to understand a business, and build a useful application. The normalization of data ensures a] Minimization of duplication of data. b] Providing flexibility to support different funtional requirements. c] Enabling the model to be translated to database design. STEPS INVOLVED IN NORMALIZATION 1] Ensure that all the ENTITIES are uniquely identified by a combination of attributes. 2] Remove repeated attributes or group of attributes, to place the entities in the first normal form. 3] Remove attributes that are dependent on only part of the identifier. 4] Remove attributes that are dependent on attributes which are not part of the identifier. 80. Define REFERENTIAL INTEGRITY ? REFERENTIAL INTEGRITY is the property that guarantees that values from one column depend on values from another column. This property is enforced through integruty constraints. Referential integrity is the automatic enforcement of referential constraints that exists between a reference table and a referencing table. When referential integrity is enforced , the value of a foreign key exists as a primary key value in the reference table. 81. Explain OUTER JOIN with example ? SELECT DEPT.DEPTNO,DNAME,JOB,ENAME FROM DEPT,EMP WHERE DEPT.DEPTNO = EMP.DEPTNO(+) AND DEPTNO IN (30,40) ORDER BY DEPT.DEPTNO; 82. Explain with example how to use a select statement with GROUP BY HAVING clause ? (or) Where and when is the HAVING clause used and what does it have ? The HAVING clause is coded after the GROUP BY clause in the query that is summarizing results by one or more grouping columns. The HAVING clause behaves the same as 603

the WHERE clause except that it is used to specify the conditions each returned group must satisfy. If one row in the group fails the condition of the HAVNG clause, the entire group is not returned as part of the result. Ex: SELECT MAX(CUSTID), REPID FROM CUSTOMER GROUP BY REPID HAVING COUNT(*) > 2; 83. How do you TUNE SQL statements ? Use OPTIMIZER HINTS for tuning Sql statements. 84. What is the advantage of ENFORCE KEY ? ENFORCE KEY field characterstic indicates the source of the value that SQL*FORMS uses to populate the field 85. What is the Purpose of ERASE command ? ERASE removes an indicated Global variable & releases the memory associated with it

604

.NET Framework 1. Introduction 1.1 What is .NET? That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways". A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability. Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

1.2 Does .NET only apply to people building web-sites? No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you not least ASP.NET.

1.3 When was .NET announced? Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

1.4 When was the first version of .NET released? The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.

1.5 What tools can I use to develop .NET applications? There are a number of tools, described here in ascending order of cost: • .NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.



605

ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.



Microsoft Visual C# .NET Standard 2003: This is a cheap (around $100) version of Visual Studio limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.



Microsoft Visual Studio.NET Professional 2003: If you have a license for Visual Studio 6.0, you can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.

At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.

1.6 What platforms does the .NET Framework run on? The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development. IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home. The Mono project is attempting to implement the .NET framework on Linux.

1.7 What languages does the .NET Framework support? MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop .NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

1.8 Will the .NET Framework go through a standardisation process? From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)."

2. Basic terminology 2.1 What is the CLR? CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article: • Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)

606



Security model



Type system



All .NET base classes



Many .NET framework classes



Development, debugging, and profiling tools



Execution and code management



IL-to-native translators and optimizers

What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

2.2 What is the CTS? CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

2.3 What is the CLS? CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLScompliant types can interoperate with any .NET program written in any language. In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

2.4 What is IL? IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

2.5 What is C#? C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++." Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-). If you are a C++ programmer, you might like to check out my C# FAQ.

2.6 What does 'managed' mean in the .NET context? The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things. Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+). Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword. Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

607

2.7 What is reflection? All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries. Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

3. Assemblies 3.1 What is an assembly? An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing. An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime. Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary. Finally, assemblies are the unit of versioning in .NET - more on this below.

3.2 How can I produce an assembly? The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:

public class CTest { public CTest() { System.Console.WriteLine( "Hello from CTest" ); } } can be compiled into a library assembly (dll) like this:

csc /t:library ctest.cs You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK. Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

608

3.3 What is the difference between a private assembly and a shared assembly? • Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.



Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

3.4 How do assemblies find each other? By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its subdirectories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

3.5 How does assembly versioning work? Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly. The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file. Remember: versioning is only applied to shared assemblies, not private assemblies.

4. Application Domains 4.1 What is an Application Domain? An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

4.2 How does an AppDomain get created? AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.

using System; using System.Runtime.Remoting; 609

public class CAppDomainInfo : MarshalByRefObject { public string GetAppDomainInfo() { return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName; } } public class App { public static int Main() { AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null ); ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" ); CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap()); string info = adInfo.GetAppDomainInfo(); Console.WriteLine( "AppDomain info: " + info ); return 0; } } 4.3 Can I write my own .NET host? Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box (http://staff.develop.com/jasonw/clr/readme.htm ). There is also a code sample in the .NET SDK called CorHost.

5. Garbage Collection 5.1 What is garbage collection? Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away? Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. There is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P =R24819 In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem: http://discuss.develop.com/archives/wa.exe?A2=ind0010A&L=DOTNET& P=R28572 Chris Sells' response to Brian's posting is here: http://discuss.develop.com/archives/wa.exe?A2=ind0010C&L=DOTNET& P=R983

610

5.3 Why doesn't the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap. Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

5.4 Is the lack of deterministic destruction in .NET a problem? It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownershipmanagement mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

5.5 Does non-deterministic destruction affect the usage of COM objects from managed code? Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my class? An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources. Microsoft recommend the following pattern:

public class CTest : IDisposable { public void Dispose() { ... // Cleanup activities GC.SuppressFinalize(this); } ~CTest()

// C# syntax hiding the Finalize()

method { Dispose(); } } In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is

611

a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

612

5.7 Do I have any control over the garbage collection algorithm? A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately.

5.8 How can I find out what the garbage collector is doing? Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to view them.

6. Serialization 6.1 What is serialization? Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

6.2 Does the .NET Framework have in-built support for serialization? There are two separate mechanisms provided by the .NET class library XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter? It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents. SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked. The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

6.4 Can I customise the serialization process? Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field. Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

6.5 Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that

613

XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

6.6 Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is? Look at the InnerException property of the exception that is thrown to get a more specific error message.

7. Attributes 7.1 What are attributes? There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.

[serializable] public class CTest {} The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you've come across Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes? Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:

[AttributeUsage(AttributeTargets.Class)] public class InspiredByAttribute : System.Attribute { public string InspiredBy; public InspiredByAttribute( string inspiredBy ) { InspiredBy = inspiredBy; } } [InspiredBy("Andy Mc's brilliant .NET FAQ")] class CTest { } class CApp { public static void Main() { object[] atts = typeof(CTest).GetCustomAttributes(true); 614

foreach( object att in atts ) if( att is InspiredByAttribute ) Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy ); } } 7.3 Can I create my own context attributes? Yes. Take a look at Don Box's sample (called CallThreshold) at http://www.develop.com/dbox/dotnet/threshold/, and also Peter Drayton's Tracehook.NET at http://www.razorsoft.net/

8. Code Access Security 8.1 What is Code Access Security (CAS)? CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

8.2 How does CAS work? The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set. For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

8.3 Who defines the CAS code groups? Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this:

Level = Machine Code Groups: 1.

All code: Nothing 1.1. Zone - MyComputer: FullTrust 1.1.1. Honor SkipVerification requests: SkipVerification 1.2. Zone - Intranet: LocalIntranet 1.3. Zone - Internet: Internet 1.4. Zone - Untrusted: Nothing 1.5. Zone - Trusted: Internet 1.6. StrongName 00240000048000009400000006020000002400005253413100040000 03 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7 BB5430BA4444FEF8348EBD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08 AC48D69CED0FC8F83B465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE7 2F1660B71927D38561AABF5C 615

AC1DF1734633C602F8F2D5: Everything Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.

8.4 How do I define my own code group? Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:

caspol -ag 1.3 -site www.mydomain.com FullTrust Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:

... 1.3. Zone - Internet: Internet 1.3.1. Site - www.mydomain.com: FullTrust ... Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.

8.5 How do I change the permission set for a code group? Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:

caspol -cg 1.2 FullTrust Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.

8.6 Can I create my own permission set? Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:

caspol -ap samplepermset.xml

Then, to apply the permission set to a code group, do something like this:

caspol -cg 1.3 SamplePermSet

(By default, 1.3 is the 'Internet' code group)

8.7 I'm having some trouble with CAS. How can I diagnose my problem? Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.

8.8 I can't be bothered with all this CAS stuff. Can I turn it off? Yes, as long as you are an administrator. Just run:

caspol -s off

616

9. Intermediate Language (IL) 9.1 Can I look at the IL for an assembly? Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly.

9.2 Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

9.3 How can I stop my code being reverse-engineered from IL? There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL obfuscation tools will become available, either from MS or from third parties. These tools work by 'optimising' the IL in such a way that reverseengineering becomes much more difficult. Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.

9.4 Can I write IL programs directly? Yes. Peter Drayton posted this simple example to the DOTNET mailing list:

.assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } } Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

9.5 Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.

10. Implications for COM 10.1 Is COM dead? This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D =0&P=68241 http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P =R60761 FWIW my view is as follows: COM is many things, and it's different things to different people. But to me, COM is fundamentally about how little blobs of code find other little blobs of code, and how they communicate with each other when they find each other. COM specifies precisely how this location and communication takes place. In a 'pure' .NET world, consisting entirely of .NET objects, little blobs of code still find each other and talk to each other, but they don't use COM to do so. They use a model which is similar to COM in some ways - for example, type information is stored in a tabular form packaged with the component, which is quite similar to packaging a type library with a COM component. But it's not COM. So, does this matter? Well, I don't really care about most of the COM stuff going away - I don't care that finding components doesn't involve a trip to the registry, or that I don't use IDL to define my interfaces. But there is one thing that I wouldn't like

617

to go away - I wouldn't like to lose the idea of interface-based development. COM's greatest strength, in my opinion, is its insistence on a cast-iron separation between interface and implementation. Unfortunately, the .NET framework seems to make no such insistence - it lets you do interface-based development, but it doesn't insist. Some people would argue that having a choice can never be a bad thing, and maybe they're right, but I can't help feeling that maybe it's a backward step.

10.2 Is DCOM dead? Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. Of course DCOM will still be used in interop scenarios.

10.3 Is MTS/COM+ dead? No. The approach for the first .NET release is to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes are provided to try to make this as painless as possible. The PDC release of the .NET SDK includes interop support for core services (JIT activation, transactions) but not some of the higher level services (e.g. COM+ Events, Queued components). Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR. For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P =R68370

10.4 Can I use COM components from .NET programs? Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types. Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:

import "oaidl.idl"; import "ocidl.idl"; [ object, uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206), helpstring("ICppName Interface"), pointer_default(unique), oleautomation ] interface ICppName : IUnknown { [helpstring("method SetName")] HRESULT SetName([in] BSTR name); [helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName ); }; [ 618

uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), version(1.0), helpstring("cppcomserver 1.0 Type Library") ] library CPPCOMSERVERLib { importlib("stdole32.tlb"); importlib("stdole2.tlb"); [ uuid(600CE6D9-5ED7-4B4D-BB49E8D5D5096F70), helpstring("CppName Class") ] coclass CppName { [default] interface ICppName; }; }; When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:

tlbimp cppcomserver.tlb If successful, you will get a message like this:

Typelib imported successfully to CPPCOMSERVERLib.dll You now need a .NET client - let's use C#. Create a .cs file containing the following code:

using System; using CPPCOMSERVERLib; public class MainApp { static public void Main() { CppName cppname = new CppName(); cppname.SetName( "bob" ); Console.WriteLine( "Name is " + cppname.GetName() ); } } Note that we are using the type library name as a namespace, and the COM class name as the class. Alternatively we could have used CPPCOMSERVERLib.CppName for the class name and gone without the using CPPCOMSERVERLib statement. Compile the C# code like this:

csc /r:cppcomserverlib.dll csharpcomclient.cs Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console:

Name is bob 10.5 Can I use .NET components from COM programs? Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW

619

can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry. Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:

using System; namespace AndyMc { [ClassInterface(ClassInterfaceType.AutoDual)] public class CSharpCOMServer { public CSharpCOMServer() {} public void SetName( string name ) { m_name = name; } public string GetName() { return m_name; } private string m_name; } } Then compile the .cs file as follows:

csc /target:library testcomserver.cs You should get a dll, which you register like this:

regasm testcomserver.dll /tlb:testcomserver.tlb /codebase Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:

Dim dotNetObj Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer") dotNetObj.SetName ("bob") MsgBox "Name is " & dotNetObj.GetName() and run the script like this:

wscript comclient.vbs And hey presto you should get a message box displayed with the text "Name is bob". An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box. Go to http://staff.develop.com/jasonw/clr/readme.htm to check it out.

10.6 Is ATL redundant in the .NET world? Yes, if you are writing applications that live inside the .NET framework. Of course many developers may wish to continue using ATL to write C++ COM components that live outside the framework, but if you are inside you will almost certainly want to use C#. Raw C++ (and therefore ATL which is based on it) doesn't have much of a place in the .NET world - it's just too near the metal and provides too much flexibility for the runtime to be able to manage it.

11. Miscellaneous 11.1 How does .NET remoting work? .NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet). Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the

620

.NET runtime Serialization Binary Formatter). But either channel can use either serialization format. There are a number of styles of remote access: • SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.



Singleton. All incoming requests from clients are processed by a single server object.



Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it. Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease. If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net site at http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml.

11.2 How can I get at the Win32 API from a .NET program? Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:

using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)] public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType); public static void Main() { MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 ); } }

621

12. Class Library 12.1 File I/O

12.1.1 How do I read from a text file? First, use a System.IO.FileStream object to open the file:

FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read ); FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This provides a nice interface for processing the stream line by line:

StreamReader sr = new StreamReader( fs ); string curLine; while( (curLine = sr.ReadLine()) != null ) Console.WriteLine( curLine ); Finally close the StreamReader object:

sr.Close();

Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not required.

12.1.2 How do I write to a text file? Similar to the read example, except use StreamWriter instead of StreamReader.

12.1.3 How do I read/write binary files? Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a StreamReader/Writer object.

12.2 Text Processing

12.2.1 Are regular expressions supported? Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title in an HTML file:

FileStream fs = new FileStream( "test.htm", FileMode.Open, FileAccess.Read ); StreamReader sr = new StreamReader( fs );

Regex r = new Regex( "<TITLE>(.*)" ); string s; while( (s = sr.ReadLine()) != null ) { if( r.IsMatch( s ) ) s = r.Replace( s, "<TITLE>New and improved ${1}" ); Console.WriteLine( s ); } 622

12.3 Internet

12.3.1 How do I download a web page? First use the System.Net.WebRequestFactory class to acquire a WebRequest object:

WebRequest request = WebRequest.Create( "http://localhost" ); Then ask for the response from the request:

WebResponse response = request.GetResponse(); The GetResponse method blocks until the download is complete. Then you can access the response stream like this:

Stream s = response.GetResponseStream(); // Output the downloaded stream to the console StreamReader sr = new StreamReader( s ); string line; while( (line = sr.ReadLine()) != null ) Console.WriteLine( line ); Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse objects respectively, to access http-specific functionality.

12.3.2 How do I use a proxy? Two approaches - to affect all web requests do this:

System.Net.GlobalProxySelection.Select = new WebProxy( "proxyname", 80 ); Alternatively, to set the proxy for a specific web request, do this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost" ); request.Proxy = new WebProxy( "proxyname", 80 ); 12.4 XML

12.4.1 Is DOM supported? Yes. Take this example XML document:

Fred Bill This document can be parsed as follows:

XmlDocument doc = new XmlDocument(); doc.Load( "test.xml" ); XmlNode root = doc.DocumentElement; foreach( XmlNode personElement in root.ChildNodes ) Console.WriteLine( personElement.FirstChild.Value.ToString() ); 623

The output is:

Fred Bill

12.4.2 Is SAX supported? No. Instead, a new XmlReader/XmlWriter API is offered. Like SAX it is streambased but it uses a 'pull' model rather than SAX's 'push' model. Here's an example:

XmlTextReader reader = new XmlTextReader( "test.xml" ); while( reader.Read() ) { if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" ) { reader.Read(); // Skip to the child text Console.WriteLine( reader.Value ); } }

12.4.3 Is XPath supported? Yes, via the XPathXXX classes:

XPathDocument xpdoc = new XPathDocument("test.xml"); XPathNavigator nav = xpdoc.CreateNavigator(); XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON"); XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) Console.WriteLine(iterator.Current); 12.5 Threading

12.5.1 Is multi-threading supported? Yes, there is extensive support for multi-threading. New threads can be spawned, and there is a system-provided threadpool which applications can use.

12.5.2 How do I spawn a thread? Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example:

class MyThread { public MyThread( string initData ) { m_data = initData; 624

m_thread = new Thread( new ThreadStart(ThreadMain) ); m_thread.Start(); } // ThreadMain() is executed on the new thread. private void ThreadMain() { Console.WriteLine( m_data ); } public void WaitUntilFinished() { m_thread.Join(); } private Thread m_thread; private string m_data; } In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method:

MyThread t = new MyThread( "Hello, world." ); t.WaitUntilFinished();

12.5.3 How do I stop a thread? There are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.

12.5.4 How do I use the thread pool? By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method:

class CApp { static void Main() { string s = "Hello, World"; ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s ); Thread.Sleep( 1000 ); // Give time for work item to be executed 625

} // DoWork is executed on a thread from the thread pool. static void DoWork( object state ) { Console.WriteLine( state ); } }

12.5.5 How do I know when my thread pool work item has completed? There is no way to query the thread pool for this information. You must put code into the WaitCallback method to signal that it has completed. Events are useful for this.

12.5.6 How do I prevent concurrent access to my data? Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():

class C { public void f() { try { Monitor.Enter(this); ... } finally { Monitor.Exit(this); } } } C# has a 'lock' keyword which provides a convenient shorthand for the code above:

class C { public void f() { lock(this) { ... } } } Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:

626

class C { public void f() { lock( m_object ) { ... } } private m_object = new object(); } 12.6 Tracing

12.6.1 Is there built-in support for tracing/logging? Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

12.6.2 Can I redirect tracing to a file? Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose. Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:

Trace.Listeners.Clear(); FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write ); Trace.Listeners.Add( new TextWriterTraceListener( fs ) ); Trace.WriteLine( @"This will be writen to c:\log.txt!" ); Trace.Flush(); Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.

627

12.6.3 Can I customise the trace output? Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:

class MyListener : TextWriterTraceListener { public MyListener( Stream s ) : base(s) { } public override void WriteLine( string s ) { Writer.WriteLine( "{0:D8} [{1:D4}] {2}", Environment.TickCount m_startTickCount, AppDomain.GetCurrentThreadId(), s ); } protected int m_startTickCount = Environment.TickCount; } (Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.) The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.

13. Resources 13.1 Recommended books I recommend the following books, either because I personally like them, or because I think they are well regarded by other .NET developers. (Note that I get a commission from Amazon if you buy a book after following one of these links.) • Applied Microsoft .NET Framework Programming - Jeffrey Richter Much anticipated, mainly due to Richter's superb Win32 books, and most people think it delivers. The 'applied' is a little misleading - this book is mostly about how the .NET Framework works 'under the hood'. Examples are in C#, but there is also a separate VB edition of the book.

628



Essential .NET Volume 1, The Common Language Runtime - Don Box Don's books don't always demonstrate the same dazzling ability to communicate that he exhibits in person, but they are always chock full of technical detail you just don't get other places. Essential .NET is likely to become a must-read for all .NET developers.



Programming Windows with C# - Charles Petzold Another slightly misleading title - this book is solely about GUI programming Windows Forms and GDI+. Well written, with comprehensive coverage. My only (minor) criticism is that the book sticks closely to the facts, without offering a great deal in the way of 'tips and tricks' for real-world apps.



Developing Applications with Visual Studio.NET - Richard Grimes Covers lots of interesting topics that other books don't, including ATL7,

Managed C++, internationalization, remoting, as well as the more run-of-the-mill CLR and C# stuff. Also a lot of info on the Visual Studio IDE. This book is most suitable for reasonably experienced C++ programmers.



C# and the .NET Platform - Andrew Troelsen Regarded by many as the best all round C#/.NET book. Wide coverage including Windows Forms, COM interop, ADO.NET, ASP.NET etc. Troelsen also has a respected VB.NET book called Visual Basic .NET and the .NET Platform: An Advanced Guide.



Programming Microsoft Visual Basic .NET - Francesco Balena Balena is a reknowned VB-er, and the reviews of his VB.NET book are glowing.



.NET and COM - The Complete Interoperability Guide - Adam Nathan Widely regarded as the bible of .NET/COM interop.



Advanced .NET Remoting - Ingo Rammer Widely recommended.

13.2 Internet Resources • The Microsoft .NET homepage is at http://www.microsoft.com/net/. Microsoft also host GOTDOTNET.



DevX host the .NET Zone.



http://www.cetus-links.org/oo_dotnet.html is a superb set of links to .NET resources.



Chris Sells has a great set of .NET links at http://www.sellsbrothers.com/links/#manlinks.



CSharp.org



microsoft.public.dotnet.* newsgroups



My C# FAQ for C++ Programmers.

13.3 Weblogs The following Weblogs ('blogs') have regular .NET content: • The .NET Guy (Brad Wilson)

629



Charles Cook: Developer of XML-RPC.NET.



Gwyn Cole: Co-author of Developing WMI solutions.



Chris Brumme



Brad Abrams



Don Box



John Lam



Peter Drayton: Co-author of C# Essentials and C# in a Nutshell.



Ingo Rammer: Author of Advanced .NET remoting.



Drew Marsh



Tomas Restrepo



Justin Rudd



Simon Fell: Developer of PocketSOAP.



Richard Caetano



sellsbrothers.com: Windows Developer News: Not really a blog, but includes regular .NET-related news.

13.4 Sample code & utilities Lutz Roeder has some great utilities and libraries at http://www.aisto.com/roeder/dotnet/ Peter Drayton's .NET Goodies page is at http://www.razorsoft.net/ Don Box & Jason Whittington's dm.net COM moniker at http://staff.develop.com/jasonw/clr/readme.htm Mike Woodring has some .NET samples at http://staff.develop.com/woodring/dotnet/ Charles Cook's XML-RPC.Net library is available at http://www.cookcomputing.com/.

630

Interview Tips  Before you take up the interview •

Read your updated bio-data line by line like you review a document or review a piece of code. The onsite team might have reformatted your bio-data to showcase your strengths with respect to the position you will be slotted at. Hence ask the onsite team to send a copy of the bio-data that has been given to the client



Talk to the onsite team before you take the interview. They will be in a position to brief you about the position that you will slotted in and your role and responsibilities



Know the names of the person(s) who will be interviewing you. Also, if you are not clear about the pronunciation, ask the onsite team for the same. It is important that you greet the interviewer(s) using their first names like “Good Morning Tom” or “Hi Michael”.

 Most of the interviewers will start by asking about your background •

Talk about your undergraduate and post-graduate degrees. Explain in brief the stream of your specialization (like graduate in Electrical Engineering and post graduation in Computer Science)



Say when you joined TCS and how long you are associated with TCS. If you have prior work experience, then mention about TCS first and then about your prior work experience

 Next, the interviewers might ask you describe the projects you have worked on.

631



You need to have the bio-data with you. Go through each of the projects in the same sequence as in your bio-data. Explain in brief the following about each of the projects. (Some sample replies are also given for reference).



The application 

“Insurance”, “Banking”, “Finance”, “Accounting” etc.



The functionality of the application in two or three sentences. Ex: “It is an Insurance application to accept quotes and Issue policies” or “It is accounting application with accounts receivable and accounts payable modules”









The technical architecture 

“Two/ Three tier client server architecture”



“web based two/ three tier client server architecture”



“Application runs only on the mainframe” etc.

The platforms (i.e. Hardware) 

If it a three tier client-server architecture, then mention the platforms in each tier.



“Client platform – Windows NT client, Middle tier – “Sun Solaris”, Database tier – Mainframe S/390 or AS 400”



“Client platform – Windows NT, Middle tier and Database tier – “Sun Solaris” etc.



Only “Mainframe S/390”, “AS 400”, etc

The software used in each of the tiers 

“Client – “Browser/ VB Screens/ Power Builder Screens”, “Middle tier –NAS, Websphere, Tuxedo, MTS, etc.”, Database – “DB2, Oracle, Sybase etc”



VS COBOL II, OS/ 390 COBOL, PL/I etc.

The languages you have worked with 



COBOL, C++, Java, Java Script, etc.

Special Software used 

Endeavor, SCLM etc. for configuration management



ODBC/ JDBC for database connectivity



Staffware etc. for workflow



Rational Rose, Designer/ Developer 2000, ERWin etc. for modeling



Any other special software you have worked with

 The roles and responsibilities you have assumed in the projects •

The table below gives some sample replies

Roles

Responsibilities

Team Member

 Coding, preparing test specs, Testing (development)  Apply fixes, test fixes (maintenance)

632

Roles

Responsibilities

Module Leader

 Preparing Design documents (High and Low level design)  Planning with respect to the module  Review of deliverables  Ensuring Quality related activities with respect to the module or completed before the delivery  Any other tasks done by you as a Module leader

Lead Analyst

 Gathering user requirements  Performing analysis of user requirements  Design of application and technical architecture  Data/ Process/ Object Modeling etc  Any other tasks done by you as a analyst

Project Leader

 Project planning  Resource allocation to the modules  Project Monitoring  Status reporting to the clients and TCS management  Review  Configuration Management  Quality related activities with respect to the project  Writing proposals etc

Production Support

 Analyzing bugs  Applying fixes  Testing the fix  Regression Testing

Maintenance and Enhancement Support

 Analyzing bugs and enhancements  Applying fixes and enhancements  Testing the fixes and enhancements  Regression Testing

Please note that the responsibilities are not cast in stone. You might have assumed more responsibilities in a particular role. For example, as a module leader, you might have been part of the requirements gathering team. If such is the case, then make it a point to mention it.

 Questions on the processes •

Be aware of the QMS processes of TCS and those followed in your project. Explain in brief about the process being asked about. Do not talk about the whole QMS processes 

633

“Code, Code review, Code rework, Test, Test Results review”, etc. The whole thing is about Do  Review  Rework  Do …

 Other Questions •







Most of the interviews will be along the above lines. However, some times the interviewer might ask some technical questions on the topic of your expertise, so be prepared for the same. Please be brief and to the point in your replies to these questions. 

“Write a query for …”



Are you aware of the differences between Java and Java Script”



“Have you done normalization and de-normalization”



“How do you react to a severity one problem in production” etc.

There might questions on your strengths. Sample answers are 

“Quick learner”,



“Work well in a team”



“Inquisitive and attempts to gather knowledge about business and technology”



Any other strengths of yours

There might questions on how you keep yourself updated of changes in technology 

Through Continuing Education Program (CEP) of TCS



Through Computer Based Training (CBT’s) of TCS in my free time



Any other avenues you can think of

Also, they might ask for your opinion on various topics like which is better 

“Two-tier Vs three-tier architecture”



“Oracle Vs Sybase” etc.

 Finally

634



The interviewer might ask you if you have any questions or you would like to know anything. It is better to answer “No thanks, the Onsite person/ team has already briefed me”. In case the onsite person/ team was not able to reply to your roles and responsibilities, then you may ask the interviewer for the same



Do not ask the following 

When you are expected to be onsite



Your duration of the assignment



Whether you will get a vacation if you are going long-term



Any other questions that are related to TCS’ HR procedures and policies

Please note that the BRM or the Onsite person/ Team can answer all questions related to TCS and hence please put such questions to these people before the scheduled interview.

 Do and Don’ts •



Do’s 

Talk to the onsite person/ Team or BRM before the scheduled interview



Greet the interviewer(s) before the start of the interview



Be brief in your replies. Explain in detail only when the interviewer asks you to elaborate it.



If you do not able to hear a question, say “Sorry, can you please repeat the question again” or “Beg you pardon, could you repeat the question again please”



Ensure that you use correct grammar while speaking



Say “Thank You” at the end of the interview

Don’ts 

Avoid Indian words “Accha, Teek Hai, Lekin, Han Han...” etc



Avoid use of the same words to confirm that you have understood what has been asked, like “Yes, yes, yes, yes, …” or “Yeah, Yeah, Yeah, …”



Avoid arguments with the interviewer



After you have answered a question if the interviewer pauses and does not ask the next question then wait for the next question. Do not keep talking.



Remember the questions that you should not be asking the interviewer (i.e. the questions under the bullet “Finally”)

The Bottom Line “Be Brief and do not answer or say anything that has not been asked for”

635

Related Documents

Rocks
December 2019 52
Rocks
November 2019 45
Rocks
October 2019 103
Minerals & Rocks
November 2019 47
Igneous Rocks
August 2019 68
Thulium Rocks
August 2019 33