Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Search Your Question

Thursday, July 24, 2008

Yahoo Interview

1) There is a n x n grid of 1's and 0's. Find the i , where i is the row
containing all 1's and all 0's(except the intersection point). Should do
it in less than 25 comparisons
..
2) Use 2 stacks to implement a queue. Followed up with making the
access to the Data structure concurrently.

3) C++ question was good, implement a c++ class such that it allows us
to add data members at runtime.

4)Implement a transaction manager in a database server. The discussion
involved a lot of stuff about transaction logs.

5) How do you tune an application. Creating indexes.

6) Some SQL performance tuning questions on creating indexes.

7) can you write a foo() in c? If so how can u do it?

8) vector implementation questions.

9) Almost everyone asked about my language.(except ppl who attended my talk).

Yahoo Interview Questions

Yahoo Telephonic Round:

Design classes for the following problem. (C++)

A Customer Can have multiple bank accounts A Bank account can be owned by multiple customers When customer logs in he sees list of account, on clicking on an account he sees list of transactions.

Solution :

Customer class, Account class, Transaction class
Customer class contains an array of pointers to the account classes
Account class contains an array of pointers to its owner customer classes
Account class also contains an array of transactions associated to it.
Transaction class contains id or pointer the customer who did that transaction
In customer class write a function with prototype

for (i in Accounts )
{
cout << i.AccountName << endl;
}
cin >> id;
for(i in Accounts[id].transactions )
{
cout << i.TransDetails << endl;
}



Yahoo Interview Round 1:

1. How to call a C++ function which is compiled with C++ compiler in C code?

Solution: The C++ compiler must know that f(int,char,float) is to be called by a C compiler using the extern "C"construct:

The extern "C" line tells the compiler that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn't supported by C, you can't make several overloaded functions simultaneously callable by a C program.

// This is C++ code
// Declare f(int,char,float) using extern "C":
extern "C" void f(int i, char c, float x);
...
// Define f(int,char,float) in some C++ module:
void f(int i, char c, float x)
{
.....
}



2. When you deliver your C++ headers and C++ library of a class (what all can you change in the class so that application using your class does not need to recompile the code)
3. How do you initialize a static member of a class with return value of some function?

Solution :

Static data members are shared by all object instances of that class. Each class instance sees and has access to the same static data. The static data is not part of the class object but is made available by the compiler whenever an object of that class comes into scope. Static data members, therefore, behave as global variables for a class. One of the trickiest ramifications of using a static data member in a class is that it must be initialized, just once, outside the class definition, in the source file. This is due to the fact a header file is typically seen multiple times by the compiler. If the compiler encountered the initialization of a variable multiple times it would be very difficult to ensure that variables were properly initialized. Hence, exactly one initialization of a static is allowed in the entire program.

Consider the following class, A, with a static data member, _id:


//File: a.h
class A
{
public:
A();
int _id;
};

The initialization of a static member is done similarly to the way global variables are initialized at file scope, except that the class scope operator must be used. Typically, the definition is placed at the top of the class source file:

// File: a.cc
int A::_id;

Because no explicit initial value was specified, the compiler will implicitly initialize _id to zero. An explicit initialization can also be specified:


// File: a.cc
int A::_id = 999;


In fact, C++ even allows arbitrary expressions to be used in initializers:

// File: a.cc
int A::_id = GetId();

4. How can one application use same API provided by different vendors at the same time?
5. If you are given the name of the function at run time how will you invoke the function?

