Search This Blog

Sunday, January 18, 2009

DBMS & RDBMS interview questions

RDBMS Concepts

1. What is database?

A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose.

2. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications.

3. What is a Database system?
The database and DBMS software together is called as Database system.

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

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

6. Describe the three levels of data abstraction?
The are three levels of abstraction:
 Physical level: The lowest level of abstraction describes how data are stored.

 Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.  

 View level: The highest level of abstraction describes only part of entire database.


7. Define the "integrity rules"
There are two Integrity rules.
 Entity Integrity: States that “Primary key cannot have NULL value”
 Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation.

8. What is extension and intension?
Extension - 
It is the number of tuples present in a table at any instance. This is time dependent.
Intension - 
It is a constant value that gives the name, structure of table and the constraints laid on it.

9. What is System R? What are its two major subsystems?
System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system. 
Its two subsystems are 
 Research Storage 
 System Relational Data System.

10. How is the data structure of System R different from the relational structure? 
Unlike Relational systems in System R 
 Domains are not supported
 Enforcement of candidate key uniqueness is optional
 Enforcement of entity integrity is optional
 Referential integrity is not enforced

11. What is Data Independence?
 Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Two types of Data Independence:
 Physical Data Independence: Modification in physical level should not affect the logical level.  
 Logical Data Independence: Modification in logical level should affect the view level.  
  NOTE: Logical Data Independence is more difficult to achieve

12. What is a view? How it is related to data independence?
A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence.

13. What is Data Model?
 A collection of conceptual tools for describing data, data relationships data semantics and constraints.

14. What is E-R model?
This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes.

15. What is Object Oriented model?
This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes.

16. What is an Entity?
It is a 'thing' in the real world with an independent existence.

17. What is an Entity type?
It is a collection (set) of entities that have same attributes.

18. What is an Entity set?
It is a collection of all entities of particular entity type in the database.

19. What is an Extension of entity type?
The collections of entities of a particular entity type are grouped together into an entity set.

20. What is Weak Entity set?
An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set.

21. What is an attribute?
It is a particular property, which describes the entity. 

22. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn).

23. What is degree of a Relation?
It is the number of attribute of its relation schema.

24. What is Relationship?
It is an association among two or more entities.

25. What is Relationship set? 
The collection (or set) of similar relationships.

26. What is Relationship type?  
Relationship type defines a set of associations or a relationship set among a given set of entity types.  
 
27. What is degree of Relationship type? 
It is the number of entity type participating.

25. What is DDL (Data Definition Language)?
A data base schema is specifies by a set of definitions expressed by a special language called DDL.

26. What is VDL (View Definition Language)?
It specifies user views and their mappings to the conceptual schema.

27. What is SDL (Storage Definition Language)?
This language is to specify the internal schema. This language may specify the mapping between two schemas.

28. What is Data Storage - Definition Language?
The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language.

29. What is DML (Data Manipulation Language)?
This language that enable user to access or manipulate data as organised by appropriate data model.
 Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.
 Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.

31. What is DML Compiler?
It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.

32. What is Query evaluation engine?
It executes low-level instruction generated by compiler.

33. What is DDL Interpreter?
It interprets DDL statements and record them in tables containing metadata.

34. What is Record-at-a-time?
The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time.

35. What is Set-at-a-time or Set-oriented?
The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.

36. What is Relational Algebra?
It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation. 

37. What is Relational Calculus?
It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL.

38. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE.

39. What is normalization? 
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties
 Minimizing redundancy
 Minimizing insertion, deletion and update anomalies.  

40. What is Functional Dependency?  
A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y.

41. When is a functional dependency F said to be minimal? 
 Every dependency in F has a single attribute for its right hand side.
 We cannot replace any dependency X A in F with a dependency Y A where Y is a proper subset of X and still have a set of dependency that is equivalent to F.
 We cannot remove any dependency from F and still have set of dependency that is equivalent to F.

42. What is Multivalued dependency?
Multivalued dependency denoted by X Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following properties
 t3[x] = t4[X] = t1[X] = t2[X]
 t3[Y] = t1[Y] and t4[Y] = t2[Y]
 t3[Z] = t2[Z] and t4[Z] = t1[Z]  
where [Z = (R-(X U Y)) ]
   
43. What is Lossless join property?
It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition.

44. What is 1 NF (Normal Form)?
The domain of attribute must include only atomic (simple, indivisible) values. 

45. What is Fully Functional dependency? 
It is based on concept of full functional dependency. A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more.

46. What is 2NF? 
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key.

47. What is 3NF?
A relation schema R is in 3NF if it is in 2NF and for every FD X A either of the following is true
 X is a Super-key of R.
 A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.

48. What is BCNF (Boyce-Codd Normal Form)?
 A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate key.
   
49. What is 4NF?
A relation schema R is said to be in 4NF if for every Multivalued dependency X Y that holds over R, one of following is true
 X is subset or equal to (or) XY = R.
 X is a super key.

50. What is 5NF?
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true 
 Ri = R for some i.
 The join dependency is implied by the set of FD, over R in which the left side is key of R.  
51. What is Domain-Key Normal Form?
A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. 
 
52. What are partial, alternate,, artificial, compound and natural key?
Partial Key:
It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
Alternate Key:
 All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key:
 If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.
 Compound Key:
  If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key.
 Natural Key:
 When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

53. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.
Types:
 Binary search style indexing
 B-Tree indexing
 Inverted list indexing
 Memory resident table
 Table indexing

54. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary.

55. What is meant by query optimization?
The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization.

56. What is join dependency and inclusion dependency?
Join Dependency:
  A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no set of sound and complete inference rules for JD.
 Inclusion Dependency:
  An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency.

57. What is durability in DBMS?
Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability.

58. What do you mean by atomicity and aggregation?
Atomicity:
Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions.
 Aggregation:
 A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships.

59. What is a Phantom Deadlock?
In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts.

60. What is a checkpoint and When does it occur?
A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes.

61. What are the different phases of transaction?
Different phases are
 Analysis phase
 Redo Phase
 Undo phase

62. What do you mean by flat file database?
It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides user-interface management.

63. What is "transparent DBMS"?
It is one, which keeps its Physical Structure hidden from user.

64. Brief theory of Network, Hierarchical schemas and their properties
Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS.

65. What is a query?
 A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language.

66. What do you mean by Correlated subquery?
 Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery. 
A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery. 
 E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM)

67. What are the primitive operations common to all record management systems?
Addition, deletion and modification.

68. Name the buffer in which all the commands that are typed in are stored
 ‘Edit’ Buffer

69. What are the unary operations in Relational Algebra?
 PROJECTION and SELECTION.

70. Are the resulting relations of PRODUCT and JOIN operation the same?
 No.
 PRODUCT: Concatenation of every row in one relation with every row in another.
 JOIN: Concatenation of rows from one relation and related rows from another.

71. What is RDBMS KERNEL?
 Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database
 You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures
.
72. Name the sub-systems of a RDBMS
 I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management

73. Which part of the RDBMS takes care of the data dictionary? How
 Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel.

74. What is the job of the information stored in data-dictionary?
 The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location. 

75. Not only RDBMS takes care of locating data it also 
 determines an optimal access path to store or retrieve the data

76. How do you communicate with an RDBMS?
 You communicate with an RDBMS using Structured Query Language (SQL)

77. Define SQL and state the differences between SQL and other conventional programming Languages
SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 

78. Name the three major set of files on disk that compose a database in Oracle
There are three major sets of files on disk that compose a database. All the files are binary. These are
 Database files 
 Control files 
 Redo logs 
The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself. 
All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one. 

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

80. What are the four Oracle system processes that must always be up and running for the database to be useable
 The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor). 

81. What are database files, control files and log files. How many of these files should a database have at least? Why?
Database Files 
The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the database. 
You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the tables and other objects, the number (or location) of the files is immaterial. 
The database files are fixed in size and never grow bigger than the size at which they were created
Control Files 
The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time you add a new database or redo log file to the database, the information is recorded in the control files. 
Redo Logs 
Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs automatically without intervention from the DBA. 
The redo log files are fixed in size and never grow dynamically from the size at which they were created. 

82. What is ROWID?
 The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted into the database), it never changes until the row is deleted or the table is dropped. 
The ROWID consists of the following three components, the combination of which uniquely identifies the physical storage location of the row. 
 Oracle database file number, which contains the block with the rows
 Oracle block address, which contains the row 
 The row within the block (because each block can hold many rows) 
The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID

83. What is Oracle Block? Can two Oracle Blocks have the same address?
 Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS software to manage the files and easier to read data into the memory areas. 
The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow. 
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only when the database is first created. 
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in different database files. 

84. What is database Trigger?
 A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 

85. Name two utilities that Oracle provides, which are use for backup and recovery.
 Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import. 
The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed. 

86. What are stored-procedures? And what are the advantages of using them.
Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic.

87. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name
 PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination. 
The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller. 
User-Defined Exceptions 
PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example: 
  ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows: 
EXCEPTION
  when OT_FAILURE then
  out_status_code := g_out_status_code;
  out_msg := g_out_msg;
The following is an example of a subprogram exception: 
EXCEPTION
  when NO_DATA_FOUND then
  g_out_status_code := 'FAIL';
  RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all user-defined exceptions. 
System-Defined Exceptions 
Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions. 

PL/SQL internal exceptions. 

Exception Name
Oracle Error
CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
STORAGE_ERROR ORA-06500
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
TRANSACTION_BACKED_OUT ORA-00061
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established.

88. Does PL/SQL support "overloading"? Explain
 The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered. 
PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference. 

89. Tables derived from the ERD 
 a) Are totally unnormalised
 b) Are always in 1NF
 c) Can be further denormalised
 d) May have multi-valued attributes

 (b) Are always in 1NF

90. Spurious tuples may occur due to
  i. Bad normalization  
  ii. Theta joins
  iii. Updating tables from join
 a) i & ii b) ii & iii
 c) i & iii d) ii & iii

 (a) i & iii because theta joins are joins made on keys that are not primary keys.

91. A B C is a set of attributes. The functional dependency is as follows
  AB -> B
  AC -> C
  C -> B
 a) is in 1NF
 b) is in 2NF
 c) is in 3NF
 d) is in BCNF

 (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF. 

92. In mapping of ERD to DFD 
 a) entities in ERD should correspond to an existing entity/store in DFD
 b) entity in DFD is converted to attributes of an entity in ERD
 c) relations in ERD has 1 to 1 correspondence to processes in DFD
 d) relationships in ERD has 1 to 1 correspondence to flows in DFD

 (a) entities in ERD should correspond to an existing entity/store in DFD

93. A dominant entity is the entity
 a) on the N side in a 1 : N relationship
 b) on the 1 side in a 1 : N relationship
 c) on either side in a 1 : 1 relationship
 d) nothing to do with 1 : 1 or 1 : N relationship

(b) on the 1 side in a 1 : N relationship

94. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By 
CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER
The above is
 a) Not an error
 b) Error - the string in single quotes 'NORTH' and 'SOUTH'
 c) Error - the string should be in double quotes
 d) Error - ORDER BY clause

