You are on page 1of 41

SQL Aptitude Interview Questions For Freshers

SQL 1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL) What operator performs pattern matching? LIKE operator What operator tests column for the absence of data? IS NULL operator Which command executes the contents of a specified file? START or @ What is the parameter substitution symbol used with INSERT INTO command? & Which command displays the SQL command in the SQL buffer, and then executes it? RUN What are the wildcards used for pattern matching? _ for single character substitution and % for multi-character substitution State true or false. EXISTS, SOME, ANY are operators in SQL. True State true or false. !=, <>, ^= all denote the same operation. True 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 What command is used to get back the privileges offered by the GRANT command? REVOKE

Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD Which system table contains information on constraints on all the tables created? USER_CONSTRAINTS 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. 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. 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. What will be the output of the following query? SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL; TROUBLETHETROUBLE 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. 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.

Which date function is used to find the difference between two dates? MONTHS_BETWEEN 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. 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. What is the use of the DROP option in the ALTER TABLE command? It is used to drop constraints specified on the table. 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 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. 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. Which function is used to find the largest integer less than or equal to a specific value? FLOOR What is the output of the following query? SELECT TRUNC(1234.5678,-2) FROM DUAL;

BASIC SQL COMMANDS SQL commands fall into one of 4 categories:

SELECT - Retrieving data from one or more tables INSERT - Adding rows to a table UPDATE - Modifying existing rows in a table DELETE - Deleting one or more rows from a table

The examples assume a table called Customer with 3 columns: Id, FirstName and LastName. I'm trying to keep this simple so I won't go into any details about data types, primary keys, etc. This will be described/explained in a future article. For the purpose of the examples the Id column is numeric and the other 2 columns contain character data.

The basic syntax for the SELECT statement is: SELECT Id, FirstName, LastName FROM Customer WHERE LastName = 'Fryar' This example retrieves id, first and last names for all customers whose last name is "Fryar". The list of columns can be replaced by a wildcard (*) to retrieve all columns from the table. The conditional part of the statement can be extended so that rows matching several criteria are retrieved: SELECT * FROM Customer WHERE LastName = 'Fryar' AND FirstName = 'Richard'

The syntax for the second of my basic SQL commands is: INSERT INTO Customer (Id, FirstName, LastName) VALUES (100, 'John', 'Smith') This could have been replaced with the following, which does exactly the same: INSERT INTO Customer (Id, FirstName, LastName) SELECT 100, 'John', 'Smith' This can be combined with the SELECT statement to add multiple rows to the table. For example, you may want to copy all customers into another table if their Id is less than 500: INSERT INTO CopyCustomer (Id, FirstName, LastName) SELECT Id, FirstName, LastName FROM Customer WHERE Id < 500

The basic syntax for the UPDATE statement is:

UPDATE Customer SET LastName = 'Wilkins' WHERE Id = 12345 This changes the last name of customer 12345.

The basic syntax for the DELETE statement is: DELETE Customer WHERE Id = 12345 This deletes customer 12345. Multiple customers could be deleted with the following: DELETE Customer WHERE LastName < 500 This deletes all customers if their Id is less than 500. OK, this is a contrived example, but it illustrates the power of the command.

Define candidate key, alternate key, composite key.

A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

What are defaults? Is there a column to which a default cannot be bound?

A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFAULT in books online.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?


is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it will not log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?

SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal configuration mode. Check out SQL Server books online for more parameters and their explanations. hat is a join and explain different types of joins?

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.

Types of joins:



are further classified as



For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".

Can you have a nested transaction?


What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It will be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

What is de-normalization and when would you go for it?

As the name indicates, de-normalization is the reverse process of normalization. It is the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.

What is systems development life cycle (SDLC)? (SDLC is also an abbreviation for Synchronous Data Link Control.) The systems development life cycle (SDLC) is a conceptual model used in project management that describes the stages involved in an information system development project, from an initial feasibility study through maintenance of the completed application. Various SDLC methodologies have been developed to guide the processes involved, including the waterfall model (which was the original SDLC method); rapid application development

(RAD); joint application development (JAD); the fountain model; the spiral model; build and fix; and synchronize-and-stabilize. Frequently, several models are combined into some sort of hybrid methodology. Documentation is crucial regardless of the type of model chosen or devised for any application, and is usually done in parallel with the development process. Some methods work better for specific types of projects, but in the final analysis, the most important factor for the success of a project may be how closely the particular plan was followed.

an SDLC methodology follows the following steps:

1. The existing system is evaluated. Deficiencies are identified. This can be done by interviewing users of the system and consulting with support personnel. 2. The new system requirements are defined. In particular, the deficiencies in the existing system must be addressed with specific proposals for improvement. 3. The proposed system is designed. Plans are laid out concerning the physical construction, hardware, operating systems, programming, communications, and security issues. 4. The new system is developed. The new components and programs must be obtained and installed. Users of the system must be trained in its use, and all aspects of performance must be tested. If necessary, adjustments must be made at this stage. 5. The system is put into use. This can be done in various ways. The new system can phased in, according to application or location, and the old system gradually replaced. In some cases, it may be more cost-effective to shut down the old system and implement the new system all at once. 6. Once the new system is up and running for a while, it should be exhaustively evaluated. Maintenance must be kept up rigorously at all times. Users of the system should be kept up-todate concerning the latest modifications and procedures.

Systems development phases

This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.
(September 2010)

The System Development Life Cycle framework provides a sequence of activities for system designers and developers to follow. It consists of a set of steps or phases in which each phase of the SDLC uses the results of the previous one. A Systems Development Life Cycle (SDLC) adheres to important phases that are essential for developers, such as planning, analysis, design, and implementation, and are explained in the section below. A number of system development life cycle (SDLC) models have been created: waterfall, fountain, spiral, build and fix, rapid prototyping, incremental, and synchronize and stabilize. The oldest of these, and the best known, is the waterfall model: a sequence of stages in