Solution :
* Compile your program with --export-dynamic on the gcc command line
* Link with -ldl (dynamic library handling, needed for dlopen and dlsym
* Call dlopen() with a null parameter, meaning you aren't loading symbols from a file but from the current executable
* Call dlsym() with the name of the function you'll be calling. Note that C++ modifies function names, so If you're trying this with C++, you'd have to either declare this function as extern "C", or figure out what name the function has after compiling. (On unix, you could run nm -s on the object file for this).
* If dlsym() returns non-null, use the returned value as a function pointer to invoke your function.

Yahoo Interview Round 2:

1. When will you use shell script/Perl ahead of C/C++?
2. How does yahoo handles billions of requests, does it create a thread per request or a process?
3. How does HTTP works?

Solution :HTTP Is a request-response protocol.

For example, a Web browser initiates a request to a server, typically by opening a TCP/IP connection. The request itself comprises o a request line, o a set of request headers, and o an entity. The server sends a response that comprises o a status line, o a set of response headers, and o an entity. The entity in the request or response can be thought of simply as the payload, which may be binary data. The other items are readable ASCII characters. When the response has been completed, either the browser or the server may terminate the TCP/IP connection, or the browser can send another request.

4. How to count number of unique music titles downloaded from a log file which contains an entry of all music title downloaded?
5. What is the difference between COM and CORBA?

Solution :COM is linked to Microsoft and CORBA to UNIX,Moreover, COM objects require installation on the machine from where it is being used .CORBA is ORB (Object request broker) , and also its a specification owned by OMG, which is open. Not owned by a company. So we cannot say that it only belongs to Unix. Corba servers can run on windows NT, and CORBA clients can run on Unix.

6. What is web service?

Solution :Web Service is defined as "a software system designed to support interoperable Machine to Machine interaction over a network." Web services are frequently just Web APIs that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services.

I got only these two Rounds as of now, if I get any more I will post them here. If you have attended yahoo interview please share your experience and questions with us. You can mail them at kchaitanyya@gmail.com or you can comment here.Solutions for rest of questions will be provided later.if you know any of the questions which are unsolved please comment the solution. we will include.

Yahoo Interview Questions-1

# A modified insertion sort uses binary search to find the position of insertion. What would be the improvement in order realized?

# class a{};
main()
{
count <<>
}
What is the output?

# The linked list size is unknown and it is very large. Find out the N th element from the back end.

# What happens in the following code?
char x[10],y[10];
x=y;

# Design a stack which supports push, pop, min and max operations in O(1).

# Design an NFA to accept a string of 0s and 1s.

# Given a balanced BST tree, write a function to replace the root with a node that belongs to the original tree.

# Explain what this function does


char *mystrcpy(char *s)
{
char des=char [MAXLEN];
char * t=des;
while(*s)
{
*++t=*++s;
}
return t;
}



# Given that you have a server hit by around 400 million users, and you have log files that contain the user ids of all of them. How do you find the frequency of login of each user. (The log files are very huge!!)

# Explain Polymorphism, Encapsulation, Inheritance, operator overloading?

Yahoo Interview Questions-2


# Design a data structure such that given a stream of numbers, you can find the maximum of the numbers at any point and also all the numbers.


# Given an array of 1s and 0s arrange the 1s together and 0s together in a single scan of the array. Optimize the boundary conditions.

# Find the common ancestor of two given nodes in a binary tree, how do you exploit the properties of a given BST for the same problem.

# Given a function getsort(data),that sorts the data given. The function sorts in place and does not use any extra memory. How do you validate the function with respect to 1)it sorts 2) it does not use extra memory

# Explain the Traveling Salesman problem? What is an NP-complete problem? What is the Hamiltonian cycle problem?

# Find out the least common ancestor in a binary tree.

Visual Basic Interview Questions -7

91. 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,

92. What is the default model of the form? And what is it number?


93. Why we need OLE-Automation? Advantages?


94. What methods are used for DBGrid in unbound mode?

AddData, EditData, Readdata, WriteData.

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

96. What is the max size allowed for Max Text box length.

32,000

97. Record set types and Number available in VB?

3.
1- Dynaset, 0 Table, 2 Snap Shot.

98. What is the max size allowed for Max Control Names length?

255.

99. How many procedures are in VB?

2.
function and sub procedures

100. What is the max size allowed for Max label caption length.?

2,048

101. what will be the result for 15/4 and 154 ?

15/4 = 3.75 and 154 = 3

102. What is the max size allowed for Msgbox Prompt and Input Box?

1024

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

104. DSN Less Connection?

"Server=Oracle; Driver={Microsoft ODBC for Oracle};"

105. Visual Basic Interview Questions only

1. 3 main differences between flexgrid control and dbgrid control
2. ActiveX and Types of ActiveX Components in VB
3. Advantage of ActiveX Dll over Active Exe
4. Advantages of disconnected recordsets
5. Benefit of wrapping database calls into MTS transactions
6. Benefits of using MTS
7. Can database schema be changed with DAO, RDO or ADO?
8. Can you create a tabletype of recordset in Jet - connected ODBC database engine?
9. Constructors and distructors
10. Controls which do not have events
11. Default property of datacontrol
12. Define the scope of Public, Private, Friend procedures?
13. Describe Database Connection pooling relative to MTS
14. Describe: In of Process vs. Out of Process component. Which is faster?
15. Difference between a function and a subroutine, Dynaset and Snapshot,early and late binding, image and picture controls,Linked Object and Embedded Object,listbox and combo box,Listindex and Tab index,modal and moduless window, Object and Class,Query unload and unload in form, Declaration and Instantiation an object?
16. Draw and explain Sequence Modal of DAO
17. How can objects on different threads communicate with one another?
18. How can you force new objects to be created on new threads?
19. How does a DCOM component know where to instantiate itself?
20. How to register a component?
21. How to set a shortcut key for label?
22. Kind of components can be used as DCOM servers
23. Name of the control used to call a windows application
24. Name the four different cursor and locking types in ADO and describe them briefly
25. Need of zorder method, no of controls in form, Property used to add a menus at runtime, Property used to count number of items in a combobox,resize a label control according to your caption.
26. Return value of callback function, The need of tabindex property
27. Thread pool and management of threads within a thread pool
28. To set the command button for ESC, Which property needs to be changed?
29. Type Library and what is it's purpose?
30. Types of system controls, container objects, combo box
31. Under the ADO Command Object, what collection is responsible for input to stored procedures?
32. VB and Object Oriented Programming
33. What are the ADO objects? Explain them.
34. What are the different compatibility types when we create a COM component?
35. What do ByVal and ByRef mean and which is the default?
36. What does Option Explicit refer to?
37. What does the Implements statement do?
38. What is OLE and DDE? Explain.
39. What is the difference between Msgbox Statement and MsgboxQ function?
40. What keyword is associated with raising system level events in VB?
41. What methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful?
42. What types of data access have you used.
43. What was introduced to Visual Basic to allow the use of Callback Functions?
44. Which controls can not be placed in MDI?
45. Which controls have refresh method, clear method
46. Which Property is used to compress a image in image control?
47. Which property of menu cannot be set at run time?
48. Which property of textbox cannot be changed at runtime and What's the maximum size of a textbox?
49. Which tool is used to configure the port range and protocols for DCOM communications?
50. What is Dll?
51. Question How many images can be placed in the image list?
52. What is the result of Null * Any value = 0 (Zero)?


Visual Basic Interview Questions -6

76. What are the type of validation available in VB?

Field, Form

77. How to trap Data Base Error?

Dim x as RDOError
X(0).Des
X(1).Number

Setting the Cursors.
Default Cursor 0
ODBC Cursor (Client side) 1
ServerSide Cursors (More Network traffic) - 2

78. How to declare Dll Procedure?

Declare function "" lib ""
Alias "" (Arg, ..) as Return type.

79. Referential Integrity (Take care By jet database Engine). Cascade Delete, Cascade Update is done setting property of Attributes.?

DbRelationDeleteCascade, DbRelationUpdateCascade.

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

81. Name some date function?

Dateadd(), Datediff(), Datepart(), Cdate()

82. What is difference between datagrid and flexgrid?

Datagrid Editable. Flexigrid Non-Editable. (Generally used for Read only purpose.)

83. What are two validate with Data Control?

Data_Validate, Data_Error.

84. To connect the Data Control with Back end What are all the properties to be set?

Data source Name, Record Source Name

85. What are the Technologies for Accessing Database from Visual Basic?set?

DAO, Data Control, RDO, ODBCDIRECT, ADO, ODBC API , 0040.

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

87. What is Mask Edit and why it is used?

Control. Restricted data input as well as formatted data output.

88. What is RdExecDirect?

Bypasses the Creation of a stored procedure to execute the query. Does not apply to Oracle.

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

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

Visual Basic Interview Questions -5

61. What is keyword used to compare to objects?

ISOperator Returns Boolean.

62. Suppose from form1 to form2 object property settings will arise to ?

Invalid procedure call or argument (Run time error 5)

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

64. What is Implicit?

Instance of specific copy of a class with its own settings for the properties defined in that class.
Note: The implicitly defined variable is never equal to nothing.

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

66. Where will we give the option explicit keyword and for what?

In the general declarations section. To trap undeclared variables.

67. How can we call Stored procedure of Back End in RDO and ADO ?

In RDO We can call using RDO Query Objects.
In ADO We can call using Command Objects.

68. What is Static Cursor?

In ADO Snap Shot is called so.

69. How to check the condition in Msgbox?

If(Msgbox("Do you want to delete this Record",VbYesNo)=VbYes)Then End if

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

71. 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:
Binding Procedure Early and Late Binding ( Can be Remove from the Memory).

72. What is the diff. Between function and sub procedures?

Function will return value but a sub procedure wont return values

73. What is the max size allowed for Extension in Visual Basic?

Frm, bas, cls, res, vbx, ocx, frx, vbp, exe

74. What is FireHouse Cursors?

Forward Only Some time Updateable

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


courtesy:DEVFYI - Developer Resource - FYI

Visual Basic Interview Questions -4

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

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

48. Can us able to set Instancing properties like Singleuse, GlobalSingleuse to ActiveXDll?

No.

49. What are properties available in Clip Board?
No Properties Available. Only the methods they are SetText, GetText, Setdata(), Getformat(), Clear

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

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

52. What is MAPI ?

Messaging Application programming Interface.

53. What is MDI form?

MDI Styles?

54. What are the locks available in Visual Basic?

Locking is the process by which a DBMS restricts access to a row in a multi-user environment 4 types of locks. They are
1. Batch Optimistic
2. Optimistic
3. Pessimistic
4. 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.

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

56. What is Tabstrip control?

Libraries of procedure external to the application but can be called from the application.

57. What is Static Variable?

Its Scope will be available through out the life time.

58. What is DBSqlPassThrough?

It will By Passing the Jet Query Processor.

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

60. What is Parser Bug?

It is difficult to use database objects declared in a module from within a form.
courtesy:DEVFYI - Developer Resource - FYI

Visual Basic Interview Questions -3


31. What are the Style Properties of Combo Box?

Simple, Dropdown list We can type and select. Dropdown Combo Only Drop Down.

32. What are the Style properties of List Box?

Simple Single Select , Extended. Multiple Select.

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

34. 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.
Get- Assigns the value of an expression to a variable or property.

35. How to change the Mouse Pointer?

Screen.MousePointer = VBHourGlass/VBNormal.

36. What is Friend Variable?

Scope sharable between projects.

37. What is DBFailError?
Rolls Back updates if any errors Occurs

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

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

40. Diff types of Lock Types?

RdConcurReadOnly 0 (Default)
RdConcurLock 1 (Pessimistic Locking)
RdConcurRowver 2 (Optimistic Lociking)
RdConcurValues 3
RdConcurBatch 4

41. What are the scopes of the class?

Public, private, Friend

42. Have you create Properties and Methods for your own Controls?

Properties Public variable of a Class
Method Public procedure of a class

43. Private Dim x as integer. Valid ?

Private cannot be used in front of DIM.

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

45. What are the different types of Dialog Box?

Predefined, Custom, User Defined.

courtesy:DEVFYI - Developer Resource - FYI

Visual Basic Interview Questions -2

6. What are the main components of the ADO object model? How are they used?

Connection: Used to make a connection between your app and an external data source, ie, sql server.Command: Used to build queries, including user-specific parameters, to access records from a data source (which are returned in a Recordset)Recordset:Used to access records returned from an SQL query. With a recordset, you can navigate returned records. You can also add, modify or delete records.

17. Can We create CGI scripts in VB??

Yes.

18. Dim x, y as integer. What is x and y data type?

X as variant and y as integer.

19. What is Centralization Error Handling?

Writing function and calling it when error occurs.

20. What is frx?

When some controls like grid and third party control placed in our application then it will create frx in run time.

21. What is the Dll required for running the VB?

Vbrun300.dll

22. Why we use Treeview Control?

To list the hierarchical list of the node objects. Such of files and Directories.

23. Handling Error in Calling chain.

This will call the top most error where the error is handled.

24. In project properties if we set Unattended what is it mean?

This cannot have user interface. This can be used for the COM creation.

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

26. What is view Port?

The area under which the container provides the view of the ActiveX Document is known as a view port.

27. What are the different types of error?

Syntax Errors, Runtime , Logic.

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

29. What is Mixed Cursors?

Static + Keyset

30. 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 position in the target to another.

Visual Basic Interview Questions -1

1. How do you register a component?

Compiling the component, running REGSVR32 MyDLL.dll

2. Name and explain the different compatibility types when creating a COM component

No Compatibility ? New GUID created, references from other components will not workProject Compatibility ? Default for a new component Binary Compatibility ? GUID does not change, references from other components will work

3. Why iss it important to use source control software for source code?
Modification history.Code ownership: Multiple people can not modify the same code at the same time.

4. What two methods are called from the ObjectContext object to inform MTS that the transaction was successful or unsuccessful?

SetComplete and SetAbort.

5. What is the tool used to configure the port range and protocols for DCOM communications?

DCOMCONFIG.EXE

6. What does Option Explicit refer to?

All variables must be declared before use. Their type is not required.

7. What are the different ways to Declare and Instantiate an object in Visual Basic 6?

Dim obj as OBJ.CLASS with eitherSet obj = New OBJ.CLASS orSet obj = CreateObject(OBJ.CLASS?) orSet obj = GetObject( , OBJ.CLASS?)orDim obj as New OBJ.CLASS

8. Name the four different cursor types in ADO and describe them briefly.

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 detectedDynamic ? All changes are visible.

9. Name the four different locking type in ADO and describe them briefly.

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. Can not alter the data.

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

11. What are the ADO objects?
Provide a scenario using three of them to return data from a database. Expected answer: Connection Connects to a data source; contains the Errors collectionCommand Executes commands to the data source. Is the only object that can accept parameters for a stored procedure.Recordset The set of data returned from the database.Scenario: There are many possibilities. The most likely is as follows:Dim conn As ADODB.ConnectionDim rs As ADODB.RecordsetDim Cmd As ADODB.Commandconn.ConnectionString = ?CONNECTION STRING?conn.OpenSet Cmd.ActiveConnection = connCmd.CommandText = ?SQL STATEMENT?Set rs = Cmd.ExecuteSet rs.ActiveConnection = Nothingconn.Close

12. Under the ADO Command Object, what collection is responsible for input to stored procedures?

The Parameters collection.

13. What are some benefits of using MTS?

Database Pooling, Transactional operations, Deployment, Security, Remote Execution.

14. What is the 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.

15. 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 marshalled across process boundaries. A single instance of an out of process component can service many clients.

SQL Interview Questions -8

121. What is the difference between file server and a database server ?

A file server just transfers all the data requested by all its client and the client processes the data while a database server runs the query and sends only the query output.

122. What is inheritance ?

Inheritance is a method by which properties and methods of an existing object are automatically passed to any object derived from it.

123. What are the two components of ODBC ?

1. An ODBC manager/administrator and
2. ODBC driver.

124. What is the function of a ODBC manager ?

The ODBC Manager manages all the data sources that exists in the system.

125. What is the function of a ODBC Driver ?

The ODBC Driver allows the developer to talk to the back end database.

126. What description of a data source is required for ODBC ?

The name of the DBMS, the location of the source and the database dependent information.

127. How is a connection establised by ODBC ?

ODBC uses the description of the datasource available in the ODBC.INI file to load the required drivers to access that particular back end database.

SQL Interview Questions -7

101. What does the term downsizing refer to ?

A host based application is re-engineered to run in smaller or LAN based environment.

102. What is event trigger ?

An event trigger, a segment of code which is associated with each event and is fired when the event occurs.

103. Why do stored procedures reduce network traffic ?

When a stored procedure is called, only the procedure call is sent to the server and not the statements that the procedure contains.

104. What are the types of processes that a server runs ?

Foreground process and Background process.

105. What is a event handler ?

An event handler is a routine that is written to respond to a particular event.

106. What is an integrity constraint ?

An integrity constraint allows the definition of certain restrictions, at the table level, on the data that is entered into a table.

107. What are the various uses of database triggers ?

Database triggers can be used to enforce business rules, to maintain derived values and perform value-based auditing.

108. What is a transaction ?

A transaction is a set of operations that begin when the first DML is issued and end when a commit or rollback is issued. BEGIN COMMIT/ROLLBACK are the boundries of a transaction.

109. Why are the integrity constraints preferred to database triggers ?

Because it is easier to define an integrity constraint than a database trigger.

110. Why is it better to use an integrity constraint to validate data in a table than to use a stored procedure ?

Because an integrity constraint is automatically checked while data is inserted into a table. A stored has to be specifically invoked.

111. What are the three components of a client server model ?

A Client,
A Server and
A Network/Communication software.

112. What are the advantages of client/server model ?

Flexibility of the system, scalability, cost saving, centralised control and implementation of business rules, increase of developers productivity, portability, improved network and resource utilization.

113. What are the disadvantages of the client/server model ?

Heterogeneity of the system results in reduced reliablity. May not be suitable for all applications. Managing and tuning networks becomes difficult.

114. What are the different topologies available for network ?

Star,
Bus,
Ring.

115. What is the first work of Client process ?

A client process at first establishes connection with the Server.

115. What are the responsibilities of a Server ?

1. Manage resources optimally across multiple clients.
2. Controlling database access and security.
3. Protecting the databse and recovering it from crashes.
4. Enforcing integrity rules globally.

116. In a Client/Server context, what does API (Application Programming Interface) refer to ?

An API, in a Client/Server context, is a specification of a set of functions for communication between the client and the server.

117. Give some examples of standard API??s ?

Open Database Connectivity (ODBC),
Integrated Database Application Programming Interface (IDAPI),
XOpen
SQL/CLI

118. What is the main advantage of developing an application using an API ?

The application can be connected to any back end server that is supported by the API.

119. What is the main disadvantage of developing an application using an API ?

The application cannot use any special features of the backend server.

120. Why is an event driven program referred to a passive program ?

Because an event driven program is always waiting for something to happen before processing.

SQL Interview Questions -6

81. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;

83. Examine this database trigger
52. CREATE OR REPLACE TRIGGER prevent_gross_modification
53. {additional trigger information}
54. BEGIN
55. IF TO_CHAR(sysdate, DY) = MON
56. THEN
57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
58. END IF;
59. END;

This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt

84. Examine this function:
61. CREATE OR REPLACE FUNCTION set_budget
62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
63. BEGIN
64. UPDATE studio
65. SET yearly_budget = v_new_budget
WHERE id = v_studio_id;

IF SQL%FOUND THEN
RETURN TRUEl;
ELSE
RETURN FALSE;
END IF;

COMMIT;
END;

Which code must be added to successfully compile this function?
1. Add RETURN right before the IS keyword.
2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.

85. Under which circumstance must you recompile the package body after recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY 2. DBMS_OUTPUT 3. DBMS_LIST 4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?
1. Any DML statements issued by the construct are still pending and can be committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section, the construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.

89. Examine this code
71. BEGIN
72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73. END;

For this code to be successful, what must be true?
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.

90 A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?

1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ?

Method 1:

Select length (translate (trim (column_name),' +-.0123456789',' ')) from dual ;

Will give you a zero if it is a number or greater than zero if not numeric (actually gives the count of non numeric characters)

Method 2:

select instr(translate('wwww',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),'X')
FROM dual;

It returns 0 if it is a number, 1 if it is not.

92 How to Select last N records from a Table?

select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm)
where a > ( select (max(rownum)-10) from clm)