(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS

95. What is Storage Manager?  
It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system.  
  
96. What is Buffer Manager?
It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory.  

97. What is Transaction Manager?
It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting.

98. What is File Manager?
It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk.  

99. What is Authorization and Integrity manager?
It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.  
 
100. What are stand-alone procedures?
Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution.

101. What are cursors give different types of cursors.
PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors
 Implicit 
 Explicit

102. What is cold backup and hot backup (in case of Oracle)?
 Cold Backup: 
It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. 
If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost. 
 Hot Backup: 
Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option. 
So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination. 
The database must be running in ARCHIVELOG mode for the hot backup option. 
If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions. 

103. What are Armstrong rules? How do we say that they are complete and/or sound
The well-known inference rules for FDs  
 Reflexive rule :  
  If Y is subset or equal to X then X Y.
 Augmentation rule:
  If X Y then XZ YZ.
 Transitive rule:
  If {X Y, Y Z} then X Z.
 Decomposition rule :
  If X YZ then X Y.
 Union or Additive rule:
  If {X Y, X Z} then X YZ.
 Pseudo Transitive rule :
  If {X Y, WY Z} then WX Z.
 Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules.

104. How can you find the minimal key of relational schema?
Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency.
 Algo. I Determining X+, closure for X, given set of FDs F
1. Set X+ = X
2. Set Old X+ = X+
3. For each FD Y Z in F and if Y belongs to X+ then add Z to X+
4. Repeat steps 2 and 3 until Old X+ = X+

Algo.II Determining minimal K for relation schema R, given set of FDs F
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K 
a. Compute (K – A)+ with respect to F
b. If (K – A)+ = R then set K = (K – A)+


105. What do you understand by dependency preservation?
Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e., 
((R1(F)) U … U (Rn(F)))+ = F+
 if decomposition is not dependency preserving, then some dependency is lost in the decomposition.
 
106. What is meant by Proactive, Retroactive and Simultaneous Update.
Proactive Update:
 The updates that are applied to database before it becomes effective in real world .
Retroactive Update: 
 The updates that are applied to database after it becomes effective in real world .
Simulatneous Update:
 The updates that are applied to database at the same time when it becomes effective in real world .

107. What are the different types of JOIN operations?
Equi Join: This is the most common type of join which involves only equality comparisions. The disadvantage in this type of join is that there 


 

Important C Answers for Interview

ANSWERS FOR TECHNICAL QUESTIONS IN C

1. What does static variable mean?
 When a variable is declared to static it will be initialized the default value zero. It is local to the block in which it is declared. The lifetime persists for each and every function call.


2. What is a pointer?
 A pointer is also called a reference of a particular data type. But instead of storing some value it stores the address of a particular variable. This address can be initialized by using “&” operator. Eg: int a = &b;


3. What is a structure?

 Structure is a special type of user defined data structure which comprises of a collection of certain type predefined data types like int, char, float etc. It is an entity which comprises of many atoms.


4. What are differences between structure and array?
 Arrays are group of data of same data type, whereas structure is combination of entities of different data types. Size of array needs to be declared initially itself whereas structure can be done both initially and dynamically.


5. In header files whether functions are declared or defined?  
 Inside header files the functions are defined and they are not declared. This is also a type of structure definition.


6. What are the differences between malloc() and calloc()?
malloc() takes a single argument(memory required in bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a single variable). Secondly, malloc() doesnot initialize the memory allocated, while calloc() initializes the allocated memory to ZERO. The difference b/w malloc and calloc are: 1. malloc() allocates byte of memory where as calloc()allocates block of memory. 


7. What are macros? What are its advantages and disadvantages?
 Macros are short form for macro definition. These macro names are handled by the pre processor and it replaces the corresponding definition. Macros increase the speed of execution whereas they also increase the size of the program.


8. Differences between pass by reference and pass by value
 Whenever we call a function if we pass the value of the variable with it, it is called call by value. Whereas, if we pass the address were the variable is stored it is called, call by reference.

9. What is static identifier?
 In C the names of variables, functions, labels etc are named as identifiers. Similarly static is also an identifier which is used to initialize value to some data types.

10. Where is the auto variables stored?  
 Even if variables are not declared auto by default they are taken to be auto. When initialized auto variables are stored in the memory it is local to the block in which it is declared, its default value is garbage.


11. Where does global, static, local, register variables, free memory and c Program instructions get stored?
 Local Variables are stored in Stack. Register variables are stored in Register. Global & static variables are stored in data segment. The memory created dynamically are stored in Heap And the C program instructions get stored in code segment.


12. Difference between arrays and linked list?
 Arrays are initialized statically whereas linked list is initialized dynamically using pointers. Arrays are easy to create and use but creating linked list is tough. Arrays must be contiguous memory locations but in linked list they can be at different places.


13. What are enumerations?
 Enumeration is the process by which we can declare what values a particular variable of a defined data type can take.


14. Describe about storage allocation and scope of global, extern, static, local and register variables?
 The extern storage type is used to allow a source module within a C program to access a variable declared in another source module.  
Static variables are only accessible within the code block that declared them, and additionally if the variable is local, rather than global, they retain their old value between subsequent calls to the code block. 
 Register variables are stored within CPU registers where ever possible, providing the fastest possible access to their values.


15. What are register variables? What are the advantages of using register variables?
 Register variables is another type of storage class in C. When declared of this type it gets stored inside the CPU registers. Whenever we are going to use a variable at many places it is useful in declaring it as register because it will increase the speed of execution.


16. What is the use of typedef?
 Typedef is used in re declaring the variables. When ever big variable declarations are present they can be substituted using typedef. Eg: typedef unsigned long int TWO;. Whenever we want to use unsigned long int we can just use TWO. Eg: TWO var1, var2;


17. Can we specify variable field width in a scanf() format string? If possible how?
 Yes we can specify variable filed width within a scanf format string. An example is here we restrict string of length greater than size 20 using this statement. scanf(“%20s”, address).


18. Out of fgets() and gets() which function is safe to use and why?
 Out of fgets() and gets(), fgets() is safer because of the following reason. Fgets() reads from the file buffer until the beginning of a new line or until EOF. Whereas, in gets() it is the users work to specify length and gets() also has the danger of overrunning.


19. Difference between strdup() and strcpy()?
  Strcpy() is used to copy one string to another in his case we have to pass two values source and destination. Whereas. In strdup() it duplicates the string and source and destination values need not be passed.


20. What is recursion?
 The processes were a particular function calls itself again and again until a condition is meet is called as recursion. For example the factorial value can be calculated using recursive
functions.


21. Differentiate between for loop and a while loop? 
 We have to initialize values outside the while loop check condition and then increment inside the while loop. Whereas all three steps can be done together inside a single for loop. 


22. What are different storage classes in C?
 C provides four storage types; ‘extern’, ‘static’, ‘auto’ and ‘register’.


23. Write down the equivalent pointer expression for referring the same element a[i][j][k][l]?
 a[i] == *(a+i)
 a[i][j] == *(*(a+i)+j)
 a[i][j][k] == *(*(*(a+i)+j)+k)
 a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l)


24. What is the difference between structure and union?
 Both structure and union are almost similar. But the main difference is how they are stored. In structures many memory locations are grouped together. In unions a single memory location is split into many.


25. What is the advantage of using unions?
 Advantage of using union is that it reduces machine dependency. We no longer have to worry about the size of an int, long, float etc.


26. What are the advantages of using pointers in a program?
 The advantages of using pointers in programs are, they help in dynamic allocation of variables, they also help in efficient memory utilization ways, etc.


27. What is the difference between Strings and Arrays?

 Strings are used to handle a set of character, handling strings is a very important concept. Arrays are nothing but storing of entities of same data type in contiguous memory location. Strings are handles as a array of characters.


28. It is a repeated question


29. What is a far pointer? Where we use it?
 Far pointers are the normalized pointers of four bytes which are used to access the main memory of the computer ...it can access both the data segment and code segment thus by modifying the offset u can modify refer two different addresses but refer to the same memory


30. float (*fnp[3])(int, int);
31.What is NULL pointer? Whether it is same as an uninitialized pointer?
  Usually a pointer is initialized to NULL. this is to tell that it is still doesn't have valid address. Uninitialized pointer can contain any value (just like any other uninitialized variable), which we call garbage. 

32.What is NULL macro? What is the difference between a NULL pointer & a NULL macro?
  NULL is a macro which contains the value 0 (on most implementations). this is the one used to initialize a pointer to NULL.


33.What does the error ‘Null Pointer Assignment’ mean and what causes this error?
Null pointer assignment:
This error is displayed when a value is stored to an uninitialized pointer. The program may appear to work properly.


34.What is near,far,huge pointers?How many bytes are occupied by them?
 near pointer:
  near ;
The first version of near declares a pointer to be one word with a range of
64K.
 This type modifier is usually used when compiling in the medium, large, or
huge memory models to force pointers to be near.
 Example:
  char near *s;
  int (near *ip)[10];
 When near is used with a function declaration, Turbo C++ generates function
code for a near call and a near return.
 far pointers:
Forces pointers to be far, generates function code for a far call and a far
return.
Syntax:
  þ far ;
 The first version of far declares a pointer to be two words with a range of
1 megabyte. This type modifier is usually used when compiling in the tiny,
small, or compact models to force pointers to be far.
 Examples:
  char far *s;
  void * far * p;
When far is used with a function declaration, Turbo C++ generates function
code for a far call and a far return.
 huge pointer:
 Syntax: huge ;
 The huge pointer is similar to the far pointer except for two additional
features.
 
 1. Its segment is normalized during pointer
  arithmetic so that pointer comparisons are
  accurate.
 2.Huge pointers can be incremented without
  suffering from segment wraparound.
35.How would you obtain segment and offset address from a far address of a memory location?
  The segment and offset address can be calculated by means of using the function FP_SEG().The parameter to the function is fp which is the file pointer.It is given as FP_SEG(fp).This function returns the segment and offset address of the given memory location.


36.Are the expressions arr and &arr same for an array of integers?
  The __expression arr and &arr are same for an array of integers.
 

37.Does mentioning the array name gives the base address in all the contexts?
  No, not in all contexts. Following is the list of exceptions.
An expression of type “array of type” is converted to type
“pointer to type” unless:

* it is the operand of the sizeof operator, or
* it is the operand of the address-of (&) operator, or

* it is a string literal used to initialize an array.

 
38. Explain one method to process an entire string as one unit?
  Strlen()-This function counts the number of charcters present in a string.
 Ex:
main()
{
char arr[]=”London”;
int len;
len=strlen(arr);
printf(“string = %s length=%d”,arr,len);
}
 Output:
 String= London length=6


39. What is the similarity between a structure, union and enumeration?
  The similarity between a structure, union and enumeration is all the three are defined by the user.


40. Can a structure contain a pointer to itself?
  Yes, structure can contain a pointer to itself.
 typedef struct node {
  char *item;
  struct node *next;
 } *NODEPTR;


41.How can we check whether the contents of two structure variables are same or not?
  Two variables of the same structure type can be compared in same way as ordinary variables.
If person1 & person2 belongs to same structure the following operations are valid.
 
Operation Meaning
Person1=person2 Assign person2 to person1
Person1==person2 Compare all members of person1 &person2 & return 1 if they are equal, zero otherwise.
Person1!=person2 Return 1 if all the member are not equal, zero otherwise.
   
42. How are structure passing and returning implemented by compiler?
 When structures are passed as arguments to functions, the entire structure is typically pushed on the stack, using as many words as are required.


43. How can we read/write structures from/to data files?
  We ca n read/write structures from/to data files by using fscanf()&fprintf().


44. What is the difference between enumeration and a set of preprocessor #defines?
  #define have a global scope whereas the scope of enum can either be global (if declared outside all function) or local (if declared inside a function).


 45. What do the ‘c’ and ‘v’ in argc and argv stand for?
 Argc-argument count
  Argv-argument vector


46. Are the variables argc and argv are local to main?
  Yes, the variables argc and argv are local to main.


47. 
48. It is the command interpreter’s job to do the expansion.
49. 


50. What are bitfields?What is the use of bitfields in structure declaration?
  A bit field is an element of a structure that is defined in terms of bits.Using a special type of struct definition, you can declare a structure element that can range from 1 to 16 bits in length.
 For example, this struct
 struct bit_field {
  int bit_1 : 1;
  int bits_2_to_5 : 4;
  int bit_6 : 1;
  int bits_7_to_16 : 10;
  } bit_var;


51. To which numbering system can the binary number 1101100100111100 be easily converted to?
  Hexadecimal Numbering System.