which the output of each stage becomes the input for the next. These stages can be characterized and divided up in different ways, including the following[6]:

Preliminary analysis: The objective of phase1 is to conduct a preliminary analysis, propose alternative solutions, describe costs and benefits and submit a preliminary plan with recommendations. Conduct the preliminary analysis: in this step, you need to find out the organization's objectives and the nature and scope of the problem under study. Even if a problem refers only to a small segment of the organization itself then you need find out what the objectives of the organization itself are. Then you need to see how the problem being studied fits in with them. Propose alternative solutions: in digging into the organization's objectives and specific problem, you may have already is covered some solutions, other possible solutions can some form interviewing may have already discovered some solutions, other possible solutions can some from interviewing people inside the organization, clients or customers affected by it, suppliers and consultants. You can also study what competitors is doing. With this data, you can have three choices. You can leave the system as is, improve it, or develop a new system. Describe the costs and benefits.

Systems analysis, requirements definition: Defines project goals into defined functions and operation of the intended application. Analyzes end-user information needs. Systems design: Describes desired features and operations in detail, including screen layouts, business rules, process diagrams, pseudocode and other documentation. Development: The real code is written here. Integration and testing: Brings all the pieces together into a special testing environment, then checks for errors, bugs and interoperability. Acceptance, installation, deployment: The final stage of initial development, where the software is put into production and runs actual business. Maintenance: What happens during the rest of the software's life: changes, correction, additions, moves to a different computing platform and more. This is often the longest of the stages.

Memory management is the act of managing computer memory. The essential requirement of memory management is to provide ways to dynamically allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed. This is critical to the computer system.

Several methods have been devised that increase the effectiveness of memory management. Virtual memory systems separate the memory addresses used by a process from actual physical addresses, allowing separation of processes and increasing the effectively available amount of RAM using paging or swapping to secondary storage. The quality of the virtual memory manager can have a big impact on overall system performance.

Dynamic memory allocation

[edit] Details

The task of fulfilling an allocation request consists of finding a block of unused memory of sufficient size. Even though this task seems simple, several issues make the implementation complex. One of such problems is internal and external fragmentation, which arises when there are many small gaps between allocated memory blocks, which are insufficient to fulfill the request. Another is that allocator's metadata can inflate the size of (individually) small allocations; this effect can be reduced by chunking. Usually, memory is allocated from a large pool of unused memory area called the heap (also called the free store). Since the precise location of the allocation is not known in advance, the memory is accessed indirectly, usually via a pointer reference. The precise algorithm used to organize the memory area and allocate and deallocate chunks is hidden behind an abstract interface and may use any of the methods described below.
[edit] Efficiency

The dynamic memory allocation algorithm actually used can impact performance significantly and a study conducted in 1994 by Digital Equipment Corporation illustrates the overheads involved for a variety of allocators. The lowest average instruction path length required to allocate a single memory slot was 52 (as measured with an instruction level profiler on a variety of software).[1]
[edit] Implementations [edit] Fixed-size-blocks allocation Main article: Memory pool

Fixed-size-blocks allocation, also called memory pool allocation, uses a free list of fixed-size blocks of memory (often all of the same size). This works well for simple embedded systems where no large objects need to be allocated, but it suffers from fragmentation.
[edit] Buddy blocks For more details on this topic, see Buddy memory allocation.

In this system, memory is allocated from several pools of memory instead of just one, where each pool represents blocks of memory of a certain power of two in size. If a smaller size is requested than is available, the smallest available size is selected and it is then broken in two. One of the resulting halves is selected, and the process repeats (checking the size again and splitting if needed) until the block is just large enough. All new blocks that are formed during these splits are added to their respective memory pools for later use. All the blocks of a particular size are kept in a sorted linked list or tree. When a block is freed, it is compared to its buddy. If they are both free, they are combined and placed in the next-largest size buddy-block list (when a block is allocated, the allocator will start with the smallest sufficiently large block avoiding needlessly breaking blocks).

[edit] Systems with virtual memory

Virtual memory is a method of decoupling the memory organisation from the actual physical hardware. The applications operate memory via virtual adresses. Each time an attempt to access the actual data is made, virtual memory subsystem translates the virtual address to a physical address, which corresponds to the address of the data as seen by the hardware. The address translation process itself is managed by the operating system. In this way addition of virtual memory enables granular control over the main memory and ways to access it. This can be used to increase the effectiveness of memory management.
[edit] Protection Main article: Memory protection

In virtual memory systems the operating system controls the ways a process can access the memory. This feature can be used to disallow a process to read or write to memory that is not allocated to the said process, essentially prevents malicious or malfunctioning code in one program from interfering with the operation of other running programs.
[edit] Sharing Main article: Shared memory

Even though the memory for different processes is normally protected from each other, different processes sometimes need to be able to share information. One way to provide this is to allow the processes to access the same part of memory. Shared memory is one of the fastest techniques for Inter-process communication.
[edit] Physical organization

Memory is usually divided into fast primary storage and slow secondary storage. Memory management in the operating system handles moving information between these two levels of memory.

Process management is an integral part of any modern day operating system (OS). The OS must allocate resources to processes, enable processes to share and exchange information, protect the resources of each process from other processes and enable synchronisation among processes. To meet these requirements, the OS must maintain a data structure for each process, which describes the state and resource ownership of that process, and which enables the OS to exert control over each process.