Here N = 10

The following query has a Problem of performance in the execution of the following query where the table ter.ter_master have 22231 records. So the results are obtained after hours.

Cursor rem_master(brepno VARCHAR2) IS
select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno = 'ALL' or a.repno > brepno)
Order by a.repno

What are steps required tuning this query to improve its performance?

-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO

-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:

SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno = 'ALL' or a.repno > a.brepno)
ORDER BY a.repno;

93 What is the difference between Truncate and Delete interms of Referential Integrity?

DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependent child records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it only checks for the existence (and status) of another foreign key Pointing to the table. If one exists and is enabled, then you will get The following error. This is true even if you do the child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing the TRUNCATE command, then re-enable them afterwards.

94. What does preemptive in preemptive multitasking mean ?

Preemptive refers to the fact that each task is alloted fixed time slots and at the end of that time slot the next task is started.

95. What does the OLTP stands for ?

OLTP stands for On Line Transaction Processing

96. What is the most important requirement for OLTP ?

OLTP requires real time response.

97. In a client server environment, what would be the major work that the client deals with ?

The client deals with the user interface part of the system.

98. Why is the most of the processing done at the sever ?

To reduce the network traffic and for application sharing and implementing business rules.

99. What does teh term upsizing refer to ?

Applications that have outgrown their environment are re-engineered to run in a larger environment. This is upsizing.