52. Which bitwise operator is suitable for checking whether a particular bit is on or off?  
  Bitwise AND Operator.


53. Which bitwise operator is suitable for turning off a particular bit in a number?
 Bitwise AND Operator.


54. Which bitwise operator is suitable for putting on a particular bit in a number?
  Bitwise OR Operator.


55. Which bitwise operator is suitable for checking whether a particular bit is on or off?
  Bitwise AND Operator.


56.Which is equivalent to multiplying by 2:Left shifting a number by 1 or left shifting an unsigned int or char by 1?
  Left shifting a number by 1 is equivalent to multiplying by 2. It is always safe to use unsigned integer operands for bitwise operations, so the second statement will hold good.
 57. Write a program to compare two strings without using the strcmp() function?


 58.Write a program to concatenate two string?
 Program:
 #include
void main()
{
char source[]=”folks!”;
char target[30]=”Hello”;
strcat(target,source);
printf(“\nsource string=%s”,source);
printf(“\ntarget string=%s”,target);
}


59.Write a program to interchange two variables without using the third one?
Program:
 #include
void main(){
int a,b;
printf("ENTER THE VALUE OF A : ");
scanf("%d",&a);
printf("ENTER THE VALUE OF B : ");
scanf("%d",&b);
if (a>b)
{a=a-b;
b=a+b;
a=b-a;
}
else
{b=b-a;
a=b+a;
b=a-b;}
printf ("A = %d \nB = %d",a,b);
}
 
60.Write a program for String reversal & palindrome check?
 Program:
 #include
#include
#include
void main()
{
char str1[20],str2[20];
clrscr();
printf("\nEnter the string: ");
scanf("%s",&str1);
strcpy(str2,str1);
strrev(str1);
61. Write a program to find the Factorial of a number 
#include
#define VALUE 6 
int i,j; 
void main()  
{  
  j=1;  
  for (i=1; i<=VALUE; i++)  
  j=j*i;  
  printf("The factorial of %d is %d\n",VALUE,j);  


62.Write a program to generate the Fibinocci Series 
#include
main()
{ int fib[24];
  int i;
  fib[0] = 0;
  fib[1] = 1;
  for(i = 2; i < 24; i++)
  fib[i] = fib[i-1] + fib[i-2];
  for (i = 0; i < 24; i++)
  printf("%3d %6d\n", i, fib[i]);
}
63.Write a program which employs Recursion 
Program to display first four multiples of a number
#include
#include
Void multi();
Void main()
{
Int I;
Clrscr();
Multi(10);
Getch();
}
Void multi(int n)
{
If(n<10000)
{
Multi(n*10);
}
Printf(“\n%d”,n);
}
Output:  
10000
1000
100
10
64.Write a program which uses Command Line Arguments 
Weight Conversion with Command Line Argument

#include
void print_converted(int pounds)
/* Convert U.S. Weight to Imperial and International
  Units. Print the results */
{ int stones = pounds / 14;
  int uklbs = pounds % 14;
  float kilos_per_pound = 0.45359;
  float kilos = pounds * kilos_per_pound;

  printf(" %3d %2d %2d %6.2f\n",
  pounds, stones, uklbs, kilos);
}
main(int argc,char *argv[])
{ int pounds;
  if(argc != 2)
  { printf("Usage: convert weight_in_pounds\n");
  exit(1);
  }
  sscanf(argv[1], "%d", &pounds); /* Convert String to int */
  printf(" US lbs UK st. lbs INT Kg\n");
  print_converted(pounds);
}

65.Write a program which uses functions like strcmp(), strcpy()? etc 
#include /* stdin, printf, and fgets */
#include /* for all the new-fangled string functions */
/* this function is designed to remove the newline from the end of a string
entered using fgets. Note that since we make this into its own function, we
could easily choose a better technique for removing the newline. Aren't
functions great? */
void strip_newline( char *str, int size )
{
  int i;

  /* remove the null terminator */
  for ( i = 0; i < size; ++i )
  {
  if ( str[i] == '\n' )
  {
  str[i] = '\0';

  /* we're done, so just exit the function by returning */
  return;  
  }
  }
  /* if we get all the way to here, there must not have been a newline! */
}
int main()
{
  char name[50];
  char lastname[50];
  char fullname[100]; /* Big enough to hold both name and lastname */
  printf( "Please enter your name: " );
  fgets( name, 50, stdin );
  /* see definition above */
  strip_newline( name, 50 );
  /* strcmp returns zero when the two strings are equal */
  if ( strcmp ( name, "Alex" ) == 0 ) 
  {
  printf( "That's my name too.\n" );
  }
  else  
  {
  printf( "That's not my name.\n" );
  }
  // Find the length of your name
  printf( "Your name is %d letters long", strlen ( name ) );
  printf( "Enter your last name: " );
  fgets( lastname, 50, stdin );
  strip_newline( lastname, 50 );
  fullname[0] = '\0';  
  /* strcat will look for the \0 and add the second string starting at
  that location */
  strcat( fullname, name ); /* Copy name into full name */
  strcat( fullname, " " ); /* Separate the names by a space */
  strcat( fullname, lastname ); /* Copy lastname onto the end of fullname */
  printf( "Your full name is %s\n",fullname );
  getchar();
  return 0;
}


66.What are the advantages of using typedef in a program? 
A good programming practice is using typedef while instantiating template classes. Then throughout the program, one can use the typedef name. There are two advantages: 
• typedef's are very useful when "templates of templates" come into usage. For example, when instantiating an STL vector of int's, you could use: 
  typedef vector&ltint, allocator&ltint> > INTVECTOR ; 
 
• If the template definition changes, simply change the typedef definition. For example, currently the definition of template class vector requires a second parameter. 
 typedef vector&ltint, allocator&ltint> > INTVECTOR ;
  INTVECTOR vi1 ;

67.How would you dynamically allocate a one-dimensional and two-dimensional array of integers? 
int **arrayPtr;
int numRows, numCols;
printf("Enter values for numRows and numCols\n");
scanf("%d",&numRows);
scanf("%d",&numCols);
/* Create space for first array (array of pointers to each row). */
arrayPtr = (int **) malloc(numRows*sizeof(int));
/* Loop through first array and create space for according to number of columns.*/
for(rowIndex=0;rowIndex < numRows;rowIndex++)
arrayPtr[rowIndex] = malloc(numCols*sizeof(int));
The easiest way to create a dynamically allocated array is to first dynamically allocate an array of pointers, of length equal to the number of rows desired, and then have each entry in that array point to a dynamically allocated array of length equal to the number of columns. 
The following example allocates a dynamic array of characters with eight rows and 5 columns. 
main()
{
  char **myArray; // eek, char ** because myArray is a pointer to a
  // pointer to a character (an array of arrays...)
 
  myArray = new char * [8]; // allocate the rows

  for (int row = 0; row < 8; row++) // now allocate the columns
  myArray[i] = new char [5]; 
}

68.How can you increase the size of a dynamically allocated array? 
Realloc() function is used to resize the memory block,which is already allocated.
Syntax: ptr_var=realloc(ptr_var,new_size);

69.How can you increase the size of a statically allocated array? 
Required amount of memory is allocated to program elements at start of the program. memory value is fixed and identified by compiler at compile time. So statically allocated memory size cannot be resized.
70.When reallocating memory if any other pointers point into the same piece of memory do you have to readjust these other pointers or do they get readjusted automatically? 

If you have a pointer to a malloc'd section of memory and you realloc it, the pointer still points to the right addrss, but the actual address *may* change.


71.Which function should be used to free the memory allocated by calloc()? 
The Free() function
Syntax: free(ptr_var);

72.How much maximum can you allocate in a single call to malloc()? 
Depending upon the amount of free memory in the ram,the size is allocated to malloc in single call. To check whether requested memory is available the following program is used..
Int ptr*;
Prt=(int*)malloc(5*sizeof(int));
If (prt==NULL)
{
Printf(“required memory not available”);
Getch();exit(0);
}

73.Can you dynamically allocate arrays in expanded memory? 
  ======
74.What is object file? How can you access object file? 

The compiler compiles the error free source code and coverts them into byte code format and this file is called the object file. Thus the text editor produces .c source files, which go to the compiler, which produces .obj object files, which go to the linker, which produces .exe executable file  
75.Which header file should you include if you are to develop a function which can accept variable number of arguments? 
Stat.h
76.Can you write a function similar to printf()? 

The library function sprintf() is similar to printf() only the formatted output is written to a memory area rather than directly to standard output. It is particularly useful when it is necessary to construct formatted strings in memory for subsequent transmission over a communications channel or to a special device
main()
{
 char buf[128];
 double x = 1.23456;
 char *spos = buf;
 int i = 0;
 sprintf(buf,"x = %7.5lf",x);
 while(i<10) puts(spos+i++);
}
OUTPUT:
x = 1.23456
 = 1.23456
= 1.23456
 1.23456
1.23456
.23456
23456
3456
456
56
77.How can a called function determine the number of arguments that have been passed to it? 
Depending upon the number of arguments passed the called function will be selected accordingly.
Ex: a)void volume(int length,int breath,int height)
  b)void volume(int length,int breath)
When a=volume(2,3) then [b] will be called. If a=volume(3,6,7) then [a] will be called. 

78.Can there be at least some solution to determine the number of arguments passed to a variable argument list function? 

79.How do you declare the following: 
o An array of three pointers to chars 
char *name[] = { "Dave","Bert","Alf" };
o An array of three char pointers 
o A pointer to array of three chars 
o A pointer to function which receives an int pointer and returns a float pointer 
o A pointer to a function which receives nothing and returns nothing 

80.What do the functions atoi(), itoa() and gcvt() do? 
• gcvtConvert floating point value to string
• * itoaConvert integer to string
• atoiConvert string to integer
81.Does there exist any other function which can be used to convert an integer or a float to a string? 
• ecvtConvert floating point value to string
• * fcvtConvert floating point value to string
82.How would you use qsort() function to sort an array of structures? 
qsort will sort an array of elements. This is a wild function that uses a pointer to another function that performs the required comparisons. 
Library : stdlib.h
Prototype : void qsort(void *base, 
  size_t num, 
  size_t size, 
  int (*comp_func)(const void *, const void *))


83.How would you use qsort() function to sort the name stored in an array of pointers to string? 
void *qsort(const void *base, size_t nmemb,
  size_t size,
  int (*compar)(const void *, const void *));
void Person_dbase::list(Listtype type)
  {
  switch (type)
  {
  case list_by_name:
  qsort(pp, n, sizeof(Person), (pif2vp)cmpname);
  break;

  case list_by_birthday:
  qsort(pp, n, sizeof(Person), (pif2vp)cmpdate);
  break;
  } // list the sorted Person-database
}
   
84.How would you use bsearch() function to search a name stored in array of pointers to string? 
void *bsearch(const void *key, const void *base,
  size_t nmemb, size_t size,
  int (*compar)(const void *, const void *));

85.How would you use the functions sin(), pow(), sqrt()? 
#include
sin():
  double sin(double x);
  sin()- gives the trignometrical sin value of x which is in radian.
pow():
  double sqrt(double x);
  sqrt() returns the non-negative square root of x. The value of x must
  not be negative.
sqrt():
  float powf(float x, float y);
  pow() returns x^y. If x is 0.0, y must be positive. If x is
  negative, y must be an integer.

86.How would you use the functions memcpy(), memset(), memmove()? 
Declaration: memcpy():
void *memcpy(void *str1, const void *str2, size_t n); 
Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is undefined.

Declaration: memset():
void *memset(void *str, int c, size_t n); 
Copies the character c (an unsigned char) to the first n characters of the string pointed to by the argument str. 

Declaration: memmove():
void *memmove(void *str1, const void *str2, size_t n); 
Copies n characters from str2 to str1. If str1 and str2 overlap the information is first completely read from str1 and then written to str2 so that the characters are copied correctly.