Co Multiprogramming
In many modern operating systems, there can be more than one instance of a program loaded in memory at the same time; for example, more than one user could be executing the same program, each user having separate copies of the program loaded into memory. With some programs, it is possible to have one copy loaded into memory, while several users have shared access to it so that they each can execute the same program-code. Such a program is said to be re-entrant. The processor at any instant can only be executing one instruction from one program but several processes can be sustained over a period of time by assigning each process to the processor at intervals while the remainder become temporarily inactive. A number of processes being executed over a period of time instead of at the same time is called concurrent execution. A multiprogramming or multitasking OS is a system executing many processes concurrently. Multiprogramming requires that the processor be allocated to each process for a period of time and de-allocated at an appropriate moment. If the processor is de-allocated during the execution of a process, it must be done in such a way that it can be restarted later as easily as possible. There are two possible ways for an OS to regain control of the processor during a programs execution in order for the OS to perform de-allocation or allocation:
1. The process issues a system call (sometimes called a software interrupt); for example, an I/O request occurs requesting to access a file on hard disk. 2. A hardware interrupt occurs; for example, a key was pressed on the keyboard, or a timer runs out (used in pre-emptive multitasking).

The stopping of one process and starting (or restarting) of another process is called a context switch or context change. In many modern operating systems, processes can consist of many sub-processes. This introduces the concept of a thread. A thread may be viewed as a subprocess; that is, a separate, independent sequence of execution within the code of one process. Threads are becoming increasingly important in the design of distributed and clientserver systems and in software run on multi-processor systems.

Constructors: Copy Constructors, What, Why, How, When (C++)

Posted by tekpool on December 22, 2006 As the name suggests, a copy constructor is called whenever an object is copied. This happens in the following cases:

When an object is create from another object during initialization (Class a = b) When an object is created from another object as a parameter to a constructor (Class a(b)) When an object is passed by value as an argument to a function (function(Class a)) When an object is return from a function (Class a; return a;) When an exception is thrown using this object type (Class a; . throw a;)

Whenever an object copying scenario like the ones above is encountered, the copy constructor is invoked. A copy constructor can be either user defined or compiler defined. If the user does not define a copy constructor, then the default compiler defined copy constructor will be invoked during object copy scenarios. The default copy constructor is a bit-by-bit (member wise) copy. But often you will encounter situations where this is not desirable since this is just a shallow copy and sometimes you do not want an exact copy or you may want to do some custom resource management.
Class t1; Class t2=t1; // Copy Constructor is invoked Class t3; t3=t1; // Assignment Operator is invoked

In the Code snippet above, the constructor is invoked twice, during the creation of objects t1 and t3. (Creation of t2 invokes the copy constructor). The destructor is invoked 3 times though. In cases like these, if the constructor allocates memory and the destructor frees it, you will see the t2s destructor will try to delete already deleted memory, if t1 is destroyed before t2 or viceversa. Meaning, you are hosed. To prevent this, a user defined copy constructor needs to be provided. which doesnt do a simple bit-by-bit but rather assigns memory specifically for the object and does a deep copy if required. To define a copy constructor for a class T, a constructor of the following format needs to be defined.
Class T { T(const T& t) }

You need a reference because if it were T(T t), it would end in a infinite recursion. (Was that an oxymoron?). const because you are not changing the object in the constructor, you are just copying its contents Some Rules of Thumb:

Dont write a copy constructor if a bit-by-bit copy works for the class If you defined your own copy constructor, it probably because you needed a deep copy or some special resource management, in which case, you will need to release these resources at the end, which means you probably need to define a destructor and you may also want to think of overloading the assignment operator (beware of self-assignment)

Posted in C++, General, Microsoft, Progamming Languages | 13 Comments

Constructors: Error / Exception Handling in Constructors

Posted by tekpool on December 8, 2006 Constructors do not have return type and so they cannot return error codes. How are errors or exceptions handled in constructors? What if the calls that you make in the constructor can actually throw exceptions? How do you let the caller know something bad happened in a constructor? There are a few ways to do robust error/exception handling in constructors
1. Do as little in the constructor has you can. Then provide an Init() function in the constructor, which does the normal initialization stuff. The user can then call this function after creating an object. The problem here is, its up to the user to actually call the Init() function. The user could potentially miss this step, making this method error prone. However, there are a lot of places where this methodology is used. You are trying to eliminate error handling in the constructor by using this method 2. Another way to do this is by putting the object in a Zombie state. This is one approach you can take especially if you do not have the option of using exceptions. When you go with this option, you will also to do provide a function that will check the state of the object after construction. The downsides to this option is that, its up to the user to do these checks and the users will need to do this every time one attempts to create an object. Its usually always better and cleaner to throw an exception instead. Use the Zombie option as a last resort. 3. The downsides to the above methods can be reduced by making the constructor private or protected, expose a CreateInstance() public method, and do all the error handling here rather than leave it to the user. But sometimes, its not possible to handle all the error conditions in a generic manner and you will need to throw an exception. 4. If an exception is thrown in the constructor, the destructor will not get called. So you need to handle and clean up as much as you can before you leave the constructor. The best way to do this is using the resource allocation is initialization technique. I will cover this topic separately in a future post. But the basic idea is to assign resource allocation and cleanup to other objects. Basically, you are trying to get allocation out of the way (indirect) so that you dont have to do it explicitly. When you dont allocate something directly, you dont have to release it either

because it will be done by the component or class who deals with it. E.g. If you need to allocate some memory or open up a file, You can use smart objects (smart pointer, auto_ptr, smart file handlers etc..) instead of calling new or fopen directly. When you do this, and if an exception is thrown in your constructor, the smart objects will automatically release the resources it acquired, as the stack unwinds. If you do not use the resource allocation is initialization technique, the user will need to wrap the statements in try/catch block and rethrow after cleaning up the mess, something like what the finally block does in Java or C#. Although this works in theory, its up to the user to make this work and it also always a source of errors and bugs (esp. memory and handle leaks) and is messy