100. What does one do when one is rightsizing ?

With rightsizing, one would move applications to the most appropriate server platforms.

SQL Interview Questions -5

60.What is CYCLE/NO CYCLE in a Sequence?

CYCLE specifies that the sequence continue 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.

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

62. Can a view be updated/inserted/deleted? If Yes - under what conditions?

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.

63. 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 and these tables are the base tables of a view, then the changes will be reference on the view.

64. Which of the following statements is true about implicit cursors?

1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.

65. Which of the following is not a feature of a cursor FOR loop?

1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?

1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?

1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?

1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT

69. Which line in the following statement will produce an error?

1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is

1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement

1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values

72. Read the following code:
10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT

73. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;

The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?

1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?

1. Only one
2. All that apply
3. All referenced
4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?

1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS

v_yearly_budget NUMBER;

BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;

RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER

31. CREATE OR REPLACE PROCEDURE update_theater
32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33. BEGIN
34. UPDATE theater
35. SET name = v_name
36. WHERE id = v_theater_id;
37. END update_theater;

79. When invoking this procedure, you encounter the error:
ORA-000: Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:
40. CREATE OR REPLACE PROCEDURE calculate_budget IS
41. v_budget studio.yearly_budget%TYPE;
42. BEGIN
43. v_budget := get_budget(11);
44. IF v_budget <>
45. THEN
46. set_budget(11,30000000);
47. END IF;
48. END;

You are about to add an argument to CALCULATE_BUDGET. What effect will this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.

SQL Interview Questions -4

41. What is a join? Explain the different types of joins?

Join is a query, which retrieves related columns or rows from multiple tables.
Self Join - Joining the table with itself.
Equi Join - Joining two tables by equating two common columns.
Non-Equi Join - Joining two tables by equating two common columns.
Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.

42. What is the sub-query?

Sub-query is a query whose return values are used in filtering conditions of the main query.

43. What is correlated sub-query?

Correlated sub-query is a sub-query, which has reference to the main query.

44. Explain CONNECT BY PRIOR?

Retrieves rows in hierarchical order eg.
select empno, ename from emp where.

45. Difference between SUBSTR and INSTR?

INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th occurrence of the string 2 in string1. The search begins from nth position of string1.
SUBSTR (String1 n, m)
SUBSTR returns a character string of size m in string1, starting from n-th position of string1.