87.How would you use the functions fseek(), fread(), fwrite() and ftell()? 
Fseek():
int fseek(FILE *stream, long offset, int mode); 
The function sets the file-position indicator for the stream stream (as specified by offset and mode), clears the end-of-file indicator for the stream, and returns zero if successful.
Fread():
size_t fread(void *ptr, size_t size, size_t nelem, FILE *stream); 
The function reads characters from the input stream stream and stores them in successive elements of the array whose first element has the address (char *)ptr until the function stores size*nelem characters or sets the end-of-file or error indicator. It returns n/size, where n is the number of characters it read. If n is not a multiple of size, the value stored in the last element is indeterminate. If the function sets the error indicator, the file-position indicator is indeterminate.
Fwrite():
size_t fwrite(const void *ptr, size_t size, size_t nelem, FILE *stream); 
The function writes characters to the output stream stream, accessing values from successive elements of the array whose first element has the address (char *)ptr until the function writes size*nelem characters or sets the error indicator. It returns n/size, where n is the number of characters it wrote. If the function sets the error indicator, the file-position indicator is indeterminate.
Ftell():
long ftell(FILE *stream); 
The function returns an encoded form of the file-position indicator for the stream stream or stores a positive value in errno and returns the value -1. For a binary file, a successful return value gives the number of bytes from the beginning of the file. For a text file, target environments can vary on the representation and range of encoded file-position indicator values.


88.How would you obtain the current time and difference between two times? 
BY USING TIMERELATED FUNCTIONS
Time() - Gets current system time as long integer
Difftime - Computes the difference between two times


89.How would you use the functions randomize() and random()? 
int randno = random(n);
It then returns a random whole number in the range 0 to n-1
BY using randomize() - Initializes random number generation with a random value based on time.


90.How would you implement a substr() function that extracts a sub string from a given string? 
substr(s,p)-- return substring of s starting at position p

91.What is the difference between the functions rand(), random(), srand() and randomize()? 
srand ... Sets a new random seed for rand 
rand ... returns a pseudo-random number (using the seed from srand 
  call) 
random and srandom are pretty mucht the same as rand and srand but the 
  have a better alorithm -> the numbers are more random 
randomize is probably a Borland specific function


92.What is the difference between the functions memmove() and memcpy()? 
memmove() – Copies n characters from str2 to str1. If str1 and str2 overlap the behavior is undefined 
memcpy() – Copies n characters from str2 to str1. If str1 and str2 overlap the information is first completely read from str1 and then written to str2 so that the characters are copied correctly


93.How do you print a string on the printer? 
BY USING: stdprn()-[standard printer] function.


94.Can you use the function fprintf() to display the output on the screen? 
yes it is possible .







Important Interview HR questions

*************************HR QUESTIONS**************************************

Q1.Define Yourself?

Ans:
 Don’t mention about your family out here.
 Don’t mention your percentage they don’t define you.
 Mention your name, college, branch and name of your school.
 Mention your achievements.
 Mention your hobbies.
 Mention your strength and weaknesses as well as what you are doing to overcome that weakness.

Q2. What do you expect from the company?
Ans:
 Always keep knowledge about the company you are going for.
 Try to know their goals 
 Don’t put up high.
 Don’t talk about the salary.
 The answer should be something like “ I expect the company to provide me with a healthy environment and a motivating work culture, Wherein I can utilize my capabilities and resources fruitfully.”

Q3. How do you Deal with tough people?
Ans:
It is said that “ A humble smile melts the stone”. Ill try to apply it practically. Ill try to humbly motivate and convince that person because” You can motivate a tiger to eat grass the only thing you have to do for it is to prove him that it’s a living thing”

Q4. What is opinion about brain drain?
Ans:
Its true that India faces the problem of brain drain but I don’t think it to be a vital problem because today we see everything globally. And we work for the global market and are more of a global citizen. My first law is to work for the humanity not nationality. Nationality comes later.

Q5.What are your strengths and weaknesses?
Ans:
 Your strength should include your moral values 
 Weakness should be accompanied by a solution to overcome it. 
 Don’t mention more than 2 weaknesses.

Q6. Why do you want to join our company?
Ans:
 Tell them that your goals and objectives matches to that of the company.
( But for this you need to have a prior idea about what is the company’s goals.)
 Give them references of some people who are working in the company and say that the working environment as said by the references suits you and it is one of the company you always wanted to work for.


Q7. What do you believe in Destiny or hard work? And why?
Ans:
I am alive because its my destiny but the way I’ll be leading my life will depend on my hard work . So I believe in both of them because both of them are important in ones life.

Q8. Who serves the country more, a scientist or an engineer?
Ans: 
A scientist works on an hypothesis and creates a principle and an engineer works on the principle to create a wonder. Though both are indispensable but an engineer serves the country more because one principle has hundreds of application and it’s the engineer who discovers these applications.

Q9. What is the difference between a goal and a dream?
Ans:
According to me “When I sleep I dream of a goal and when I am awake I accomplish it” or “I dream a dream each day to dream a dream each day , I work for a goal each day and reach a goal each day”.
This answer will depend totally upon your personality.

Q10. Why are you interested to work in a Software company?
Ans: You should state your own reason out here speak your heart. But avoid saying things like it fetches lot of money or more money than other fields.

Q11.Where do you see yourself after five years?
Ans:
After five years I see myself as a person who has worked honestly and as a person who has contributed to the company and the society enough to play a key role in it. I don’t expect to be in the limelight but I expect to be rewarded appropriately for my hard work.

Q12. Which is better public sector or a private sector? And why?
Ans:
There are always 2 sides of a coin and both the sectors have both sides. The positive side as well as the negative side. In public sector it’s the contacts and influences that work more than hard work does where as in Private sector the work is all that matters. As I am a hardworking person and believe in working I will prefer private sector job over public sector because I see more opportunities out here in private sector.

Q13. In which sector should government spend more-Education or health care and why??
Ans: Though both the sector need investment by the government but education should be the priority because its by education that a person comes to know about general hygiene and thus tries to protect himself from various diseases. Education also raises the living standard of a person and hence he is more capable and does not suffer from malnutrition. 

Q14. Who is the biggest victim of crime today Women or men? And why?
Ans:
With the rise in living standard and materialistic demands women and men both serve as the victim to crime. But women being the weaker sect suffers the most. 

Q15. Where should we spend more money- Development or defense?
Ans:
We should spend more on development as only when we are developed enough we can defend it well. As its said “Development is necessary for enlightening the mind” So by developing we will make our citizens more aware so that they can defend themselves.

Q16.Should computer be a compulsory subject in schools?
Ans:
Yes It should be a compulsory subject in schools, As with the changing era most of the basic operations have been computerized and to work on the very same level students of school should be given knowledge of computers so that they are aware and ease to operation is there.
OR
Yes because today like general science, computer is also used in day to day life so when we are teaching them general sciences why should we miss out computer science. 

Q17.Why should we select you?
Ans:
 Don’t say things like because “I am the best”.
 Say about your qualities and how those qualities fit the best in the company’s requirement.
 Here you have a good chance to boast about your moral values

Q18. What do you know about our company?
Ans:
 Always have a prior knowledge about the company .
 Be attentive when they are giving ppt it will avail you with certain facts which you might have missed out.
 Don’t talk about their image in the share market.



Q19. If we don’t select you which company will you prefer?
Ans:
 Don’t name any company out here.
 Tell them that you will prefer a company which will help you in your growth and which will provide a healthy and a competitive environment.
 Don’t say stuffs like” A company which will pay me more”.


 

Important 'C' Interview Questions

************************C Questions*********************************

Note : All the programs are tested under Turbo C/C++ compilers.  

It is assumed that,
 Programs run under DOS environment,
 Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed). 

Predict the output or error(s) for the following:

1. void main()
{
 int const * p=5;
 printf("%d",++(*p));
}
Answer:
  Compiler error: Cannot modify a constant value. 
Explanation:  
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

2. main()
{
 char s[ ]="man";
 int i;
 for(i=0;s[ i ];i++)
 printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
  mmmm
  aaaa
  nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

3. main()
{
 float me = 1.1;
 double you = 1.1;
 if(me==you)
printf("I love U");
else
  printf("I hate U");
}
Answer: 
I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb: 
Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .  

4. main()
 {
 static int var = 5;
 printf("%d ",var--);
 if(var)
  main();
 }
Answer:
5 4 3 2 1
  Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.  

5. main()
{
  int c[ ]={2.8,3.4,4,6.7,5};
  int j,*p=c,*q=c;
  for(j=0;j<5;j++) j="0;j<5;j++){" i="20;" i="-1,j="-1,k="0,l="2,m;" m="i++&&j++&&k++||l++;" 0 =" 0)." i="3;" c="-" c="%d" c="2;" minus=" plus." i="65;" i="10;" i=" !">14;
Printf ("i=%d",i);
}
Answer:
i=0


  Explanation:
In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero). 

15. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}
Answer:
77 
Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
 Now performing (11 + 98 – 32), we get 77("M");
 So we get the output 77 :: "M" (Ascii is 77).


16. #include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer:
SomeGarbageValue---10
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.
 
17. #include
main()
{
struct xx
{
  int x=3;
  char name[]="hello";
 };
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
 Answer:
Compiler Error
Explanation:
You should not initialize variables in declaration

18. #include
main()
{
struct xx
{
int x;
struct yy
{
char s;
 struct xx *p;
};
struct yy *q;
};
}
Answer:
Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

19. main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed

20. main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}
Answer:
45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.

21. #define square(x) x*x
main()
{
int i;
i = 64/square(4);
printf("%d",i);
}
Answer:
64
Explanation:
the macro call square(4) will substituted by 4*4 so the expression becomes i = 64/4*4 . Since / and * has equal priority the expression will be evaluated as (64/4)*4 i.e. 16*4 = 64
  
22. main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Answer:
ibj!gsjfoet
 Explanation:
  ++*p++ will be parse in the given order
 *p that is value at the location currently pointed by p will be taken
 ++*p the retrieved value will be incremented 
 when ; is encountered the location will be incremented that is p++ will be executed
Hence, in the while loop initial value pointed by p is ‘h’, which is changed to ‘i’ by executing ++*p and pointer moves to point, ‘a’ which is similarly changed to ‘b’ and so on. Similarly blank space is converted to ‘!’. Thus, we obtain value in p becomes “ibj!gsjfoet” and since p reaches ‘\0’ and p1 points to p thus p1doesnot print anything. 

23. #include
#define a 10
main()
{
#define a 50
printf("%d",a);
}
Answer:
50
Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.

24. #define clrscr() 100
main()
{
clrscr();
printf("%d\n",clrscr());
}
Answer:
100
Explanation:
Preprocessor executes as a seperate pass before the execution of the compiler. So textual replacement of clrscr() to 100 occurs.The input program to compiler looks like this :
  main()
  {
  100;
  printf("%d\n",100);
  }
 Note: 
100; is an executable statement but with no action. So it doesn't give any problem

25. main()
{
printf("%p",main);
}
Answer:
  Some address will be printed.
Explanation:
  Function names are just addresses (just like array names are addresses).
main() is also a function. So the address of function main will be printed. %p in printf specifies that the argument is an address. They are printed as hexadecimal numbers.

27) main()
{
clrscr();
}
clrscr();
 
Answer:
No output/error
Explanation:
The first clrscr() occurs inside a function. So it becomes a function call. In the second clrscr(); is a function declaration (because it is not inside any function).

28) enum colors {BLACK,BLUE,GREEN}
 main()
{
  
 printf("%d..%d..%d",BLACK,BLUE,GREEN);
   
 return(1);
}
Answer:
0..1..2
Explanation:
enum assigns numbers starting from 0, if not explicitly defined.

29) void main()
{
 char far *farther,*farthest;
  
 printf("%d..%d",sizeof(farther),sizeof(farthest));
   
 }
Answer:
4..2  
Explanation:
  the second pointer is of char type and not a far pointer