As you have seen, there is no one size fits all rule to do error/exception handling in constructors. I have listed the most commonly used methods and one of these should work most of the time. Posted in C++, General, Progamming Languages | 3 Comments

Swapping variables without additional space

Posted by tekpool on December 3, 2006 Swapping variables is a very common operation used it tons of algorithms like sorting etc. The most common and obvious technique is using of a temporary variable to swap values between two variables
void swap(int &i, int &j) { int temp = i; i = j; j = temp; }

Instead of writing a separate function for each data type, you could write a MACRO or templatize the function. Swapping without using a temporary variable is an age old trick and there are a few ways to do this. You could use of the basic arithmetic operations like +,-,/,*
1: void swap(int &i, int &j) 2: { 3: i=i+j; 4: j=i-j; 5: i=i-j; 6: }

The technique involves storing the sum of variables in one of them and then extracting it back by subtracting the other number. There are different variants to this technique. E.g, instead of starting by storing the sum, you could store the difference, product or the quotient. The last two

could lead you to round-off and integer division errors. However all of them have one fundamental flaw. Its in line 3, and the issue is that this could lead to an overflow error. This is another technique the gets you around these issues; the XOR Swapping technique
void swap(int &i, int &j) { i = i ^ j; j = j ^ i; i = i ^ j; }

This is an elegant technique and should work well with any primitive data type and you could write a simple MACRO like
#define SWAP(i, j) (((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))

Although, the XOR technique gets rid of the other issues like overflow and round off errors that we encountered in the previous technique, the lands in into yet another issues; This does not work when you try to swap the same memory location. However if can get around this by a simple if check or a more elegant OR check like
#define SWAP(i, j) ( (i==j) || ((i) ^= (j)), ((j) ^= (i)), ((i) ^= (j)))

The first OR condition (i == j) is checked before the actual SWAP. (You do not need a SWAP if the both memory locations hold the same data) Posted in Algorithms, Bit Fiddling, C++, General | 7 Comments

Singleton Pattern: Part 3 Double Checked Locking

Posted by tekpool on November 27, 2006 Singleton Pattern: Part 3 Double Checked Locking In the last post on Singleton Patterns, We looked into a thread safe mechanism to create singleton objects. The concept works well enough for most systems. However, when this becomes a hot section (heavily accessed) in your code, we will begin to hit performance problems. Heres why: Lets say we have a high performant system, with 50-100 threads working around like magic, sharing tasks and running as fast as possible. Lets say that all the threads hit this hot section very often. This will result in the hot section being a real bottle neck, synchronizing and slowing down all the threads. Every thread enters this critical section and blocks every other thread from using this section. But is this really required? The clever double locking system tries to fix this problem.