46. Explain UNION, MINUS, UNION ALL and 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.

47. What is ROWID?

ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

48. What is the fastest way of accessing a row in a table?
Using ROWID.
CONSTRAINTS

49. What is an integrity constraint?

Integrity constraint is a rule that restricts values to a column in a table.

50. What is referential integrity constraint?

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.

51. What is 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.

52. What is ON DELETE CASCADE?

When ON DELETE CASCADE is specified Oracle maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.

53. What are the data types allowed in a table?

CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?

CHAR pads blank spaces to the maximum length.
VARCHAR2 does not pad blank spaces.
For CHAR the maximum length is 255 and 2000 for VARCHAR2.

55. 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 column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

56. What are the pre-requisites to modify datatype of a column and 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.

57. Where the integrity constraints are stored in data dictionary?

The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?

The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

59. If 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.

60. What is a database link?

Database link is a named path through which a remote database can be accessed.

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

SQL Interview Questions -3

21. Which command executes the contents of a specified file?

START or @.

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

23. Which command displays the SQL command in the SQL buffer, and then executes it?

RUN.

24. What command is used to get back the privileges offered by the GRANT command?

REVOKE.

25. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.

Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?

MONTHS_BETWEEN.

27. What operator performs pattern matching?

LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command?

It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?

IS NULL operator.

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

31. Which function is used to find the largest integer less than or equal to a specific value?

FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?

Data Definition Language (DDL).

33. What is the use of DESC in SQL?

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.

34. What command is used to create a table by copying the structure of another table?

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.

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

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?

1200.

37. What are the wildcards used for pattern matching.?

_ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?

&

39. What's an SQL injection?

SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

40. What is difference between TRUNCATE & DELETE

TRUNCATE commits after deleting entire table i.e., cannot 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.

SQL Interview Questions -2

1. The most important DDL statements in SQL are:

CREATE TABLE - creates a new database table

ALTER TABLE - alters (changes) a database table

DROP TABLE - deletes a database table

CREATE INDEX - creates an index (search key)

DROP INDEX - deletes an index


2. Operators used in SELECT statements.

= Equal
<> or != Not equal
> Greater than
<>= Greater than or equal
<= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern

3. SELECT statements:

SELECT column_name(s) FROM table_name
SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value
Note that single quotes around text values and numeric values should not be enclosed in quotes. Double quotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records.

SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE column_name operator value

5. The INSERT INTO Statements:

INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:

UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:

DELETE FROM table_name WHERE column_name = some_value
Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:

SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND

SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

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

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

18. What will be the output of the following query?
SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;?
TROUBLETHETROUBLE. p>

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

SQl Job Interview Questions

SQL
SQL is an English like language consisting of commands to store, retrieve, maintain & regulate access to your database.

SQL*Plus
SQL*Plus is an application that recognizes & executes SQL commands & specialized SQL*Plus commands that can customize reports, provide help & edit facility & maintain system variables.

NVL
NVL : Null value function converts a null value to a non-null value for the purpose of evaluating an expression. Numeric Functions accept numeric I/P & return numeric values. They are MOD, SQRT, ROUND, TRUNC & POWER.

Date Functions
Date Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY, MONTHS_BETWEEN & SYSDATE.

Character Functions
Character Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additional functions are GREATEST & LEAST. Group Functions returns results based upon groups of rows rather than one result per row, use group functions. They are AVG, COUNT, MAX, MIN & SUM.

TTITLE & BTITLE
TTITLE & BTITLE are commands to control report headings & footers.

COLUMN
COLUMN command define column headings & format data values.

BREAK
BREAK command clarify reports by suppressing repeated values, skipping lines & allowing for controlled break points.

COMPUTE
command control computations on subsets created by the BREAK command.

SET
SET command changes the system variables affecting the report environment.

SPOOL
SPOOL command creates a print file of the report.

JOIN
JOIN is the form of SELECT command that combines info from two or more tables.
Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.
Equijoin returns rows from two or more tables joined together based upon a equality condition in the WHERE clause.
Non-Equijoin returns rows from two or more tables based upon a relationship other than the equality condition in the WHERE clause.
Outer Join combines two or more tables returning those rows from one table that have no direct match in the other table.
Self Join joins a table to itself as though it were two separate tables.

Union
Union is the product of two or more tables.

Intersect
Intersect is the product of two tables listing only the matching rows.

Minus
Minus is the product of two tables listing only the non-matching rows.

Correlated Subquery
Correlated Subquery is a subquery that is evaluated once for each row processed by the parent statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart questions whose answer depends on the value in each row processed by parent statement.

Multiple columns
Multiple columns can be returned from a Nested Subquery.

Sequences
Sequences are used for generating sequence numbers without any overhead of locking. Drawback is that after generating a sequence number if the transaction is rolled back, then that sequence number is lost.

Synonyms
Synonyms is the alias name for table, views, sequences & procedures and are created for reasons of Security and Convenience.
Two levels are Public - created by DBA & accessible to all the users. Private - Accessible to creator only. Advantages are referencing without specifying the owner and Flexibility to customize a more meaningful naming convention.

Indexes
Indexes are optional structures associated with tables used to speed query execution and/or guarantee uniqueness. Create an index if there are frequent retrieval of fewer than 10-15% of the rows in a large table and columns are referenced frequently in the WHERE clause. Implied tradeoff is query speed vs. update speed. Oracle automatically update indexes. Concatenated index max. is 16 columns.

Data types
Max. columns in a table is 255. Max. Char size is 255, Long is 64K & Number is 38 digits.
Cannot Query on a long column.
Char, Varchar2 Max. size is 2000 & default is 1 byte.
Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.
Long Character data of variable length upto 2GB.
Date Range from Jan 4712 BC to Dec 4712 AD.
Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.
Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.

Order of SQL statement execution
Where clause, Group By clause, Having clause, Order By clause & Select.

Transaction
Transaction is defined as all changes made to the database between successive commits.

Commit
Commit is an event that attempts to make data in the database identical to the data in the form. It involves writing or posting data to the database and committing data to the database. Forms check the validity of the data in fields and records during a commit. Validity check are uniqueness, consistency and db restrictions.

Posting
Posting is an event that writes Inserts, Updates & Deletes in the forms to the database but not committing these transactions to the database.

Rollback
Rollback causes work in the current transaction to be undone.

Savepoint
Savepoint is a point within a particular transaction to which you may rollback without rolling back the entire transaction.

Set Transaction
Set Transaction is to establish properties for the current transaction.

Locking
Locking are mechanisms intended to prevent destructive interaction between users accessing data. Locks are used to achieve.

Consistency
Consistency : Assures users that the data they are changing or viewing is not changed until the are thro' with it.