30) main()
{
 int i=400,j=300;
 printf("%d..%d");
}
Answer:
400..300
Explanation:
printf takes the values of the first two assignments of the program. Any number of printf's may be given. All of them take only the first two values. If more number of assignments given in the program,then printf will take garbage values.

31) main()
{
 char *p;
 p="Hello";
 printf("%c\n",*&*p);
}
Answer:

Explanation:
* is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H.

32) main()
{
  int i=1;
  while (i<=5)   {   printf("%d",i);   if (i>2)
  goto here;
  i++;
  }
}
fun()
{
  here:
  printf("PP");
}
Answer:
Compiler error: Undefined label 'here' in function main
Explanation:
Labels have functions scope, in other words The scope of the labels is limited to functions . The label 'here' is available in function fun() Hence it is not visible in function main.

33) main()
{
  static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
  int i;
  char *t;
  t=names[3];
  names[3]=names[4];
  names[4]=t; 
  for (i=0;i<=4;i++)   printf("%s",names[i]); } Answer: Compiler error: Lvalue required in function main Explanation: Array names are pointer constants. So it cannot be modified. 34) void main() {  int i=5;  printf("%d",i++ + ++i); } Answer: Output Cannot be predicted exactly. Explanation: Side effects are involved in the evaluation of i 35) void main() {  int i=5;  printf("%d",i+++++i); } Answer: Compiler Error  Explanation: The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.      36) #include
main()
{
int i=1,j=2;
switch(i)
 {
 case 1: printf("GOOD");
  break;
 case j: printf("BAD");
  break;
 }
}
Answer:
Compiler Error: Constant expression required in function main.
Explanation:
The case statement can have only constant expressions (this implies that we cannot use variable names directly so an error).
 Note:
Enumerated types can be used in case statements. 

37) main()
{
int i;
printf("%d",scanf("%d",&i)); // value 10 is given as input here
}
Answer:
1
Explanation:
Scanf returns number of items successfully read and not 1/0. Here 10 is given as input which should have been scanned successfully. So number of items read is 1. 

38) #define f(g,g2) g##g2
main()
{
int var12=100;
printf("%d",f(var,12));
 }
Answer:
100 

39) main()
{
int i=0;
 
for(;i++;printf("%d",i)) ;
printf("%d",i);
}
Answer:
 1
Explanation:
before entering into the for loop the checking condition is "evaluated". Here it evaluates to 0 (false) and comes out of the loop, and i is incremented (note the semicolon after the for loop).

40) #include
main()
{
  char s[]={'a','b','c','\n','c','\0'};
  char *p,*str,*str1;
  p=&s[3];
  str=p;
  str1=s;
  printf("%d",++*p + ++*str1-32);
}
Answer:
M
Explanation:
p is pointing to character '\n'.str1 is pointing to character 'a' ++*p meAnswer:"p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10. then it is incremented to 11. the value of ++*p is 11. ++*str1 meAnswer:"str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98. both 11 and 98 is added and result is subtracted from 32. 
i.e. (11+98-32)=77("M");
 
41) #include
main()
{
  struct xx
  {
  int x=3;
  char name[]="hello";
  };
struct xx *s=malloc(sizeof(struct xx));
printf("%d",s->x);
printf("%s",s->name);
}
Answer:
Compiler Error
Explanation:
Initialization should not be done for structure members inside the structure declaration

42) #include
main()
{
struct xx
 {
  int x;
  struct yy
  {
  char s;
  struct xx *p;
  };
  struct yy *q;
  };
  }
Answer:
Compiler Error
Explanation:
in the end of nested structure yy a member have to be declared.

43) main()
{
 extern int i;
 i=20;
 printf("%d",sizeof(i));
}
Answer:
Linker error: undefined symbol '_i'.
Explanation:
extern declaration specifies that the variable i is defined somewhere else. The compiler passes the external variable to be resolved by the linker. So compiler doesn't find an error. During linking the linker searches for the definition of i. Since it is not found the linker flags an error.

44) main()
{
printf("%d", out);
}
int out=100;
Answer:
Compiler error: undefined symbol out in function main.
Explanation:
The rule is that a variable is available for use from the point of declaration. Even though a is a global variable, it is not available for main. Hence an error.

45) main()
{
 extern out;
 printf("%d", out);
}
 int out=100;
Answer:
100 
 Explanation: 
This is the correct way of writing the previous program.
   
46) main()
{
 show();
}
void show()
{
 printf("I'm the greatest");
}
Answer:
Compier error: Type mismatch in redeclaration of show.
Explanation:
When the compiler sees the function show it doesn't know anything about it. So the default return type (ie, int) is assumed. But when compiler sees the actual definition of show mismatch occurs since it is declared as void. Hence the error.
The solutions are as follows:
1. declare void show() in main() .
2. define show() before main().
3. declare extern void show() before the use of show().
 
47) main( )
{
  int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
  printf(“%u %u %u %d \n”,a,*a,**a,***a);
  printf(“%u %u %u %d \n”,a+1,*a+1,**a+1,***a+1);
  }
Answer:
100, 100, 100, 2
112, 104, 102, 3
Explanation:
  The given array is a 3-D one. It can also be viewed as a 1-D array. 
   
2 4 7 8 3 4 2 2 2 3 3 4
  100 102 104 106 108 110 112 114 116 118 120 122

thus, for the first printf statement a, *a, **a give address of first element . since the indirection ***a gives the value. Hence, the first line of the output.
for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increments the first dimension thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1. Hence, the output.

48) main( )
{
  int a[ ] = {10,20,30,40,50},j,*p;
  for(j=0; j<5; p =" a;" j="0;" ptr =" p;" a =" value" ptr =" value" 1002 =" value" 102 =" 1." p =" 2," a =" 2," ptr =" 2." p =" 3," a =" 3," ptr =" 3." p =" 1006" 1000 =" 3," a =" 108" 100 =" 4," ptr =" 4." j="0;j<3;j++)scanf(“%s”,(q+j));" j="0;" j="0;" 2 =" M" ch =" ‘g’," cp =" “goofy”;" j =" 20;" vp =" &ch;" vp =" &j;" vp =" cp;" vp =" &ch" p =" ptr;" p =" s+3." p =" s+2." 1 =" s" x =" “girl”;" n =" strlen(x);" x =" x[n];" i="0;" blank="" irl="" rl="" l="" here="" a="" string="" a="" pointer="" to="" is="" initialized="" with="" a="" value="" the="" strlen="" function="" returns="" the="" length="" of="" the="" thus="" n="" has="" a="" value="" the="" next="" statement="" assigns="" value="" at="" the="" nth="" location="" to="" the="" first="" now="" the="" string="" becomes="" now="" the="" printf="" statement="" prints="" the="" string="" after="" each="" iteration="" it="" increments="" it="" starting="" loop="" starts="" from="" 0="" to="" the="" first="" time="" hence="" it="" prints="" nothing="" and="" pointer="" value="" is="" the="" second="" time="" it="" prints="" from="" e="" and="" the="" third="" time="" it="" prints="" and="" the="" last="" time="" it="" prints="" and="" the="" loop="" int="" i="0;i<=10;i++)" runtime="" abnormal="" program="" assert="" failed="">, 
Explanation:
asserts are used during debugging to make sure that certain conditions are satisfied. If assertion fails, the program will terminate reporting the same. After debugging use,
 #undef NDEBUG
and this will disable all the assertions from the source code. Assertion
is a good debugging tool to make use of.  
  
55) main()
 {
 int i=-1;
 +i;
 printf("i = %d, +i = %d \n",i,+i);
 }
Answer:
 i = -1, +i = -1
Explanation:
Unary + is the only dummy operator in C. Where-ever it comes you can just ignore it just because it has no effect in the expressions (hence the name dummy operator).

56) What are the files which are automatically opened when a C file is executed?
Answer:
stdin, stdout, stderr (standard input,standard output,standard error).

57) what will be the position of the file marker?
 a: fseek(ptr,0,SEEK_SET);
 b: fseek(ptr,0,SEEK_CUR);

Answer :
 a: The SEEK_SET sets the file position marker to the starting of the file.
  b: The SEEK_CUR sets the file position marker to the current position
 of the file.

58) main()
 {
 char name[10],s[12];
 scanf(" \"%[^\"]\"",s);
 }
 How scanf will execute? 
Answer:
First it checks for the leading white space and discards it.Then it matches with a quotation mark and then it reads all character upto another quotation mark.

59) What is the problem with the following code segment?
 while ((fgets(receiving array,50,file_ptr)) != EOF)
  ;
Answer & Explanation:
fgets returns a pointer. So the correct end of file check is checking for != NULL.

60) main()
 {
 main();
 }
Answer:
 Runtime error : Stack overflow.
Explanation:
main function calls itself again and again. Each time the function is called its return address is stored in the call stack. Since there is no condition to terminate the function call, the call stack overflows at runtime. So it terminates the program and results in an error.

61) main()
 {
 char *cptr,c;
 void *vptr,v;
 c=10; v=0;
 cptr=&c; vptr=&v;
 printf("%c%v",c,v);
 }
Answer:
Compiler error (at line number 4): size of v is Unknown.
Explanation:
You can create a variable of type void * but not of type void, since void is an empty type. In the second line you are creating variable vptr of type void * and v of type void hence an error.

62) main()
 {
 char *str1="abcd";
 char str2[]="abcd";
 printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
 }
Answer:
2 5 5
Explanation:
In first sizeof, str1 is a character pointer so it gives you the size of the pointer variable. In second sizeof the name str2 indicates the name of the array whose size is 5 (including the '\0' termination character). The third sizeof is similar to the second one.

63) main()
 {
 char not;
 not=!2;
 printf("%d",not);
 }
Answer:
0
Explanation:
! is a logical operator. In C the value 0 is considered to be the boolean value FALSE, and any non-zero value is considered to be the boolean value TRUE. Here 2 is a non-zero value so TRUE. !TRUE is FALSE (0) so it prints 0.

64) #define FALSE -1
 #define TRUE 1
 #define NULL 0
 main() {
  if(NULL)
  puts("NULL");
  else if(FALSE)
  puts("TRUE");
  else
  puts("FALSE");
  }
Answer:
TRUE
Explanation:
The input program to the compiler after processing by the preprocessor is,
 main(){
  if(0)
  puts("NULL");
 else if(-1)
  puts("TRUE");
 else
  puts("FALSE");
  }
Preprocessor doesn't replace the values given inside the double quotes. The check by if condition is boolean value false so it goes to else. In second if -1 is boolean value true hence "TRUE" is printed.

65) main()
 {
 int k=1;
 printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
 }
Answer:
1==1 is TRUE
Explanation:
When two strings are placed together (or separated by white-space) they are concatenated (this is called as "stringization" operation). So the string is as if it is given as "%d==1 is %s". The conditional operator( ?: ) evaluates to "TRUE".

66) main()
 {
 int y;
 scanf("%d",&y); // input given is 2000
 if( (y%4==0 && y%100 != 0) || y%100 == 0 )
  printf("%d is a leap year");
 else
  printf("%d is not a leap year");
 }
Answer:
2000 is a leap year
Explanation:
An ordinary program to check if leap year or not.

67) #define max 5
 #define int arr1[max]
 main()
 {
 typedef char arr2[max];
 arr1 list={0,1,2,3,4};
 arr2 name="name";
 printf("%d %s",list[0],name);
 }
Answer:
Compiler error (in the line arr1 list = {0,1,2,3,4})
Explanation:
arr2 is declared of type array of size 5 of characters. So it can be used to declare the variable name of the type arr2. But it is not the case of arr1. Hence an error.
Rule of Thumb: 
#defines are used for textual replacement whereas typedefs are used for declaring new types.

68) int i=10;
 main()
 {
  extern int i;
  {
  int i=20;
  {
  const volatile unsigned i=30;
  printf("%d",i);
  }
  printf("%d",i);
  }
 printf("%d",i);
 }