Instead of locking down the critical section and blocking all the threads, this technique gives a chance for the threads to asynchronously check, whether or not it needs to enter this section in the first place. If it does (when instance != null), it then locks the section and proceeds in a normal thread safe manner where it does the second check. So the name, Double Checked Locking.
class Singleton { private: static Singleton instance; protected Singleton() { } public static Singleton CreateInstance() { if(instance == null) //first check { // Use a mutex locking mechanism // that suits your system LockCriticalSection(); if (instance == null) //second check { instance = new Singleton(); } UnLockCriticalSection(); } return instance; } }

Note: If you are using Java to implement this, beware that there are issues in Javas memory model that prevent this technique from working correctly. This issue is however, fixed. So make sure you have the latest JDK if you plan to use this in your code. In a later post, I will go over the bug in JDK, more specifically in Javas memory model that causes this problem. Posted in Uncategorized | 2 Comments

Binary Tree Searching: Improving Search Performance with Sentinels

Posted by tekpool on November 16, 2006 A normal search across a BST (Binary Search Tree) would look like this bool BinaryTree::Search (int data ) { Node *current = this->root;

while ( current != NULL ) { if (current->data < data) { current = current->left; } else if (current->data > data) { current = current->right; } else if ( current->data == data ) { return true; } } return false; } You keep going down the tree, until you find a node whose value is equal to one you are looking for, or you bail out when you hit a leaf (NULL) node. If you look at the number of statements, there is one conditional check on the while, and an average of 1.5 conditional checks inside the loop. That makes it a total of 2.5 checks every iteration. On a tree with a 1000 nodes, thats 2500 checks. Lets see how we can improve this. I am using the sentinel node technique for this purpose. In this case static Node * Leaf; This is how the search will look like static Node* Leaf; bool BinaryTree::Search (int data ) { Node *current = this->root; Leaf->data = data; while ( current->data != lead->data ) { if (current->data < data) { current = current->left; } else {

current = current->right; } } return (current != Leaf); } The sentinel is a static node, and while building the tree, you point all the leaf nodes to this sentinel node instead of NULL. Before you start the search, you set the value of the sentinel node to the data you are searching for. This way you are guaranteed to get a hit. You just need to do one extra check at the end to see if the Hit node was a Node in the tree or the sentinel node. If you look at the number of conditional statements in the loop, there is one in the while statement and one inside the loop, that makes it 2 searches every iteration. You just saved half a conditional statement. Dont underestimate this improvement. E.g. In a 1000 iteration loop you saved 500 checks. This is extremely useful with large trees or when you are searching the tree several times or any other scenario where this call happens in a hot section. Posted in Algorithms, Binary Trees, C++, Data Structures, General, Microsoft | 13 Comments

Binary Tree Traversal: Breadth First aka Width First aka Level Order
Posted by tekpool on November 4, 2006 Binary Tree Traversal: Breadth First aka Width First aka Level Order This is the lesser know of the different kinds of binary tree traversals. Most beginner books and articles only cover the depth first searches. Breadth first traversals are an extremely important tool when working with Binary Trees. The idea is pretty nifty. Basically you work with a Queue, and push the root node into the Queue. Then do the following until you have visited all nodes in the tree. Visit and Dequeue each element (node) in the queue, and as you visit the node, enqueue its left and right child (if present). Continue this until there are no more nodes in the queue. At this point you have finished a breadth order traversal of the binary tree. Lets work this out with an example. Heres a small perfectly balanced tree that I going to be working with. The idea of doing a breadth first traversal is visit the nodes in the following order 1,2,3,4,5,6,7. Initially, you start of with an empty queue and enqueue the root node into the queue. I will display the contents of the queue as we move along.
------------------------------------------| 1 --------------------------------------------

Visit each element int the queue, enqueue its left and right nodes and dequeue itself. Once the elements are dequeued, I will put them to the left of the queue. Visit Node 1, enqueue 2 and 3 and dequeue 1
1 ------------------------------------------| 2, 3 --------------------------------------------

Visit Node 2, enqueue 4 and 5 and dequeue 2

1, 2 ------------------------------------------| 3, 4, 5 --------------------------------------------

Visit Node 3, enqueue 6 and 7 and dequeue 3

1, 2, 3 ------------------------------------------| 4, 5, 6, 7 --------------------------------------------

Visit Node 4, dequeue 4 Nothing to enqueue since 4 has no child nodes

1, 2, 3, 4 | ------------------------------------------5, 6, 7 --------------------------------------------

Visit Node 5, dequeue 5, Nothing to enqueue since 5 has no child nodes

1, 2, 3, 4, 5 ------------------------------------------| 6, 7 --------------------------------------------

Visit Node 6, dequeue 6, Nothing to enqueue since 6 has no child nodes

1, 2, 3, 4, 5, 6 ------------------------------------------| 7 --------------------------------------------

Visit Node 7, dequeue 7, Nothing to enqueue since 6 has no child nodes

------------------------------------------1, 2, 3, 4, 5, 6, 7 | --------------------------------------------

We have just finished a breadth order traversal of a binary tree Heres a pseudo-code snippet that of the solution.

BreadthOrderTraversal(BinaryTree binaryTree) { Queue queue; queue.Enqueue(binaryTree.Root); while(Queue.Size > 0) { Node n = GetFirstNodeInQueue(); queue.Enqueue(n.LeftChild); //Enqueue if exists queue.Enqueue(n.RightChild); //Enqueue if exists queue.Dequeue(); //Visit } }

Posted in Algorithms, Binary Trees, C++, Data Structures, General, Microsoft, Progamming Languages | 10 Comments

Singleton Pattern: Part 2 Thread-Safe implemenation

Posted by tekpool on October 27, 2006 Singleton Pattern: Part 2 Thread-Safe implemenation We looked into a trivial implementation of the singleton pattern in the previous post. The implementation was both lazy and non-thread safe. Its lazy, because the singleton instance is created only when its required. The implementation was also not thread safe. So, if several calls were made into this method from a multi-threaded program, you could end up creating multiple instances of the class, and also mess up seriously since the system expects to have only one instance. The problem is at the place, where you check if the instance is null. This is how it could go all wrong. In a multithread environment, lets say 2 threads T1 and T2 are calling the CreateInstance() function. T1 executes the if condition and then loses its time-slice, Meanwhile T2 gets its chance to execute code. At this point the singleton instance is not yet created. T2 then creates the object and returns the caller an instance of the newly created object. When T1 gets back another time-slice, it creates another object and returns that instance to its caller. Since its a static instance, T2 will lose its the state of the object it acquired and then hell breaks loose.
class Singleton { private: static Singleton instance; protected Singleton() { } public static Singleton CreateInstance() { // Use a mutex locking mechanism

// that suits your system LockCriticalSection(); if (instance == null) { instance = new Singleton(); } UnLockCriticalSection(); return instance; } } }

Posted in C++, Design Patterns, General, Microsoft, Progamming Languages | 178 Comments

Singleton Pattern: Part 1 Trivial implemenation

Posted by tekpool on October 19, 2006 Singleton Pattern: Part 1 Trivial implemenation The purpose of a singleton pattern is to ensure a unique instance of the class and to provide global access to this. It falls under the Creational patterns category. The class implementing the singleton pattern will have to do the following items:
1. Provide an Instance Creation Method to the user. 2. Maintain the unique instance throughout the life of the program(s) in which this class is created.

To maintain the unique instance, the class will have to remove the normal object creation procedure away from the user. The normal object creation is through the constructor. Taking this away from the user would mean, making the constructor as private or protected. With the absence of a public constructor, the class now can take total control on how its instances are created. The only way to do this, is to provide a static method (say CreateInstance). Why static? Because, the user can actually call this method without creating an object (which is obviously out of the users control). The logic of the CreateInstance method is pretty straightforward. Check, if any instance has already been created, if yes, return the instance, else create and store the instance and return it. It is obvious here again, storing the instance has to be done in a private static variable, static because, you are doing this in a static method, private because, you need to do the maintenance of the singleton instance creation. Heres the code sample to demonstrate this. I am going to promote Test Driven Development in my examples. The TestApp::TestSingleton() method is the test code that I wrote even before writing the actual Singleton class. I will discuss Test Driven Development in detail in another series.

class TestApp { public: static void TestSingleton() { Singleton s1 = Singleton.Instance(); Singleton s2 = Singleton.Instance(); if (s1 == s2) { printf("PASSED: Objects are of the same instance"); } else { printf("FAILED: Objects do not point to the same instance"); } } } // WARNING: DO NOT USE THIS CODE ANYWHERE. // THIS IS A VERY TRIVIAL IMPLEMENATION. WE WILL // DISCUSS THE ISSUES WITH THIS IN FUTURE POSTS. class Singleton { private: static Singleton instance; protected Singleton() { } public static Singleton CreateInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } }

Posted in C++, Design Patterns, General, Microsoft, Progamming Languages | 1 Comment

String Pattern Matching: Write a function that checks for a given pattern at the end of a given string
Posted by tekpool on October 15, 2006 String Pattern Matching: Write a function that checks for a given pattern at the end of a given string In other words, Write a function, a variant of strstr that takes in 2 strings str1 and str2 and returns true if str2 occurs at the end of the string str1, and false otherwise.
bool str_str_end(char * str1, char * str2) { // Store the base pointers of both strings char* beginStr1 = str1; char* beingStr2 = str2; // Move to the end of the strings while(*str1++); while(*str2++); for(; *str1 == *str2; str1--, Str2--) { If( str2 == beginStr2 || str1 == beingStr1) { break; } } return If(*str1 == *str2 && str2 == beginStr2 && *str1 != 0); }

Save the base addresses of the strings and then traverse to the end of the stings. To check if the string str2 occurs at the end of the string str1, start comparing characters from the end of the strings and move backwards. The function returns true when
1. All the characters in str1 match all the characters in str2 from the end. 2. The pointer str2 reaches back at the beginning of the string, which means there is nothing more to be compared 3. The strings are not empty.

The above conditions are required so that the loops do not run in an infinite loop.
Data structures and algorithms questions

Write a function and the node data structure to visit all of the nodes in a binary tree. You know what a queue is .... Implement a queue class with Java. What is the cost of enqueue and dequeue? Can you improve this? What if the queue is full (I was using an looping array)? What kind of mechanism would you use to increase its size? Give an algorithm that calculates the distance between two text strings (only operations you can have are: delete, add, and change, one by one). Given the definition of a sequence (5 4 7 6 is, but 1 2 4 5 is not), write an algorithm to check if an arbitrary array is a sequence or not. Once I figured out a solution, I was asked to do a space and time complexity analysis. Describe a situation where concurrent access would lead to inconsistency in your application. How would you solve this problem? You are given a list of n numbers from 1 to n-1, with one of the numbers repeated. Devise a method to determine which number is repeated. Write an algorithm to detect loop in a linked list. Given the time, devise an algorithm to calculate the angle between the hour and minute hands of an analog clock. Devise an algorithm for detecting whether a given string is a palindrome (spelled the same way forwards and backwards). For example, "A man, a plan, a canal, Panama." Given an eight-bit bitmap graphics file, devise an algorithm to convert the file into a two-bit ASCII approximation. Reverse a linked list. Insert in a sorted list First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'. Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index). Delete an element from a doubly linked list. Write a function to find the depth of a binary tree. Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.

Besides communication cost, what is the other source of inefficiency in RPC? Ways of optimizing symbol table storage in compilers. A walk-through through the symbol table functions, lookup() implementation etc - The interv. was on the Microsoft C team. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square). Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array. Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - sol given in the C lib -> typec.h) Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space. Do a breadth first traversal of a tree. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list). What is a balanced tree How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory. Implement an algorithm to reverse a doubly linked list. A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square. The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first. How would you implement a hash table ? How do you deal with collisions? How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory. Given a history of URLs, how would you determine if a particular URL had been seen before? Since pages can have multiple URLs pointing to them, how can you make sure you've never seen the same CONTENT before?

Write a function to print all of the permutations of a string. Come up with the plan on how to traverse a graph, as well as to quickly determine if a given URL is one of the million or so you've previously seen. The Web can be modeled as a directed graph. Come up with a graph traversal algorithm. Make the algorithm non-recursive and breadth-first. Implement an algorithm to reverse a singly linked list. (with and without recursion) Implement an algorithm to reverse a doubly linked list. Implement an algorithm to insert in a sorted list. Delete an element from a doubly linked list. Write a function to copy two strings, A and B. The last few bytes of string A overlap the first few bytes of string B. Implement an algorithm to sort an array. Given a sequence of characters, how will you convert the lower case characters to upper case characters? Write a routine that prints out a 2-D array in spiral order. Count the number of set bits in a number without using a loop. Give me an algorithm and C code to shuffle a deck of cards, given that the cards are stored in an array of ints. Try to come up with a solution that does not require any extra space. Write a function that takes in a string parameter and checks to see whether or not it is an integer, and if it is then return the integer value. How would you print out the data in a binary tree, level by level, starting at the top? Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words in it. Write a function to find the depth of a binary tree. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list). How would you implement a queue from a stack? Write a funtion that finds repeating characters in a string.

Write a routine to reverse a series of numbers without using an array. Give me an algorithm for telling me the number I didn't give you in a given range of numbers. (Numbers are given at random)

1. What is C language ? 2. What does static variable mean? 3. What are the different storage classes in C ? 4. What is hashing ? 5. Can static variables be declared in a header file ? 6. Can a variable be both constant and volatile ? 7. Can include files be nested? 8. What is a null pointer ? 9. What is the output of printf("%d") ? 10. What is the difference between calloc() and malloc() ? 11. What is the difference between printf() and sprintf() ? 12. How to reduce a final size of executable ? 13. Can you tell me how to check whether a linked list is circular ? 14. Advantages of a macro over a function ? 15. What is the difference between strings and character arrays ? 16. Write down the equivalent pointer expression for referring the same element a[i][j][k][l] ? 17. Which bit wise operator is suitable for checking whether a particular bit is on or off ? 18. Which bit wise operator is suitable for turning off a particular bit in a number ? 19. Which bit wise operator is suitable for putting on a particular bit in a number ? 20. Does there exist any other function which can be used to convert an integer or a float to a string ? 21. Why does malloc(0) return valid memory address ? What's the use ? 22. Difference between const char* p and char const* p 23. What is the result of using Option Explicit ? 24. What is the benefit of using an enum rather than a #define constant ? 25. What is the quickest sorting method to use ? 26. When should the volatile modifier be used ? 27. When should the register modifier be used? Does it really help ? 28. How can you determine the size of an allocated portion of memory ? 29. What is page thrashing ? 30. When does the compiler not implicitly generate the address of the first element of an array ? 31. What is the benefit of using #define to declare a constant ? 32. How can I search for data in a linked list ? 33. Why should we assign NULL to the elements (pointer) after freeing them ? 34. What is a null pointer assignment error ? What are bus errors, memory faults, and core dumps ? 35. When should a type cast be used ?

36. What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used? 37. How can I convert a string to a number ? 38. How can I convert a number to a string ? 39. Is it possible to execute code even after the program exits the main() function? 40. What is the stack ? 41. How do you print an address ? 42. Can a file other than a .h file be included with #include ? 43. What is Preprocessor ? 44. How can you restore a redirected standard stream ? 45. What is the purpose of realloc( ) ? 46. What is the heap ? 47. How do you use a pointer to a function ? 48. What is the purpose of main( ) function ? 49. Why n++ executes faster than n+1 ? 50. What will the preprocessor do for a program ? 51. What is the benefit of using const for declaring constants ? 52. What is the easiest sorting method to use ? 53. Is it better to use a macro or a function ? 54. What are the standard predefined macros ?

Data Patterns Placement Paper March 2011:1. complete the following a. $ * * $ @ * ? ? # @ @ # # $ ? ? some what simillar like this...but not clear. b. 1 , 3 , 7 , 13 , 21 , __ , 43 Ans : 31 c. 1, 3, 9, __ , 16900 2. Point out error, if any, in the following program main() { int i=1; switch(i) { case 1: printf("\nRadioactive cats have 18 half-lives"); break; case 1*2+4: printf("\nBottle for rent -inquire within"); break; } } Ans. No error. Constant expression like 1*2+4 are acceptable in cases of a switch. 3. Point out the error, if any, in the following program main() { int a=10,b; a>= 5 ? b=100 : b=200; printf("\n%d",b); } Ans. lvalue required in function main(). The second assignment should be written in parenthesis as follows: a>= 5 ? b=100 : (b=200); 4. In the following code, in which order the functions would be called? a= f1(23,14)*f2(12/4)+f3(); a) f1, f2, f3 b) f3, f2, f1 c) The order may vary from compiler to compiler d) None of the above

5. What would be the output of the following program? main() { int i=4; switch(i) { default: printf("\n A mouse is an elephant built by the Japanese"); case 1: printf(" Breeding rabbits is a hair raising experience"); break; case 2: printf("\n Friction is a drag"); break; case 3: printf("\n If practice make perfect, then nobody's perfect"); 6. Ten questions on analogies. eg: chief : tribe :: governer : state epaulette : shoulder :: tiara : head guttural : throat :: gastric : stomach inept : clever :: languid : active knife : butcher :: hammer : carpenter :: Directions 7-10 :The table below shows the number of people who responded to a survey about their favorite style of music. Use this information to answer the following questions to the nearest whole percentage. 7. What percentage of respondents under 31 , indicated that blues in their favorite style? A. 7.1 B. 7.6 C. 8.3 D. 14.1 E. 7.2 Ans: B 8. What percentage of respondents aged 21-30 indicated that jazz is their favorite style? A. 64 % B. 60%

C. 75% D. 36% E. 46% Ans: A 9. What percentage of the total sample indicated that Jazz is heir favorite style of music? A. 6 % B. 8% C. 22% D. 4% E. 11% Ans: E 10. What percentage of the total sample were aged 21-30? A. 31 % B. 23% C. 25% D. 14% E. 30% Ans: C 11. The values of shares (in Rs).of A, B and C from January to June are as follows. Month A B C January 30 60 80 February 35 65 85 March 45 75 65 April 40 75 82 May 55 75 85 June 50 75 80 12. If x and y are both positive integers, how much greater is x than y? x + y = 20 x = y A. B. C. D. E. Ans: C 13. Fifty percent of the articles in a certain magazine are written by staff members. Sixty percent of the articles are on current affairs. If 75 percent of the articles on current affairs are written by staff

members with more than 5 years experience of journalism, how many of the articles on current affairs are written by journalists with more than 5 years experience? 20 articles are written by staff members. Of the articles on topics other than current affairs, 50 percent are by staff members with less than 5 years experience. A. B. C. D. E. Ans: A 14. Is xy > 0 ? x/y < 0 x+y<0 A. B. C. D. E. Ans: A 15 One number, n, is selected at random from a set of 10 integers. What is the probability that n + 13 = 0 ? The largest integer in the set is 13. The arithmetic mean of the set is zero? A. B. C. D. E. Ans: E 16. Is w a whole number? 3w is an odd number. 2w is an even number A. B. C. D. E. Ans: B 17. In 1978, a kg of paper was sold at Rs25/-. If the paper rate increases at 1.5% more than the inflation

rate which is 6.5% a year, then what will be the cost of a kg of paper after 2 years? (a) 29.12 (b) 29.72 (c) 30.12 (d) 32.65 (e) none of these 18. In A,B,C are having some marbles with each of them. A has given B and C the same number of marbles each of them already have. Then, B gave C and A the same number of marbles they already have. Then C gave A and B the same number of marbles they already have. At the end A,B,and C have equal number of marbles. (i) If x,y,z are the marbles initially with A,B,C respectively. Then the number of marbles B have at the end (a) 2(x-y-z) (b) 4(x-y-z) (c) 2(3y-x-z) (d) x + y-z Ans. (c) (ii) If the total number of marbles are 72, then the number of marbles with A at the starting (a) 20 (b) 30 (c) 32 (d) 39 Ans. (d)

19. If a car starts from A towards B with some velocity. Due to some problem in the engine after traveling 30km, the car goes with 4/5 th of its actual velocity The car reaches B 45 min later to the actual time. If the car engine fails after traveling 45km, the car reaches the destination B 36min late to the actual time What is the initial velocity of car and what is the distance between A and B in km Ans. 20 & 130. 20. A person has Rs 100/- in his pocket, he can as 25 pencils or 15 books. He kept 15% of the money for traveling expenses and purchased 5 pencils. So how many books he can purchase with the remaining


Data Patterns Placement Paper May 2011:1. Point out the error in the following program main() { const char *fun(); *fun()='A'; } const char *fun() { return "Hello"; } Ans. fun() returns to a "const char" pointer which cannot be modified 2. What would be the output of the following program? main() { const int x=5; int *ptrx; ptrx=&x; *ptrx=10; printf("%d",x); } a) 5 b) 10 c) Error d) Garbage value 3. A switch statement cannot include a) constants as arguments b) constant expression as arguments c) string as an argument d) None of the above 4. How long the following program will run? main() { printf("\nSonata Software"); main(); }