Integrity
Assures database data and structures reflects all changes made to them in the correct sequence. Locks ensure data integrity and maximum concurrent access to data. Commit statement releases all locks. Types of locks are given below.
Data Locks protects data i.e. Table or Row lock.
Dictionary Locks protects the structure of database object i.e. ensures table's structure does not change for the duration of the transaction.
Internal Locks & Latches protects the internal database structures. They are automatic.
Exclusive Lock allows queries on locked table but no other activity is allowed.
Share Lock allows concurrent queries but prohibits updates to the locked tables.
Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.
Row Exclusive same as Row Share but prohibits locking in shared mode.
Shared Row Exclusive locks the whole table and allows users to look at rows in the table but prohibit others from locking the table in share or updating them.
Share Update are synonymous with Row Share.

Deadlock
Deadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for a locked resource. First user needs a resource locked by the second user and the second user needs a resource locked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the same sequence and use Commit frequently to release locks.

Mutating Table
Mutating Table is a table that is currently being modified by an Insert, Update or Delete statement. Constraining Table is a table that a triggering statement might need to read either directly for a SQL statement or indirectly for a declarative Referential Integrity constraints. Pseudo Columns behaves like a column in a table but are not actually stored in the table. E.g. Currval, Nextval, Rowid, Rownum, Level etc.

SQL*Loader
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To load data from external files into an Oracle database, two types of input must be provided to SQL*Loader : the data itself and the control file. The control file describes the data to be loaded. It describes the Names and format of the data files, Specifications for loading data and the Data to be loaded (optional). Invoking the loader sqlload username/password controlfilename .

Solutions to C programming questions

1 solution) gives compiler error because of post increment on an expression and it it valid only on variable


2 solution) 9 9 56



3 solution) ans1: x*=y+1;
ans2:x*=++y,y--;



4 solution) emptystring or nthing



5 solution) First call can take an integer as input whether or not you put any spaces/newlines/white space characters before it.
But the second call expects at least one ' ' [ space ] character and then some/none white space characters and then an integer.



6 solution) 16


7 solution) 1111


8 solution) prints the numbers in 2 rows each containing 10 elements with in between spaces


9 solution) it won't because of overflow in the statement *a=*a+*b;


10 solution) 4 8


11 solution) 987641

12 solution) 2 1 2

13 solution) unsigned/**/int/**/p;


14 solution) 3 3 5 5


15 solution) output1:2 3
output2:2 4


16 solution) 111


17 solution) 82


18 solution) segmentation fault


19 solution) 15


20 solution) (nil)


21 solution) It prints the lower case letters present in the input


22 solution) 3 1


23 solution) 12
concatinate(1,2)