Answer:
30,20,10
Explanation:
'{' introduces new block and thus new scope. In the innermost block i is declared as, 
 const volatile unsigned
which is a valid declaration. i is assumed of type int. So printf prints 30. In the next block, i has value 20 and so printf prints 20. In the outermost block, i is declared as extern, so no storage space is allocated for it. After compilation is over the linker resolves it to global variable i (since it is the only variable visible there). So it prints i's value as 10.

69) main()
 {
  int *j;
  {
  int i=10;
  j=&i;
  }
  printf("%d",*j);
}
Answer:
10
Explanation:
The variable i is a block level variable and the visibility is inside that block only. But the lifetime of i is lifetime of the function so it lives upto the exit of main function. Since the i is still allocated space, *j prints the value stored in i since j points i.

70) main()
 {
 int i=-1;
 -i;
 printf("i = %d, -i = %d \n",i,-i);
 }
Answer:
i = -1, -i = 1
Explanation:
-i is executed and this execution doesn't affect the value of i. In printf first you just print the value of i. After that the value of the expression -i = -(-1) is printed.

71) #include
main()
 {
  const int i=4;
  float j;
  j = ++i;
  printf("%d %f", i,++j);
 }
Answer:
Compiler error 
  Explanation:
i is a constant. you cannot change the value of constant 

72) #include
main()
{
  int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
  int *p,*q;
  p=&a[2][2][2];
  *q=***a;
  printf("%d..%d",*p,*q);
}
Answer:
garbagevalue..1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays. but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. now q is pointing to starting address of a.if you print *q meAnswer:it will print first element of 3D array.

73) #include
main()
  {
  register i=5;
  char j[]= "hello";  
  printf("%s %d",j,i);
}
Answer:
hello 5
Explanation:
if you declare i as register compiler will treat it as ordinary integer and it will take integer value. i value may be stored either in register or in memory.

74) main()
{
  int i=5,j=6,z;
  printf("%d",i+++j);
  }
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)  
   
76) struct aaa{
struct aaa *prev;
int i;
struct aaa *next;
};
main()
{
 struct aaa abc,def,ghi,jkl;
 int x=100;
 abc.i=0;abc.prev=&jkl;
 abc.next=&def;
 def.i=1;def.prev=&abc;def.next=&ghi;
 ghi.i=2;ghi.prev=&def;
 ghi.next=&jkl;
 jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
 x=abc.next->next->prev->next->i;
 printf("%d",x);
}
Answer:
2
Explanation:
  above all statements form a double circular linked list;
abc.next->next->prev->next->i 
this one points to "ghi" node the value of at particular node is 2.

77) struct point
 {
 int x;
 int y;
 };
struct point origin,*pp;
main()
{
pp=&origin;
printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
printf("origin is (%d%d)\n",pp->x,pp->y);

 
Answer:
origin is(0,0)
origin is(0,0) 
Explanation:
pp is a pointer to structure. we can access the elements of the structure either with arrow mark or with indirection operator. 
Note: 
Since structure point is globally declared x & y are initialized as zeroes 
  
78) main()
{
 int i=_l_abc(10);
  printf("%d\n",--i);
}
int _l_abc(int i)
{
 return(i++);
}
Answer:
9
Explanation: 
return(i++) it will first return i and then increments. i.e. 10 will be returned.

79) main()
{
 char *p;
 int *q;
 long *r;
 p=q=r=0;
 p++;
 q++;
 r++;
 printf("%p...%p...%p",p,q,r);
}
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.

 80) main()
{
 char c=' ',x,convert(z);
 getc(c);
 if((c>='a') && (c<='z'))  x=convert(c);  printf("%c",x); } convert(z) {   return z-32; } Answer:  Compiler error Explanation: declaration of convert and format of getc() are wrong.  81) main(int argc, char **argv) {  printf("enter the character");  getchar();  sum(argv[1],argv[2]); } sum(num1,num2) int num1,num2; {  return num1+num2; } Answer: Compiler error. Explanation: argv[1] & argv[2] are strings. They are passed to the function sum without converting it to integer values.   82) # include
int one_d[]={1,2,3};
main()
{
 int *ptr; 
 ptr=one_d;
 ptr+=3;
 printf("%d",*ptr);
}
Answer:
garbage value
Explanation:
ptr pointer is pointing to out of the array range of one_d.

// pointer to functions question
83) # include
aaa() {
  printf("hi");
 }
bbb(){
 printf("hello");
 }
ccc(){
 printf("bye");
 }
main()
{
  int (*ptr[3])();
  ptr[0]=aaa;
  ptr[1]=bbb;
  ptr[2]=ccc;
  ptr[2]();
}
Answer:
bye 
Explanation:
ptr is array of pointers to functions of return type int.ptr[0] is assigned to address of the function aaa. Similarly ptr[1] and ptr[2] for bbb and ccc respectively. ptr[2]() is in effect of writing ccc(), since ptr[2] points to ccc.

85) #include
main()
{
FILE *ptr;
char i;
ptr=fopen("zzz.c","r");
while((i=fgetch(ptr))!=EOF)
printf("%c",i);
}
Answer:
contents of zzz.c followed by an infinite loop  
 Explanation:
The condition is checked against EOF, it should be checked against NULL.

86) main()
{
 int i =0;j=0;
 if(i && j++)
  printf("%d..%d",i++,j);
printf("%d..%d,i,j);
}
Answer:
0..0 
Explanation:
The value of i is 0. Since this information is enough to determine the truth value of the boolean expression. So the statement following the if statement is not executed. The values of i and j remain unchanged and get printed.
   
87) main()
{
 int i;
 i = abc();
 printf("%d",i);
}
abc()
{
 _AX = 1000;
}
Answer:
1000
Explanation:
Normally the return value from the function is through the information from the accumulator. Here _AH is the pseudo global variable denoting the accumulator. Hence, the value of the accumulator is set 1000 so the function returns value 1000. 

88) int i;
  main(){
int t;
for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
  printf("%d--",t--);
  }
 // If the inputs are 0,1,2,3 find the o/p
Answer:
  4--0
  3--1
  2--2  
Explanation:
Let us assume some x= scanf("%d",&i)-t the values during execution 
  will be,
  t i x
  4 0 -4
  3 1 -2
  2 2 0
   
89) main(){
  int a= 0;int b = 20;char x =1;char y =10;
  if(a,b,x,y)
  printf("hello");
 }
Answer:
hello 
Explanation:
The comma operator has associativity from left to right. Only the rightmost value is returned and the other values are evaluated and ignored. Thus the value of last variable y is returned to check in if. Since it is a non zero value if becomes true so, "hello" will be printed.

90) main(){
 unsigned int i;
 for(i=1;i>-2;i--)
  printf("c aptitude");
}
gives no output….just blank
Explanation:
i is an unsigned integer. It is compared with a signed value. Since the both types doesn't match, signed is promoted to unsigned value. The unsigned equivalent of -2 is a huge value so condition becomes false and control comes out of the loop. 

91) In the following pgm add a stmt in the function fun such that the address of 
'a' gets stored in 'j'.
main(){
  int * j;
  void fun(int **);
  fun(&j);
 }
 void fun(int **k) {
  int a =0;
  /* add a stmt here*/
 }
Answer:
  *k = &a
Explanation:
  The argument of the function is a pointer to a pointer.
   
92) What are the following notations of defining functions known as?
i. int abc(int a,float b)
  {
  /* some code */
 }
ii. int abc(a,b)
  int a; float b;
  {
  /* some code*/
  }
Answer:
i. ANSI C notation
ii. Kernighan & Ritche notation 

93) main()
{
char *p;
p="%d\n";
  p++;
  p++;
  printf(p-2,300);
}
Answer:
 300
Explanation:
The pointer points to % since it is incremented twice and again decremented by 2, it points to '%d\n' and 300 is printed.

94) main(){
 char a[100];
 a[0]='a';a[1]]='b';a[2]='c';a[4]='d';
 abc(a);
}
abc(char a[]){
 a++; 
  printf("%c",*a);
 a++;
 printf("%c",*a);
}
Explanation:
The base address is modified only in function and as a result a points to 'b' then after incrementing to 'c' so bc will be printed.
   
95) func(a,b)
int a,b;
{
 return( a= (a==b) );
}
main()
{
int process(),func();
printf("The value of process is %d !\n ",process(func,3,6));
}
process(pf,val1,val2)
int (*pf) ();
int val1,val2;
{
return((*pf) (val1,val2));
 }
Answer:
The value of process is 0 
Explanation:
The function 'process' has 3 parameters - 1, a pointer to another function 2 and 3, integers. When this function is invoked from main, the following substitutions for formal parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the result of the operation performed by the function 'func'. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a==b returns 0. therefore the function returns 0 which in turn is returned by the function 'process'.

96) void main()
{
 static int i=5;
 if(--i){
  main();
  printf("%d ",i);
 }
}
Answer:
 0 0 0 0
Explanation:
 The variable "I" is declared as static, hence memory for I will be allocated for only once, as it encounters the statement. The function main() will be called recursively unless I becomes equal to 0, and since main() is recursively called, so the value of static I ie., 0 will be printed every time the control is returned.

97) void main()
{
 int k=ret(sizeof(float));
 printf("\n here value is %d",++k);
}
int ret(int ret)
{
 ret += 2.5;
 return(ret);
}
Answer:
 Here value is 7
Explanation:
 The int ret(int ret), ie., the function name and the argument name can be the same.
 Firstly, the function ret() is called in which the sizeof(float) ie., 4 is passed, after the first expression the value in ret will be 6, as ret is integer hence the value stored in ret will have implicit type conversion from float to int. The ret is returned in main() it is printed after and preincrement.
 
98) void main()
{
 char a[]="12345\0";
 int i=strlen(a);
 printf("here in 3 %d\n",++i);
}
Answer: 
here in 3 6
Explanation:
 The char array 'a' will hold the initialized string, whose length will be counted from 0 till the null character. Hence the 'I' will hold the value equal to 5, after the pre-increment in the printf statement, the 6 will be printed.
 
99) void main()
{
 unsigned giveit=-1;
 int gotit;
 printf("%u ",++giveit);
 printf("%u \n",gotit=--giveit);
}
Answer:
 0 65535
Explanation:
 
100) void main()
{
 int i;
 char a[]="\0";
 if(printf("%s\n",a))
  printf("Ok here \n");
 else
  printf("Forget it\n");
}
Answer:
 Ok here 
Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.
 
101) void main()
{
 void *v;
 int integer=2;
 int *i=&integer;
 v=i;
 printf("%d",(int*)*v);
}
Answer: 
Compiler Error. We cannot apply indirection on type void*.
Explanation:
Void pointer is a generic pointer type. No pointer arithmetic can be done on it. Void pointers are normally used for, 
1. Passing generic pointers to functions and returning such pointers.
2. As a intermediate pointer type.
3. Used when the exact pointer type will be known at a later point of time.

102) void main()
{
 int i=i++,j=j++,k=k++;
printf(“%d%d%d”,i,j,k);
}
Answer: 
Garbage values.
Explanation:
An identifier is available to use in program code from the point of its declaration. 
So expressions such as i = i++ are valid statements. The i, j and k are automatic variables and so they contain some garbage value. Garbage in is garbage out (GIGO). 


103) void main()
{
 static int i=i++, j=j++, k=k++;
printf(“i = %d j = %d k = %d”, i, j, k);
}
Answer: 
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.

104) void main()
{
 while(1){
  if(printf("%d",printf("%d")))
  break;
  else
  continue;
 }
}
Answer: 
Garbage values
Explanation:
The inner printf executes first to print some garbage value. The printf returns no of characters printed and this value also cannot be predicted. Still the outer printf prints something and so returns a non-zero value. So it encounters the break statement and comes out of the while statement.

104) main()
{
 unsigned int i=10;
 while(i-->=0)
  printf("%u ",i);

}
Answer:
 10 9 8 7 6 5 4 3 2 1 0 65535 65534…..