a) infinite loop b) until the stack overflows c) All of the above d) None of the above 5. On combining the following statements, you will get char*p; p=malloc(100); a) char *p= malloc(100) b) p= (char*)malloc(100) c) All of the above d) None of the above 6.Point out the error in the following program main() { int a=10; void f(); a=f(); printf("\n%d",a); } void f() { printf("\nHi"); } Ans. The program is trying to collect the value of a "void" function into an integer variable. 7. In the following program how would you print 50 using p? main() { int a[]={10, 20, 30, 40, 50}; char *p; p= (char*) a; } Ans. printf("\n%d",*((int*)p+4)); 8. Would the following program compile? main() { int a=10,*j; void *k; j=k=&a; j++; k++;

printf("\n%u%u",j,k); } a) Yes b) No, the format is incorrect c) No, the arithmetic operation is not permitted on void pointers d) No, the arithmetic operation is not permitted on pointers 9. According to ANSI specifications which is the correct way of declaring main() when it receives command line arguments? a) main(int argc, char *argv[]) b) main(argc,argv) int argc; char *argv[]; c) main() {int argc; char *argv[]; } d) None of the above 10. What error would the following function give on compilation? f(int a, int b) { int a; a=20; return a; } a) missing parenthesis in the return statement b) The function should be declared as int f(int a, int b) c) redeclaration of a d) None of the above 11. We should not read after a write to a file without an intervening call to fflush(), fseek() or rewind() < TRUE/FALSE> Ans. True 12. If the program (myprog) is run from the command line as myprog 1 2 3 , What would be the output? main(int argc, char *argv[]) { int i; for(i=0;i<argc;i++) printf("%s",argv[i]); } a) 1 2 3 b) C:\MYPROG.EXE 1 2 3 c) MYP d) None of the above 13. If the following program (myprog) is run from the command line as myprog 1 2 3, What would be the output? main(int argc, char *argv[])