24 solution) *1 -> replacing '<' with '+' in the declaration of the loop #include
int main(){
int n = 42;
for(int i = 0; i + n; i-- )
printf("-");
return 0;
}
* 2 -> replacing n with i in the declaration of the loop
#include
int main(){
int n = 42;
for(int i = 0; i <> adding a '-' before i in the comparison in for loop
#include
int main(){
int n = 42;
for(int i = 0; -i < href="http://placementsindia.blogspot.com/2007/10/c-programming-questions.html">

Modified Array based QuickSort with respect to the Partition Strategy

Recall that the linked-list version of quicksort() puts all items whose keys are equal to the pivot's key into a third queue, which doesn't need to be sorted. This can save much time if there are many repeated keys.

The array-based version of quicksort() does not treat items with equal keys specially, so those items are sorted in the recursive calls.

Is it possible to modify array-based quicksort() so that the array is partitioned into three parts (keys less than pivot, keys equal to pivot, keys greater than pivot) while still being in-place? (The only memory you may use is the array plus a constant amount of additional memory.)

Why or why not?

Solution:In the first place,whatever I put here is only my approach to solve this problem and much better solution might exist.Now getting on to the solution..

In linked list implementation,we simply modify the pointers so that we end up with 3 lists.One list L1 to contain all the keys less than pivot ,one L2 with keys equal to the pivot and the other L3 with keys greater than pivot.Hence what we require is only an additional head pointer which points to this list L3 containing all elements equal to the pivot.SO we do not require any significant additional memory !!

But this is not the case with array implementation wherein we are confronted by difficulties arising from fixed size of array .If at all we want to maintain a list of keys equal to the pivot, then we need to maintain a separate array and also need to remove all those from the original array,which means a herder's task.


We will do it in much simpler way.Whenever,a duplicate entry of pivot is encountered by the left pointer,swap it with some element ,smaller than pivot and positioned to its left.Hence we move all the pivots encountered by the left pointer to the left extreme of the array. Similarly move all the pivots encountered by the right pointer to the right side of the array.
Now we have all the elements equal to the pivot on either extreme ends of the array.
In the middle,we have remaining 2 sub-arrays.Now the array looks like this
L2-left L1 L3 L2-right
Now get all these pivot elements in the left extreme (L2-left) to occupy the positions preceding L3 by swapping with those elements on the right portion of the first list L1.Similarly do swaps to get L2-right next to L2-Left by swapping its elements with those elements on the left portion of 3rd list L3.Now we have array in the form L1,L2,L3 where L2-left and L2-right are joined into one.

Now we can recursively sort L2-left and L2-right.

I am also putting the code of normal array based quicksort and this modified version ,so that once can verify it.





int leftpivotcounter=0; //global variable
int rightpivotcounter=0; //global variable
// these 2 are the only additional space used to accomplish the task in modified quicksort.


void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void normal_quicksort(int *arr,int left,int right)
{
if(left>=right)
return;
else if(right-left==1)
{
if(arr[left]>arr[right])
swap(arr+left,arr+right);
}
else
{
swap(arr+(left+right)/2,arr+right);
int rpos=right,lpos=left;
int pivot=arr[right--];
while(left {
while(left left++;
while(right>=lpos &&arr[right]>=pivot )
right--;
if(left <=right )
{
swap(arr+left,arr+right);
}
else if (left > right )
{

swap(arr+right+1,arr+rpos);

partition(arr,lpos,right);
partition(arr,right+2,rpos);
break;
}

}
}
}


void modified_quicksort(int *arr,int left,int right)
{
if(left>=right)
return;
else if(right-left==1)
{
if(arr[left]>arr[right])
swap(arr+left,arr+right);
}
else
{
swap(arr+(left+right)/2,arr+right);
int rpos=right,lpos=left;
leftpivotcounter=lpos-1;
rightpivotcounter=rpos;
int pivot=arr[right--];
while(left {
while(left {
if(arr[left]==pivot)
{
leftpivotcounter++;
swap(arr+leftpivotcounter,arr+left);
}
left++;
}
while(right>=lpos &&arr[right]>=pivot )
{
if(arr[right]==pivot)
{
rightpivotcounter--;
swap(arr+rightpivotcounter,arr+right);
}
right--;
}
if(left <=right )
{
swap(arr+left,arr+right);
}
else if (left > right )
{
swap(arr+right+1,arr+rpos);
for(int i=0;(i+lpos<=leftpivotcounter) &&((2*i) {
swap(arr+lpos+i,arr+right-i);
}
for(int i=0;(rpos-i-1>=rightpivotcounter) && (rpos > right+3+2*i) ;i++)
{
swap(arr+rpos-1-i,arr+right+2+i);
}
partition(arr,lpos,right-(leftpivotcounter-lpos+1));
partition(arr,right+2+(rpos-rightpivotcounter),rpos);
break;
}

}
}
}

Last Non Zero Digit of Factorial

Question Write a program that can compute the last non-zero digit of any factorial for ( 0 <= N <= 10000). For example, if your program is asked to compute the last nonzero digit of 5!, your program should produce 2 because 5! = 120, and 2 is the last nonzero digit of 120.

Solution:Well if one has thoroughly gone through the post,
the answer is easy to arrive at.Since the question asks only about the last non Zero digit,we need not bother about calculating the whole factorial and can just keep track of last nonzero digit by writing nonzerodigit(N)=nonzerodigit(N* nonzerodigit(N-1)).

Here follows the last nonzero digits of first 5 numbers.
N factorial Last Non Zero Digit

1! 1
2! nonzerodigit(2*1)=2
3! nonzerodigit(3*2)=6
4! nonzerodigit(4*6)=4
5! nonzerodigit(4*5)=2!!!(one gets zero if only the last digit is tracked)

So ,it should be clear the mere tracking of last digit is not enough but we need to track some K digits in each factorial.
So we track the last K digits of factorial of each number and store them in a vector V.
At the same time we want to have minimum K.
A brief thought would suggest that we should track of that many no of digits such that for all numbers <=1000 we should never encounter a 0 in V.

This means K is 1+ maximum no of zeros one would encounter in N! for N<=1000.

In this particular case K is 1+5 (maximum no of zeros is 5 since 5^5=3125 and 5^6>10000).

So track the last 6 digits of each of the factorials.Thus we arrived at the solution!!

Question If you have already solved the above problem, then give a generalized method to find the last X non-zero digits of N factorial

Solution:This question is similar to the above one except that we need to track X-1 more digits of N! .
so answer to this is X+No of zeros in N! factorial.

Quick Sort routine to find the kth smallest element in an array

Question Describe an efficient algorithm based on Quicksort that will find the element of a set that would be at position k if the elements were sorted.

Solution:We make slight modifications to the quicksort routine to find the kth smallest element.Like in normal quicksort,we choose a pivot and partition the remaining array in to 2 sub arrays.At this stage,we have 3 possibilities.

1)the size of the first sub array is k-1 ,in which case pivot itself is the kth smallest.
2)the size of the first sub array is greater than k ,in which case kth smallest element is to be recursively searched in the first sub-array.

3)the size of the first sub array is less than k-1 ,in which case reuired element is to be recursively searched in the second sub-array.


Hence unlike quicksort where each problem gives rise to 2 subproblems,here each problem gives rise to only 1 sub problem.

Pseudo Code:

QuickSelect(Array A, n, k)
pivot = A [Random(1, n)]
X={x | x belongs to A and x <=pivot}
Y={x | x belongs to A and x >=pivot}
if size(X) = k
return pivot;
else if size(X) < k
return QuickSelect(Y,n-size(X)-1,k-size(X)-1);
else
return QuickSelect(X,size(X),k);

Run time Analysis of QuickSort ,Nature of Input,Pivot strategies

Question Determine the running time of QuickSort for

a.Sorted input
b.reverse -ordered input
c.random input
d. When all the elements are equal



Solution:This solution is being written with the assumption that middle element of the array is chosen as the pivot.The answers differ based on the pivot selection as well.
a.Sorted input
In the case of sorted input,the left and right pointers of the sub arrays pass each other with out a single swap in all the iterations.The problem is divided in to 2 equal problems in all but the base case of unit size array.Hence the recurrence relation for this case is T(N)=2*T(N/2)+O(N).Hence the complexity in this case is O(NlogN).

b.reverse-ordered input

This case is identical to the previous case except that we have so many swaps in each iteration.The left and right pointers swap the content on each increment in their directions.This effects only the O(N) part of the recurrence relation that we have in the previous case.But as the swap is of complexity O(1), the complexity of each iteration remains the same.And the division of the array is still even.So the complexity doesn't change.Hence it is still O(NlogN)

c.Random Input
Well there are theorems asserting that the complexity of quicksort on a random input is O(NlogN).We will prove it by considering evenly the chances of even and worst splits.
let's consider that good and bad splits alternate in the iterations, with good splits in the best case (N/2) and bad ones in the worst (N-1).
So every two levels, the array's been cut in half,which means, it's still exponential reduction -- O(NlogN ).

d. When all the elements are equal

It is as good as the sorted array.So the complexity is O(NlogN).

Question The ones who are familiar with QuickSort might also be well aware of the important phase of the algorithm-the pivot selection.Suppose we always choose the middle element as the pivot .Does this make it unlikely that QuickSort will require quadratic time?


Solution:Choosing the middle element never makes it unlikey that the QuickSort will require quadratic time.One might encounter an input in which the middle element is always the maximum in all iterations.Then the complexity will be quadratic.

example:a={1,3,2} choosing 3 as pivot produces 2 subproblems , one of size 0 and other of size 2.In the next iteration,with out loss of generality take 2 as the pivot.It produces a sub array of size 1 and another of size 0.Thus an input can always be generated in such a way that QuickSort routine always gives rise to 2 subarrays,one of them being of size 0.Hence quadratic time is not always avoidable.

Question What is the worst-case behavior (number of comparisons) for quick sort?
Solution:As we have seen in the previous question,because of a bad pivot selection we might at the worst run in to quadratic time complexity.

Question In selecting the pivot for QuickSort, which is the best choice for optimal partitioning:
a.The first element of the array
b.The last element of the array
c.The middle element of the array
d.The largest element of the array
e.The median of the array
f.Any of the above


Solution:while the choices a,b,c will always not guarantee O(NlogN) complexity,choice d always gives quadratic run time.choice e guarantees even partition of the array.Hence it is the optimal partition.
hence the sol is e.

Question In its worst case QuickSort behaves like:
a.Bubble sort
b.Selection sort
c.Insertion sort
d.Bin sort


Solution:In the worst ,the pivot selected will always be the maximum element leading to quadratic time complexity.In this case as it depicts the behaviour of bubble sort,where in maximum element always bubbles to the end.

Tree Arithmetic

1)If a tree has N nodes, then how many are the edges?

Solution:Every node has a parent except the root.Each edge associates a node with its child.So the number of edges are N-1.

2)Prove that there exists only a single path from each node to the root?
Solution:If there are more than 1 paths from a node to the root,it means there are more than 1 parents for one of the ancestors of the node concerned, which is impossible in a tree.

3)Prove that the depth of a tree is always equal to the height of the tree?

Solution: Height of a tree is the height of the root.Depth of a tree is the depth of the deepest node, which is the number of edges from root to it.This should also be the node which defines the height of the root,otherwise we end up with a contradiction.

4)The structure of a typical tree is to have in each node ,besides it data, a pointer to each of its children.But this might be infeasible if there aren’t fixed number of children at each node.So how do modify this data structure to accommodate variable no of children at each node?


Solution:Well the answer to this is child sibling relationship.


5)What are the maximum and minimum depths of a binary search tree?

Solution:In a binary tree of N nodes,the maximum depth is N-1 when it develops only on 1 side and the minimum is floor(log(N)).


6)How many are the no of null pointers for a binary tree of N nodes?

Solution: Total no of pointer=2*N. And each edge is associated with 1 pointer.
So the no of null pointer is 2*N-(N-1)=N+1 .

7)Distinguish inorder , preorder and postorder traversals properly?
Solution: Inorder traversal:Left subtree is first processed ,followed by root and then by right subtree.