Explanation:
Since i is an unsigned integer it can never become negative. So the expression i-- >=0 will always be true, leading to an infinite loop. 

105) #include
main()
{
 int x,y=2,z,a;
 if(x=y%2) z=2;
 a=2;
 printf("%d %d ",z,x);
}
 Answer: 
Garbage-value 0
Explanation:
The value of y%2 is 0. This value is assigned to x. The condition reduces to if (x) or in other words if(0) and so z goes uninitialized.
Thumb Rule: Check all control paths to write bug free code.

106) main()
{
 int a[10];
 printf("%d",*a+1-*a+3);
}
Answer:
4  
Explanation:
 *a and -*a cancels out. The result is as simple as 1 + 3 = 4 ! 

107) #define prod(a,b) a*b
main() 
{
 int x=3,y=4;
 printf("%d",prod(x+2,y-1));
}
Answer:
10
Explanation:
 The macro expands and evaluates to as:
 x+2*y-1 => x+(2*y)-1 => 10

108) main()
{
 unsigned int i=65000;
 while(i++!=0);
 printf("%d",i);
}
Answer:
 1
Explanation:
Note the semicolon after the while statement. When the value of i becomes 0 it comes out of while loop. Due to post-increment on i the value of i while printing is 1.
  
109) main()
{
 int i=0;
 while(+(+i--)!=0)
  i-=i++;
 printf("%d",i);
}
Answer:
-1
Explanation:
Unary + is the only dummy operator in C. So it has no effect on the expression and now the while loop is, while(i--!=0) which is false and so breaks out of while loop. The value –1 is printed due to the post-decrement operator.
  
113) main()
{
 float f=5,g=10;
 enum{i=10,j=20,k=50};
 printf("%d\n",++k);
 printf("%f\n",f<<2); i="10;" i="10;" i="10;" i="0;">=0;i++) ;
  printf("%d\n",i);
  }
Answer
  -128
Explanation
Notice the semicolon at the end of the for loop. THe initial value of the i is set to 0. The inner loop executes to increment the value from 0 to 127 (the positive range of char) and then it rotates to the negative value of -128. The condition in the for loop fails and so comes out of the for loop. It prints the current value of i that is -128.
  
113) main()
  {
  unsigned char i=0;
  for(;i>=0;i++) ;
  printf("%d\n",i);
  }
Answer
 infinite loop
Explanation
The difference between the previous question and this one is that the char is declared to be unsigned. So the i++ can never yield negative value and i>=0 never becomes false so that it can come out of the for loop.

114) main()
  {
  char i=0;
  for(;i>=0;i++) ;
  printf("%d\n",i);
   
 }
Answer:
  Behavior is implementation dependent.
Explanation:
The detail if the char is signed/unsigned by default is implementation dependent. If the implementation treats the char to be signed by default the program will print –128 and terminate. On the other hand if it considers char to be unsigned by default, it goes to infinite loop.
Rule:
You can write programs that have implementation dependent behavior. But dont write programs that depend on such behavior.

115) Is the following statement a declaration/definition. Find what does it mean?
int (*x)[10];
Answer
  Definition.
 x is a pointer to array of(size 10) integers.

  Apply clock-wise rule to find the meaning of this definition.


116). What is the output for the program given below 

  typedef enum errorType{warning, error, exception,}error;
  main()
  {
  error g1;
  g1=1; 
  printf("%d",g1);
  }
Answer
  Compiler error: Multiple declaration for error
Explanation
The name error is used in the two meanings. One means that it is a enumerator constant with value 1. The another use is that it is a type name (due to typedef) for enum errorType. Given a situation the compiler cannot distinguish the meaning of error to know in what sense the error is used: 
 error g1;
g1=error; 
 // which error it refers in each case?
When the compiler can distinguish between usages then it will not issue error (in pure technical terms, names can only be overloaded in different namespaces).
Note: the extra comma in the declaration,
enum errorType{warning, error, exception,}
is not an error. An extra comma is valid and is provided just for programmer’s convenience.
  
 
117) typedef struct error{int warning, error, exception;}error;
  main()
  {
  error g1;
  g1.error =1; 
  printf("%d",g1.error);
  }

Answer
  1
Explanation
The three usages of name errors can be distinguishable by the compiler at any instance, so valid (they are in different namespaces).
Typedef struct error{int warning, error, exception;}error;
This error can be used only by preceding the error by struct kayword as in:
struct error someError;
typedef struct error{int warning, error, exception;}error;
This can be used only after . (dot) or -> (arrow) operator preceded by the variable name as in :
g1.error =1; 
  printf("%d",g1.error);
  typedef struct error{int warning, error, exception;}error;
This can be used to define variables without using the preceding struct keyword as in:
error g1;
Since the compiler can perfectly distinguish between these three usages, it is perfectly legal and valid.

Note
This code is given here to just explain the concept behind. In real programming don’t use such overloading of names. It reduces the readability of the code. Possible doesn’t mean that we should use it!
  
118) #ifdef something
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer:
  Compiler error : undefined symbol some
Explanation:
This is a very simple example for conditional compilation. The name something is not already known to the compiler making the declaration 
int some = 0;
effectively removed from the source code.

119) #if something == 0
int some=0;
#endif

main()
{
int thing = 0;
printf("%d %d\n", some ,thing);
}

Answer
  0 0 
Explanation
This code is to show that preprocessor expressions are not the same as the ordinary expressions. If a name is not known the preprocessor treats it to be equal to zero. 

120). What is the output for the following program

  main()
  {
  int arr2D[3][3];
  printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
  }
Answer
1
Explanation
This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays.  
 arr2D is made up of a 3 single arrays that contains 3 integers each . 
 
 
 





The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1). 
Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1). 
Since both parts of the expression evaluates to true the result is true(1) and the same is printed.  

121) void main()
  {
if(~0 == (unsigned int)-1)
printf(“You can answer this if you know how values are represented in memory”);
  } 
 Answer
You can answer this if you know how values are represented in memory
Explanation
~ (tilde operator or bit-wise negation operator) operates on 0 to produce all ones to fill the space for an integer. –1 is represented in unsigned value as all 1’s and so both are equal.

122) int swap(int *a,int *b)
{
 *a=*a+*b;*b=*a-*b;*a=*a-*b;
}
main()
{
  int x=10,y=20;
 swap(&x,&y);
  printf("x= %d y = %d\n",x,y);
}
Answer
 x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

123) main()

char *p = “ayqm”;
printf(“%c”,++*(p++));
}
Answer:
b  

124) main()
 {
  int i=5;
  printf("%d",++i++);

Answer:
  Compiler error: Lvalue required in function main
Explanation:
  ++i yields an rvalue. For postfix ++ to operate an lvalue is required.

125) main()
{
char *p = “ayqm”;
char c;
c = ++*p++;
printf(“%c”,c);
}
Answer:
b
Explanation:
There is no difference between the expression ++*(p++) and ++*p++. Parenthesis just works as a visual clue for the reader to see which expression is first evaluated. 

126)
int aaa() {printf(“Hi”);}
int bbb(){printf(“hello”);}
iny ccc(){printf(“bye”);}

main()
{
int ( * ptr[3]) ();
ptr[0] = aaa;
ptr[1] = bbb;
ptr[2] =ccc;
ptr[2]();
}
Answer:
 bye
Explanation: 
int (* ptr[3])() says that ptr is an array of pointers to functions that takes no arguments and returns the type int. By the assignment ptr[0] = aaa; it means that the first function pointer in the array is initialized with the address of the function aaa. Similarly, the other two array elements also get initialized with the addresses of the functions bbb and ccc. Since ptr[2] contains the address of the function ccc, the call to the function ptr[2]() is same as calling ccc(). So it results in printing "bye".

127)
main()
{
int i=5;
printf(“%d”,i=++i ==6);
}

Answer:
1
Explanation:
The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true(1). Hence the result.

128) main()
{
  char p[ ]="%d\n";
p[1] = 'c';
printf(p,65);
}
Answer:
A
Explanation:
Due to the assignment p[1] = ‘c’ the string becomes, “%c\n”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
 
129) void ( * abc( int, void ( *def) () ) ) ();

Answer::
 abc is a ptr to a function which takes 2 parameters .(a). an integer variable.(b). a ptr to a funtion which returns void. the return type of the function is void.
Explanation:
  Apply the clock-wise rule to find the result.


130) main()
{
while (strcmp(“some”,”some\0”)) 
printf(“Strings are not equal\n”);
 }
Answer:
No output
Explanation:
Ending the string constant with \0 explicitly makes no difference. So “some” and “some\0” are equivalent. So, strcmp returns 0 (false) hence breaking out of the while loop. 

131) main()
{
char str1[] = {‘s’,’o’,’m’,’e’};
char str2[] = {‘s’,’o’,’m’,’e’,’\0’};
while (strcmp(str1,str2)) 
printf(“Strings are not equal\n”);
}
Answer:
“Strings are not equal”
“Strings are not equal”
….
Explanation:
If a string constant is initialized explicitly with characters, ‘\0’ is not appended automatically to the string. Since str1 doesn’t have null termination, it treats whatever the values that are in the following positions as part of the string until it randomly reaches a ‘\0’. So str1 and str2 are not the same, hence the result.
 
132) main()
{
int i = 3;
for (;i++=0;) printf(“%d”,i);
}

Answer:
  Compiler Error: Lvalue required.
Explanation:
As we know that increment operators return rvalues and hence it cannot appear on the left hand side of an assignment operation.
 
133) void main()
{
int *mptr, *cptr;
mptr = (int*)malloc(sizeof(int));
printf(“%d”,*mptr);
int *cptr = (int*)calloc(sizeof(int),1);
printf(“%d”,*cptr);
}
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.
 
134) void main()
{
static int i;
while(i<=10) (i>2)?i++:i--;
 printf(“%d”, i);
}
Answer:
  32767
Explanation:
Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.

135) main()
{
  int i=10,j=20;
 j = i, j?(i,j)?i:j:j;
  printf("%d %d",i,j);
}

Answer:
10 10
Explanation:
  The Ternary operator ( ? : ) is equivalent for if-then-else statement. So the question can be written as:
  if(i,j)
  {
if(i,j)
  j = i;
  else
  j = j;  
  }
  else
  j = j;  


136) 1. const char *a;
2. char* const a; 
3. char const *a;
-Differentiate the above declarations.

Answer:
1. 'const' applies to char * rather than 'a' ( pointer to a constant char )
 *a='F' : illegal
  a="Hi" : legal

2. 'const' applies to 'a' rather than to the value of a (constant pointer to char )
 *a='F' : legal
 a="Hi" : illegal

3. Same as 1.

137) main()
{
  int i=5,j=10;
 i=i&=j&&10;
  printf("%d %d",i,j);
}

Answer:
1 10
Explanation:
The expression can be written as i=(i&=(j&&10)); The inner expression (j&&10) evaluates to 1 because j==10. i is 5. i = 5&1 is 1. Hence the result. 

138) main()
{
  int i=4,j=7;
 j = j || i++ && printf("YOU CAN");
  printf("%d %d", i, j);
}

Answer:
4 1 
Explanation:
The boolean expression needs to be evaluated only till the truth value of the expression is not known. j is not equal to zero itself means that the expression’s truth value is 1. Because it is followed by || and true || (anything) => true where (anything) will not be evaluated. So the remaining expression is not evaluated and so the value of i remains the same.
Similarly when && operator is involved in an expression, when any of the operands become false, the whole expression’s truth value becomes false and hence the remaining expression will not be evaluated.  
 false && (anything) => false where (anything) will not be evaluated.

139) main()
{
  register int a=2;
 printf("Address of a = %d",&a);
  printf("Value of a = %d",a);
}
Answer:
Compier Error: '&' on register variable
Rule to Remember:
  & (address of ) operator cannot be applied on register variables.
 