{ int i,j=0; for(i=0;i<argc;i++) j=j+ atoi(argv[i]); printf("%d",j); } a) 1 2 3 b) 6 c) error d) "123" 14. If the following program (myprog) is run from the command line as myprog monday tuesday wednesday thursday? What would be the output? main(int argc, char *argv[]) { while(--argc >0) printf("%s",*++argv); } a) myprog monday tuesday wednesday thursday b) monday tuesday wednesday thursday c) myprog tuesday thursday d) None of the above 15. In the following code, is p2 an integer or an integer pointer? typedef int* ptr ptr p1,p2; Ans. Integer pointer 16. If the following program (myprog) is run from the command line as myprog friday tuesday sunday, What would be the output? main(int argc, char *argv[]) { while(sizeofargv) printf("%s",argv[--sizeofargv]); } a) myprog friday tuesday sunday b) myprog friday tuesday c) sunday tuesday friday myprog d) sunday tuesday friday 17. What would be the output of the following program? main() { int i=4; switch(i)

{ default: printf("\n A mouse is an elephant built by the Japanese"); case 1: printf(" Breeding rabbits is a hair raising experience"); break; case 2: printf("\n Friction is a drag"); break; case 3: printf("\n If practice make perfect, then nobody's perfect"); } } a) A mouse is an elephant built by the Japanese b) Breeding rabbits is a hare raising experience c) All of the above d) None of the above 18. What is the output of the following program? #define SQR(x) (x*x) main() { int a,b=3; a= SQR(b+2); printf("%d",a); } a) 25 b) 11 c) error d) garbage value 19. In which line of the following, an error would be reported? 1. #define CIRCUM(R) (3.14*R*R); 2. main() 3. { 4. float r=1.0,c; 5. c= CIRCUM(r); 6. printf("\n%f",c); 7. if(CIRCUM(r))==6.28) 8. printf("\nGobbledygook"); 9. } a) line 1 b) line 5 c) line 6 d) line 7 20. What is the type of the variable b in the following declaration? #define FLOATPTR float*

FLOATPTR a,b; a) float b) float pointer c) int d) int pointer 21. In the following code; #include<stdio.h> main() { FILE *fp; fp= fopen("trial","r"); } fp points to: a) The first character in the file. b) A structure which contains a "char" pointer which points to the first character in the file. c) The name of the file. d) None of the above