Preorder: root is first processed followed by left and right subtrees.There is no order defined between left and right children.Essentially left and right subtrees are traversed only after the root is traversed.

Postorder:Left and right children are traversed before traversing root.


8)How is a binary tree different from binary search tree?

Solution:In Binary search tree, all the elements in the left subtree are <= root and all the elements in the right subtree are >= root,which is not the case with all the binary trees.

9)Recursive calls have always been employed in the case of trees because of their recursive structural property.But linked lists aren’t that different .But why recursion is not that advisable in the case of lists?(A little theoretical …. Think in terms of limited stack size of your machine)

Solution:The depth of a well built tree of N nodes is log(N).So recursive calls are affordable most of the times as stack overflow is seldom possible.But if recursive calls are employed for lists, then the order of recursive call stack size is N which
is not feasible for large N.

10)What are the complexities of insertion,deletion on a binary search tree?

Solution:Insertion in a well built binary search tree is O(logN) and so is the deletion.This is under assumption that depth of tree is O(logN).


11)Show that the maximum number of nodes in a binary tree of height H is 2^(H+1) -1

Solution:In a binary tree of height H ,with maximum number of nodes,all the levels should be completely filled.At depth d, the number of nodes should be 2^d.
Therefore, the total number of nodes =1+2+4+....+2^H=2^(H+1)-1.

Number of ways to express a number as summation of consecutive numbers

Question.All the positive numbers can be expressed as a sum of one, two or more consecutive positive integers. For example 9 can be expressed in three such ways, 2+3+4, 4+5 or 9. Given an integer ,you will have to determine in how many ways that number can be expressed as summation of consecutive numbers.

Solution:
2+3+4=(1+2+3+4)-(1)
=(1+2+3+4+5)-(1+2+3)
=(1+2+3+4+5+6+7+8+9)-(1+2+3+4+5+6+7+8)

This shows that the no of solutions to this problem is the no of tuples (n,m) such that
given number K can be expressed as K=(1+2+..........+n)-(1+2+3+...........+m)
and n > m

i.e K=n*(n+1)/2 -m*(m+1)/2
=(n-m)(n+m+1)/2
2*k=(n-m)*(n+m+1)
If we put the factor n-m=p and (n+m+1)=q,we get S=2*k=p*q
As p+q=2*n+1 is odd and S is even either n-m is odd otherwise n+m+1 is odd.
This leaves out with finding out the no of odd divisors of S,which can be easily done using prime factorization.
if S=(2^p)*(3^q)*(5^r)*(7^s)......

then the solution is (q+1)*(r+1)*(s+1)*.. i.e the no of odd divisors of S.

Solutions to Logical Puzzles-2

)3
It is of the form 0^2+2,1^2+2,3^2+2,6^2+2,10^2+2,.....
The sequence of n is 0,1,3,6,10,... so the next n is 15 => 15^2+2

2)2
The function is S(n)=S(n-1)*(n+2) + 3 ,n>1
=6 ,n=1

3)1
It is of the form S(n)*3+2 for even and S(n)*2-3 for odd where S(n) is the nth element.
So 7th element = 239*2-3=475

4)2
The function is S(n)=(n+2)^3 -2

5)1
The numbers in the sequence is a combination of n^2 and n^3 and n is odd.

6)2
The function is S(n)=S(n-1)*n-n n>1
=3 n=1

7)

8)1
The function is S(n)=(S(n-1)-1)*(n-1) n>1
=8 n=1

9)

10)

Combinations

Question:Computing the exact number of ways that N things can be taken M at a time can be a great challenge when N and/or M become very large.So given 5<=N<=100 5<=M<=100 and M<=N.Compute the EXACT value of: N!/(M!*(N-M)!) The final value of C will fit in a 32-bit Pascal LongInt or a C long. So deduce an approach based on this assumption given.

Solution:At a mere glance,this problem may seem to have a direct solution,though it isn't upon a long thought.The naive approach to calculate combination of N things taken M at a time is obtained by mere application of formula,which mean finding N! ,M! and (N-M)! and the putting them in the expression.But as N and M are independently large enough for overflows to occur in N! and M! calculations.
One of the approaches to solve this problem,based on prime factorization can be formulated in the following manner.

Consider a prime P whose exponents in N!,M! and (N-M)! are p1,p2 and p3 respectively.

therefore the exponent of P in N!/M!*(N-M)! is p1+p2-p3.

This way we can store the exponents of all primes <= the largest prime which divides N.

One this is done ,we can merely multiply all these primes each raised to its exponent to get the required answer.


Now getting on to the tricky part of finding the exponent of a prime P in N!

In general ,if P is any prime,then the no of P's in N! is given by
Sum (floor(n/P^i)) for P^i <= N This apparently weird formula can be explained with ease!! consider the numbers 1,2,3,.........,,N.Every Pth number is divisible by P.So all those multiples of P put together contribute floor(N/P) to the power of P. Similarly every P^2th number is divisible by P^2.And each of them have already contributed 1 to power of P in previous iteration,as each of them are divisible by P.So each of them contribute an additional 1, which means they all together contribute floor(N/P^2) to the already sum. These terms of contribution go on till we have P^i <= N,hence the summation Sum (floor(N/P^i)) for P^i <= N The Cpp implementation of above task is given below


#include
using namespace std;
#include
#include
#include
#include
typedef vector powers;
void insert(vector &P,int i,vector V,int size)
{
vector temp=P[i-1];
//calculation of exponent of each prime
for(int j=0;j {
while(i%V[j]==0)
{
temp[j]++;
i/=V[j];
}
}
P.push_back(temp);
}
int main()
{
vector V;
vector P;
V.push_back(2);
bool flag;
int N,R;
for(int i=3;i<100;i+=2)
{
flag=true;
for(int j=0;V[j]*V[j] <=i;j++)
{
if(i%V[j]==0)
{
flag=false;
break;
}
}
if(flag)
{
V.push_back(i);
}
}
int size=V.size();
vector temp(size,0);
P.push_back(temp);
P.push_back(temp);
for(int i=2;i<=100;i++)
{
insert(P,i,V,size);
}
while(cin >> N >>R)
{
if(N==0 && R==0)
{
return(0);
}
else
{
long sol=1;
for(int i=0;i {

sol*=(long)pow((double)V[i],P[N][i]-P[R][i]
-P[N-R][i]); //Pi^(p1-p2-p3)
}
cout< "< "<

}

}
return(0);
}

Archives