140) main()
{
  float i=1.5;
 switch(i)
  {
  case 1: printf("1");
  case 2: printf("2");
  default : printf("0");
 }
}
Answer:
Compiler Error: switch expression not integral
Explanation:
  Switch statements can be applied only to integral types.

141) main()

  extern i;
 printf("%d\n",i);
  {
  int i=20;
  printf("%d\n",i);
  }
}
Answer:
Linker Error : Unresolved external symbol i
Explanation:
The identifier i is available in the inner block and so using extern has no use in resolving it. 

142) main()
{
  int a=2,*f1,*f2;
 f1=f2=&a;
  *f2+=*f2+=a+=2.5;
 printf("\n%d %d %d",a,*f1,*f2);
}
Answer:
16 16 16
Explanation:
f1 and f2 both refer to the same memory location a. So changes through f1 and f2 ultimately affects only the value of a. 
 
143) main()
{
  char *p="GOOD";
 char a[ ]="GOOD";
printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p), strlen(p));
 printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
}
Answer:
  sizeof(p) = 2, sizeof(*p) = 1, strlen(p) = 4
 sizeof(a) = 5, strlen(a) = 4
Explanation:
  sizeof(p) => sizeof(char*) => 2
 sizeof(*p) => sizeof(char) => 1
  Similarly,
 sizeof(a) => size of the character array => 5
When sizeof operator is applied to an array it returns the sizeof the array and it is not the same as the sizeof the pointer variable. Here the sizeof(a) where a is the character array and the size of the array is 5 because the space necessary for the terminating NULL character should also be taken into account.

144) #define DIM( array, type) sizeof(array)/sizeof(type)
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr, int));  
}
Answer:
10  
Explanation:
The size of integer array of 10 elements is 10 * sizeof(int). The macro expands to sizeof(arr)/sizeof(int) => 10 * sizeof(int) / sizeof(int) => 10. 

145) int DIM(int array[]) 
{
return sizeof(array)/sizeof(int );
}
main()
{
int arr[10];
printf(“The dimension of the array is %d”, DIM(arr));  
}
Answer:
1  
Explanation:
Arrays cannot be passed to functions as arguments and only the pointers can be passed. So the argument is equivalent to int * array (this is one of the very few places where [] and * usage are equivalent). The return statement becomes, sizeof(int *)/ sizeof(int) that happens to be equal in this case. 

146) main()
{
 static int a[3][3]={1,2,3,4,5,6,7,8,9};
 int i,j;
 static *p[]={a,a+1,a+2};
  for(i=0;i<3;i++) j="0;j<3;j++)" x="10,y="8;" x="%d" y="%d" x="8" y="10" i =" 257;" iptr =" &i;" i =" 258;" iptr =" &i;" i="300;" ptr =" &i;" ptr="2;" ptr =" 2" 00101100 =""> 556.

151) #include
main()
{
char * str = "hello";
char * ptr = str;
char least = 127;
while (*ptr++)
  least = (*ptrprintf("%d",least);
}
Answer:
0
Explanation: 
After ‘ptr’ reaches the end of the string the value pointed by ‘str’ is ‘\0’. So the value of ‘str’ is less than that of ‘least’. So the value of ‘least’ finally is 0.

152) Declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Answer:
  (char*(*)( )) (*ptr[N])( );

153) main()
{
struct student 
{
char name[30];
struct date dob;
}stud;
struct date
  { 
  int day,month,year;
  };
  scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Inside the struct definition of ‘student’ the member of type struct date is given. The compiler doesn’t have the definition of date structure (forward reference is not allowed in C in this case) so it issues an error.

154) main()
{
struct date;
struct student
{
char name[30];
struct date dob;
}stud;
struct date
  {
  int day,month,year;
 };
scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
}
Answer:
Compiler Error: Undefined structure date
Explanation:
Only declaration of struct date is available inside the structure definition of ‘student’ but to have a variable of type struct date the definition of the structure is required. 

155) There were 10 records stored in “somefile.dat” but the following program printed 11 names. What went wrong?
void main()
{
struct student

char name[30], rollno[6];
}stud;
FILE *fp = fopen(“somefile.dat”,”r”);
while(!feof(fp))
 {
  fread(&stud, sizeof(stud), 1 , fp);
puts(stud.name);
}
}
Explanation:
fread reads 10 records and prints the names successfully. It will return EOF only when fread tries to read another record and fails reading EOF (and returning EOF). So it prints the last record again. After this only the condition feof(fp) becomes false, hence comes out of the while loop. 

156) Is there any difference between the two declarations, 
1. int foo(int *arr[]) and
2. int foo(int *arr[2])
Answer:
No 
Explanation:
Functions can only pass pointers and not arrays. The numbers that are allowed inside the [] is just for more readability. So there is no difference between the two declarations.


157) What is the subtle error in the following code segment?
void fun(int n, int arr[])
{
int *p=0;
int i=0;
while(i++  p = &arr[i];
*p = 0;
}
Answer & Explanation:
If the body of the loop never executes p is assigned no address. So p remains NULL where *p =0 may result in problem (may rise to runtime error “NULL pointer assignment” and terminate the program).  

158) What is wrong with the following code?  
int *foo()
{
int *s = malloc(sizeof(int)100);
assert(s != NULL);
return s;
}
Answer & Explanation:
assert macro should be used for debugging and finding out bugs. The check s != NULL is for error/exception handling and for that assert shouldn’t be used. A plain if and the corresponding remedy statement has to be given.

159) What is the hidden bug with the following statement?
assert(val++ != 0);
Answer & Explanation:
Assert macro is used for debugging and removed in release version. In assert, the experssion involves side-effects. So the behavior of the code becomes different in case of debug version and the release version thus leading to a subtle bug. 
Rule to Remember:
Don’t use expressions that have side-effects in assert statements.  

160) void main()
{
int *i = 0x400; // i points to the address 400
*i = 0; // set the value of memory location pointed by i;
}
Answer:
Undefined behavior 
Explanation:
The second statement results in undefined behavior because it points to some location whose value may not be available for modification. This type of pointer in which the non-availability of the implementation of the referenced location is known as 'incomplete type'.

161) #define assert(cond) if(!(cond)) \
  (fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
 __FILE__,__LINE__), abort())

void main()
{
int i = 10;
if(i==0) 
  assert(i < 100); 
else
  printf("This statement becomes else for if in assert macro");
}
Answer:
No output
Explanation:
The else part in which the printf is there becomes the else for if in the assert macro. Hence nothing is printed. 
The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s, file %s, line %d \n",#cond, __FILE__,__LINE__), abort()))

Note:
However this problem of “matching with nearest else” cannot be solved by the usual method of placing the if statement inside a block like this,
#define assert(cond) { \
if(!(cond)) \
  (fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
 __FILE__,__LINE__), abort()) \
}

162) Is the following code legal?
struct a
  { 
int x;
 struct a b;
  }
Answer:
  No
Explanation:
Is it not legal for a structure to contain a member that is of the same
type as in this case. Because this will cause the structure declaration to be recursive without end.

163) Is the following code legal?
struct a
  { 
int x;
  struct a *b;
  }
Answer:
Yes.
Explanation:
*b is a pointer to type struct a and so is legal. The compiler knows, the size of the pointer to a structure even before the size of the structure
is determined(as you know the pointer to any type is of same size). This type of structures is known as ‘self-referencing’ structure.

164) Is the following code legal?
typedef struct a
  { 
int x;
 aType *b;
  }aType
Answer:
  No
Explanation:
The typename aType is not known at the point of declaring the structure (forward references are not made for typedefs).

165) Is the following code legal?
typedef struct a aType;
struct a

int x;
aType *b;
};
Answer:
 Yes
Explanation:
The typename aType is known at the point of declaring the structure, because it is already typedefined.

166) Is the following code legal?
void main()
{
typedef struct a aType;
aType someVariable;
struct a

int x;
  aType *b;
  };
}
Answer:
  No
Explanation:
  When the declaration,
typedef struct a aType;
is encountered body of struct a is not known. This is known as ‘incomplete types’.
 
167) void main()
{
printf(“sizeof (void *) = %d \n“, sizeof( void *));
 printf(“sizeof (int *) = %d \n”, sizeof(int *));
 printf(“sizeof (double *) = %d \n”, sizeof(double *));
 printf(“sizeof(struct unknown *) = %d \n”, sizeof(struct unknown *));
 }
Answer :
sizeof (void *) = 2
sizeof (int *) = 2
sizeof (double *) = 2
sizeof(struct unknown *) = 2
Explanation:
The pointer to any type is of same size.

168) char inputString[100] = {0};
To get string input from the keyboard which one of the following is better?
 1) gets(inputString)
 2) fgets(inputString, sizeof(inputString), fp)
Answer & Explanation:
The second one is better because gets(inputString) doesn't know the size of the string passed and so, if a very big input (here, more than 100 chars) the charactes will be written past the input string. When fgets is used with stdin performs the same operation as gets but is safe.

169) Which version do you prefer of the following two,
1) printf(“%s”,str); // or the more curt one
2) printf(str);
Answer & Explanation:
Prefer the first one. If the str contains any format characters like %d then it will result in a subtle bug. 

170) void main()
{
int i=10, j=2;
int *ip= &i, *jp = &j;
int k = *ip/*jp;
printf(“%d”,k);

Answer: 
Compiler Error: “Unexpected end of file in comment started in line 5”.
Explanation:
The programmer intended to divide two integers, but by the “maximum munch” rule, the compiler treats the operator sequence / and * as /* which happens to be the starting of comment. To force what is intended by the programmer,
int k = *ip/ *jp; 
// give space explicity separating / and * 
//or
int k = *ip/(*jp);
// put braces to force the intention  
will solve the problem.  

171) void main()
{
char ch;
for(ch=0;ch<=127;ch++)
printf(“%c %d \n“, ch, ch);
}
Answer: 
 Implementaion dependent
Explanation:
The char type may be signed or unsigned by default. If it is signed then ch++ is executed after ch reaches 127 and rotates back to -128. Thus ch is always smaller than 127.

172) Is this code legal?
int *ptr; 
ptr = (int *) 0x400; Answer: 
  Yes
Explanation:
The pointer ptr will point at the integer in the memory location 0x400. 
173) main()
{
char a[4]="HELLO";
printf("%s",a);

Answer: 
  Compiler error: Too many initializers
Explanation:
The array a is of size 4 but the string constant requires 6 bytes to get stored.

174) main()

char a[4]="HELL";
printf("%s",a);
}
Answer: 
  HELL%@!~@!@???@~~!
Explanation:
The character array has the memory just enough to hold the string “HELL” and doesnt have enough space to store the terminating null character. So it prints the HELL correctly and continues to print garbage values till it accidentally comes across a NULL character.

175) main()

  int a=10,*j;
 void *k; 
  j=k=&a;
  j++;  
  k++;
  printf("\n %u %u ",j,k);

Answer: 
  Compiler error: Cannot increment a void pointer
Explanation:
Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers.

176) main()
  {
  extern int i;
  { int i=20;
  {  
  const volatile unsigned i=30; printf("%d",i); 
  }
  printf("%d",i);
  }
  printf("%d",i);
 } 
 int i;

177) Printf can be implemented by using __________ list.
Answer: 
  Variable length argument lists
178) char *someFun()
  {
  char *temp = “string constant";
  return temp;
  }
  int main()
  {
  puts(someFun());
  }
Answer:
  string constant 
Explanation:
  The program suffers no problem and gives the output correctly because the character constants are stored in code/data area and not allocated in stack, so this doesn’t lead to dangling pointers. 

179) char *someFun1()
  {
  char temp[ ] = “string";
  return temp;
  }
  char *someFun2()
  {
  char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
  return temp;
  }
  int main()
  {
  puts(someFun1());
  puts(someFun2());
  }
Answer:
 Garbage values.
Explanation:
 Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.