Thursday, November 13, 2008

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

Sql Interview Questions

SQL

1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL)

2. What operator performs pattern matching?
LIKE operator

3. What operator tests column for the absence of data?
IS NULL operator

4. Which command executes the contents of a specified file?
START or @

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

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

7. What are the wildcards used for pattern matching?
_ for single character substitution and % for multi-character substitution

8. State true or false. EXISTS, SOME, ANY are operators in SQL.
True

9. State true or false. !=, <>, ^= all denote the same operation.
True

10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all

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

12. Which system tables contain information on privileges granted and privileges obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

13. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS

14. TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP.

15. What is the difference between TRUNCATE and DELETE commands?
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE.

16. What command is used to create a table by copying the structure of another table?
Answer :
CREATE TABLE .. AS SELECT command
Explanation :
To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

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

18. What will be the output of the following query?
SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );
Answer :
NO
Explanation :
The query checks whether a given string is a numerical digit.

19. What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;
This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.


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

21. Why does the following command give a compilation error?
DROP TABLE &TABLE_NAME;
Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

22. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

23. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.

24. What is the value of ‘comm’ and ‘sal’ after executing the following query if the initial value of ‘sal’ is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000

25. What is the use of DESC in SQL?
Answer :
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

26. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

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

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






SQL – QUERIES

I. SCHEMAS

Table 1 : STUDIES

PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER)

Table 2 : SOFTWARE

PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), SCOST (NUMBER), DCOST (NUMBER), SOLD (NUMBER)

Table 3 : PROGRAMMER

PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL (NUMBER)

LEGEND :

PNAME – Programmer Name, SPLACE – Study Place, CCOST – Course Cost, DEVIN – Developed in, SCOST – Software Cost, DCOST – Development Cost, PROF1 – Proficiency 1

QUERIES :

1. Find out the selling cost average for packages developed in Oracle.
2. Display the names, ages and experience of all programmers.
3. Display the names of those who have done the PGDCA course.
4. What is the highest number of copies sold by a package?
5. Display the names and date of birth of all programmers born in April.
6. Display the lowest course fee.
7. How many programmers have done the DCA course.
8. How much revenue has been earned through the sale of packages developed in C.
9. Display the details of software developed by Rakesh.
10. How many programmers studied at Pentafour.
11. Display the details of packages whose sales crossed the 5000 mark.
12. Find out the number of copies which should be sold in order to recover the development cost of each package.
13. Display the details of packages for which the development cost has been recovered.
14. What is the price of costliest software developed in VB?
15. How many packages were developed in Oracle ?
16. How many programmers studied at PRAGATHI?
17. How many programmers paid 10000 to 15000 for the course?
18. What is the average course fee?
19. Display the details of programmers knowing C.
20. How many programmers know either C or Pascal?
21. How many programmers don’t know C and C++?
22. How old is the oldest male programmer?
23. What is the average age of female programmers?
24. Calculate the experience in years for each programmer and display along with their names in descending order.
25. Who are the programmers who celebrate their birthdays during the current month?
26. How many female programmers are there?
27. What are the languages known by the male programmers?
28. What is the average salary?
29. How many people draw 5000 to 7500?
30. Display the details of those who don’t know C, C++ or Pascal.
31. Display the costliest package developed by each programmer.
32. Produce the following output for all the male programmers
Programmer
Mr. Arvind – has 15 years of experience

KEYS:

1. SELECT AVG(SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE';
2. SELECT PNAME,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12) "AGE", TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) "EXPERIENCE" FROM PROGRAMMER;
3. SELECT PNAME FROM STUDIES WHERE COURSE = 'PGDCA';
4. SELECT MAX(SOLD) FROM SOFTWARE;
5. SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '%APR%';
6. SELECT MIN(CCOST) FROM STUDIES;
7. SELECT COUNT(*) FROM STUDIES WHERE COURSE = 'DCA';
8. SELECT SUM(SCOST*SOLD-DCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C';
9. SELECT * FROM SOFTWARE WHERE PNAME = 'RAKESH';
10. SELECT * FROM STUDIES WHERE SPLACE = 'PENTAFOUR';
11. SELECT * FROM SOFTWARE WHERE SCOST*SOLD-DCOST > 5000;
12. SELECT CEIL(DCOST/SCOST) FROM SOFTWARE;
13. SELECT * FROM SOFTWARE WHERE SCOST*SOLD >= DCOST;
14. SELECT MAX(SCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'VB';
15. SELECT COUNT(*) FROM SOFTWARE WHERE DEVIN = 'ORACLE';
16. SELECT COUNT(*) FROM STUDIES WHERE SPLACE = 'PRAGATHI';
17. SELECT COUNT(*) FROM STUDIES WHERE CCOST BETWEEN 10000 AND 15000;
18. SELECT AVG(CCOST) FROM STUDIES;
19. SELECT * FROM PROGRAMMER WHERE PROF1 = 'C' OR PROF2 = 'C';
20. SELECT * FROM PROGRAMMER WHERE PROF1 IN ('C','PASCAL') OR PROF2 IN ('C','PASCAL');
21. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++');
22. SELECT TRUNC(MAX(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'M';
23. SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'F';
24. SELECT PNAME, TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) FROM PROGRAMMER ORDER BY PNAME DESC;
25. SELECT PNAME FROM PROGRAMMER WHERE TO_CHAR(DOB,'MON') = TO_CHAR(SYSDATE,'MON');
26. SELECT COUNT(*) FROM PROGRAMMER WHERE SEX = 'F';
27. SELECT DISTINCT(PROF1) FROM PROGRAMMER WHERE SEX = 'M';
28. SELECT AVG(SAL) FROM PROGRAMMER;
29. SELECT COUNT(*) FROM PROGRAMMER WHERE SAL BETWEEN 5000 AND 7500;
30. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++','PASCAL') AND PROF2 NOT IN ('C','C++','PASCAL');
31. SELECT PNAME,TITLE,SCOST FROM SOFTWARE WHERE SCOST IN (SELECT MAX(SCOST) FROM SOFTWARE GROUP BY PNAME);
32.SELECT 'Mr.' || PNAME || ' - has ' || TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) || ' years of experience' “Programmer” FROM PROGRAMMER WHERE SEX = 'M' UNION SELECT 'Ms.' || PNAME || ' - has ' || TRUNC (MONTHS_BETWEEN (SYSDATE,DOJ)/12) || ' years of experience' “Programmer” FROM PROGRAMMER WHERE SEX = 'F';



II . SCHEMA :

Table 1 : DEPT

DEPTNO (NOT NULL , NUMBER(2)), DNAME (VARCHAR2(14)),
LOC (VARCHAR2(13)

Table 2 : EMP

EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR2(10)),
JOB (VARCHAR2(9)), MGR (NUMBER(4)), HIREDATE (DATE),
SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2))

MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key.
QUERIES

1. List all the employees who have at least one person reporting to them.
2. List the employee details if and only if more than 10 employees are present in department no 10.
3. List the name of the employees with their immediate higher authority.
4. List all the employees who do not manage any one.
5. List the employee details whose salary is greater than the lowest salary of an employee belonging to deptno 20.
6. List the details of the employee earning more than the highest paid manager.
7. List the highest salary paid for each job.
8. Find the most recently hired employee in each department.
9. In which year did most people join the company? Display the year and the number of employees.
10. Which department has the highest annual remuneration bill?
11. Write a query to display a ‘*’ against the row of the most recently hired employee.
12. Write a correlated sub-query to list out the employees who earn more than the average salary of their department.
13. Find the nth maximum salary.
14. Select the duplicate records (Records, which are inserted, that already exist) in the EMP table.
15. Write a query to list the length of service of the employees (of the form n years and m months).

KEYS:

1. SELECT DISTINCT(A.ENAME) FROM EMP A, EMP B WHERE A.EMPNO = B.MGR; or SELECT ENAME FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP);
2. SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND DEPTNO=10);
3. SELECT A.ENAME "EMPLOYEE", B.ENAME "REPORTS TO" FROM EMP A, EMP B WHERE A.MGR=B.EMPNO;
4. SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP MINUS SELECT MGR FROM EMP);
5. SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO HAVING DEPTNO=20);
6. SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP GROUP BY JOB HAVING JOB = 'MANAGER' );
7. SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB;
8. SELECT * FROM EMP WHERE (DEPTNO, HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE) FROM EMP GROUP BY DEPTNO);
9. SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY') HAVING COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO)) FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY'));
10. SELECT DEPTNO, LPAD(SUM(12*(SAL+NVL(COMM,0))),15) "COMPENSATION" FROM EMP GROUP BY DEPTNO HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP GROUP BY DEPTNO);
11. SELECT ENAME, HIREDATE, LPAD('*',8) "RECENTLY HIRED" FROM EMP WHERE HIREDATE = (SELECT MAX(HIREDATE) FROM EMP) UNION SELECT ENAME NAME, HIREDATE, LPAD(' ',15) "RECENTLY HIRED" FROM EMP WHERE HIREDATE != (SELECT MAX(HIREDATE) FROM EMP);
12. SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL) FROM EMP F WHERE E.DEPTNO = F.DEPTNO);
13. SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT(SAL)) FROM EMP B WHERE A.SAL<=B.SAL);
14. SELECT * FROM EMP A WHERE A.EMPNO IN (SELECT EMPNO FROM EMP GROUP BY EMPNO HAVING COUNT(EMPNO)>1) AND A.ROWID!=MIN (ROWID));
15. SELECT ENAME "EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12))||' YEARS '|| TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN (SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE" FROM EMP;

Oracle Interview Questions

Oracle Sample Questions : Oracle Interview Questions
1.What is a transaction ?
Answer: A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements.
1. What is implicit cursor and how is it used by Oracle ?
Answer: An implicit cursor is a cursor which is internally created by Oracle.It is created by Oracle for each individual SQL.
2. Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ?
Answer: Public synonyms
3. What is PL/SQL?
Answer: PL/SQL is Oracle's Procedural Language extension to SQL.The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools.
4. Is there a PL/SQL Engine in SQL*Plus?
Answer: No.Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine.Thus, all your PL/SQL are send directly to the database engine for execution.This makes it much more efficient as SQL statements are not stripped off and send to the database individually.
5. Is there a limit on the size of a PL/SQL block?
Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K.You can run the following select statement to query the size of an existing package or procedure. SQL> select * from dba_object_size where name = 'procedure_name'
6. Can one read/write files from PL/SQL?
Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=...parameter).Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn', func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;
7. How can I protect my PL/SQL source code?
Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code.This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original).This way you can distribute software without having to worry about exposing your proprietary algorithms and methods.SQL*Plus and SQL*DBA will still understand and know how to execute such scripts.Just be careful, there is no "decode" command available. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy
8. Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ?
Answer: From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements.
Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
21. What are the various types of Exceptions ?
Answer: User defined and Predefined Exceptions.
22. Can we define exceptions twice in same block ?
Answer: No.
23. What is the difference between a procedure and a function ?
Answer: Functions return a single variable by value whereas procedures do not return any variable by value.Rather they return multiple variables by passing variables by reference through their OUT parameter.
24. Can you have two functions with the same name in a PL/SQL block ?
Answer: Yes.
25. Can you have two stored functions with the same name ?
Answer: Yes.
26. Can you call a stored function in the constraint of a table ?
Answer: No.
27. What are the various types of parameter modes in a procedure ?
Answer: IN, OUT AND INOUT.
28. What is Over Loading and what are its restrictions ?
Answer: OverLoading means an object performing different functions depending upon the no.of parameters or the data type of the parameters passed to it.
29. Can functions be overloaded ?
Answer: Yes.
30. Can 2 functions have same name & input parameters but differ only by return datatype
Answer: No.
31. What are the constructs of a procedure, function or a package ?
Answer: The constructs of a procedure, function or a package are :
• variables and constants
• cursors
• exceptions
32. Why Create or Replace and not Drop and recreate procedures ?
Answer: So that Grants are not dropped.
33. Can you pass parameters in packages ? How ?
Answer: Yes.You can pass parameters to procedures or functions in a package.
34. What are the parts of a database trigger ?
Answer: The parts of a trigger are:
• A triggering event or statement
• A trigger restriction
• A trigger action
35. What are the various types of database triggers ?
Answer: There are 12 types of triggers, they are combination of :
• Insert, Delete and Update Triggers.
• Before and After Triggers.
• Row and Statement Triggers.
36. What is the advantage of a stored procedure over a database trigger ?
Answer: We have control over the firing of a stored procedure but we have no control over the firing of a trigger.
37. What is the maximum no.of statements that can be specified in a trigger statement ?
Answer: One.
38. Can views be specified in a trigger statement ?
Answer: No
39. What are the values of :new and :old in Insert/Delete/Update Triggers ?
Answer: INSERT : new = new value, old = NULL
DELETE : new = NULL, old = old value
UPDATE : new = new value, old = old value
40. What are cascading triggers? What is the maximum no of cascading triggers at a time?
Answer: When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading.Max = 32.
41. What are mutating triggers ?
Answer: A trigger giving a SELECT on the table on which the trigger is written.
42. What are constraining triggers ?
Answer: A trigger giving an Insert/Updat e on a table having referential integrity constraint on the triggering table.
43. Describe Oracle database's physical and logical structure ?
Answer:
• Physical : Data files, Redo Log files, Control file.
• Logical : Tables, Views, Tablespaces, etc.
44. Can you increase the size of a tablespace ? How ?
Answer: Yes, by adding datafiles to it.
45. Can you increase the size of datafiles ? How ?
Answer: No (for Oracle 7.0)
Yes (for Oracle 7.3 by using the Resize clause )
46. What is the use of Control files ?
Answer: Contains pointers to locations of various data files, redo log files, etc.
47. What is the use of Data Dictionary ?
Answer: It Used by Oracle to store information about various physical and logical Oracle structures e.g.Tables, Tablespaces, datafiles, etc
48. What are the advantages of clusters ?
Answer: Access time reduced for joins.
49. What are the disadvantages of clusters ?
Answer: The time for Insert increases.
50. Can Long/Long RAW be clustered ?
Answer: No.
51. Can null keys be entered in cluster index, normal index ?
Answer: Yes.
52. Can Check constraint be used for self referential integrity ? How ?
Answer: Yes.In the CHECK condition for a column of a table, we can reference some other column of the same table and thus enforce self referential integrity.
53. What are the min.extents allocated to a rollback extent ?
Answer: Two
54. What are the states of a rollback segment ? What is the difference between partly available and needs recovery ?
Answer: The various states of a rollback segment are :
• ONLINE
• OFFLINE
• PARTLY AVAILABLE
• NEEDS RECOVERY
• INVALID.
55. What is the difference between unique key and primary key ?
Answer: Unique key can be null; Primary key cannot be null.
56. An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ?
Answer: No.
57. Can you define multiple savepoints ?
Answer: Yes.
58. Can you Rollback to any savepoint ?
Answer: Yes.
59. What is the maximum no.of columns a table can have ?
Answer: 254.
60. What is the significance of the & and && operators in PL SQL ?
Answer: The & operator means that the PL SQL block requires user input for a variable.
The && operator means that the value of this variable should be the same as inputted by the user previously for this same variable
61. Can you pass a parameter to a cursor ?
Answer: Explicit cursors can take parameters, as the example below shows.A cursor parameter can appear in a query wherever a constant can appear.
CURSOR c1 (median IN NUMBER) IS
SELECT job, ename FROM emp WHERE sal > median;
62. What are the various types of RollBack Segments ?
Answer: The types of Rollback sagments are as follows :
• Public Available to all instances
• Private Available to specific instance
63. Can you use %RowCount as a parameter to a cursor ?
Answer: Yes
64. Is the query below allowed :
Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of Number(4) and Char(15))
Answer: Yes
65. Is the assignment given below allowed :
ABC = PQR (Where ABC and PQR are records)
Answer: Yes
66. Is this for loop allowed :
For x in &Start..&End Loop
Answer: Yes
67. How many rows will the following SQL return :
Select * from emp Where rownum < 10;
Answer: 9 rows
68. How many rows will the following SQL return :
Select * from emp Where rownum = 10;
Answer: No rows
69. Which symbol preceeds the path to the table in the remote database ?
Answer: @
70. Are views automatically updated when base tables are updated ?
Answer: Yes
71. Can a trigger written for a view ?
Answer: No
72. If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last record or first record ?
Answer: Last Record
73. A table has the following data : [[5, Null, 10]].What will the average function return ?
Answer: 7.5
74. Is Sysdate a system variable or a system function?
Answer: System Function
75. Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we get the next number 2.Suppose at this point we issue an rollback and again issue a nextval.What will the output be ?
Answer: 3
76. Definition of relational DataBase by Dr.Codd (IBM)?
Answer: A Relational Database is a database where all data visible to the user is organized strictly as tables of data values and where all database operations work on these tables.
77. What is Multi Threaded Server (MTA) ?
Answer: In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates a separate process for each database user.But in MTA the database manager can assign multiple users (multiple user processes) to a single dispatcher (server process), a controlling process that queues request for work thus reducing the databases memory requirement and resources.
78. Which are initial RDBMS, Hierarchical & N/w database ?
Answer:
• RDBMS - R system
• Hierarchical - IMS
• N/W - DBTG
79. Difference between Oracle 6 and Oracle 7
Answer:
ORACLE 7 ORACLE 6
Cost based optimizer Rule based optimizer
Shared SQL Area SQL area allocated for each user
Multi Threaded Server Single Threaded Server
Hash Clusters Only B-Tree indexing
Roll back Size Adjustment No provision
Truncate command No provision
Distributed Database Distributed Query
Table replication & snapshots No provision
Client/Server Tech No provision
80. What is Functional Dependency
Answer: Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each X-value has associated with it precisely one -Y value in R
81. What is Auditing ?
Answer: The database has the ability to audit all actions that take place within it. a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL
82. While designing in client/server what are the 2 imp.things to be considered ?
Answer: Network Overhead (traffic), Speed and Load of client server
83. What are the disadvantages of SQL ?
Answer: Disadvantages of SQL are :
• Cannot drop a field
• Cannot rename a field
• Cannot manage memory
• Procedural Language option not provided
• Index on view or index on index not provided
• View updation problem
84. When to create indexes ?
Answer: To be created when table is queried for less than 2% or 4% to 25% of the table rows.
85. How can you avoid indexes ?
Answer: To make index access path unavailable
• Use FULL hint to optimizer for full table scan
• Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another.
• Use an expression in the Where Clause of the SQL.
86. What is the result of the following SQL :
Select 1 from dual UNION Select 'A' from dual;
Answer: Error
87. Can database trigger written on synonym of a table and if it can be then what would be the effect if original table is accessed.
Answer: Yes, database trigger would fire.
88. Can you alter synonym of view or view ?
Answer: No
89. Can you create index on view
Answer: No.
90. What is the difference between a view and a synonym ?
Answer: Synonym is just a second name of table used for multiple link of database.View can be created with many tables, and with virtual columns and with conditions.But synonym can be on view.
91. What's the length of SQL integer ?
Answer: 32 bit length
92. What is the difference between foreign key and reference key ?
Answer: Foreign key is the key i.e.attribute which refers to another table primary key. Reference key is the primary key of table referred by another table.
93. Can dual table be deleted, dropped or altered or updated or inserted ?
Answer: Yes
94. If content of dual is updated to some value computation takes place or not ?
Answer: Yes
95. If any other table same as dual is created would it act similar to dual?
Answer: Yes
96. For which relational operators in where clause, index is not used ?
Answer: <> , like '%...' is NOT functions, field +constant, field||''
97. .Assume that there are multiple databases running on one machine.How can you switch from one to another ?
Answer: Changing the ORACLE_SID
98. What are the advantages of Oracle ?
Answer: Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100 hardware platforms and 20 networking protocols. Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than most of its competitors earn in total revenue.This market clout means that you are unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces available. Backup and Recovery : Oracle provides industrial strength support for on-line backup and recovery and good software fault tolerence to disk failure.You can also do point-in-time recovery. Performance : Speed of a 'tuned' Oracle Database and application is quite good, even with large databases.Oracle can manage > 100GB databases. Multiple database support : Oracle has a superior ability to manage multiple databases within the same transaction using a two-phase commit protocol.
99. What is a forward declaration ? What is its use ?
Answer: PL/SQL requires that you declare an identifier before using it.Therefore, you must declare a subprogram before calling it.This declaration at the start of a subprogram is called forward declaration.A forward declaration consists of a subprogram specification terminated by a semicolon.
100. What are actual and formal parameters ?
Answer: Actual Parameters : Subprograms pass information using parameters.The variables or expressions referenced in the parameter list of a subprogram call are actual parameters.For example, the following procedure call lists two actual parameters named emp_num and amount:
Eg.raise_salary(emp_num, amount);
Formal Parameters : The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters.For example, the following procedure declares two formal parameters named emp_id and increase:
Eg.PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL;
101. What are the types of Notation ?
Answer: Position, Named, Mixed and Restrictions.
102. What all important parameters of the init.ora are supposed to be increased if you want to increase the SGA size ?
Answer: In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 & 3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database creation}. The initial SGA was around 4MB when the server RAM was 32MB and The new SGA was around 13MB when the server RAM was increased to 128MB.
103. .If I have an execute privilege on a procedure in another users schema, can I execute his procedure even though I do not have privileges on the tables within the procedure ?
Answer: Yes
104. What are various types of joins ?
Answer: Types of joins are:
• Equijoins
• Non-equijoins
• self join
• outer join
105. What is a package cursor ?
Answer: A package cursor is a cursor which you declare in the package specification without an SQL statement.The SQL statement for the cursor is attached dynamically at runtime from calling procedures.
106. If you insert a row in a table, then create another table and then say Rollback.In this case will the row be inserted ?
Answer: Yes.Because Create table is a DDL which commits automatically as soon as it is executed.The DDL commits the transaction even if the create statement fails internally (eg table already exists error) and not syntactically.

C++ Interview Questions

C,C++ Questions
1. Base class has some virtual method and derived class has a method with the same name. If we initialize the base class pointer with derived
object,. calling of that virtual method will result in which method being called?
a. Base method
b. Derived method..
Ans. b
2. For the following C program
#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans. Area of the circle is 122.656250
Area of the circle is 19.625000
3. What do the following statements indicate. Explain.
• int(*p)[10]
• int*f()
• int(*pf)()
• int*p[10]
Refer to:
-- Kernighan & Ritchie page no. 122
-- Schaum series page no. 323
4.
void main()
{
int d=5;
printf("%f",d);
}
Ans: Undefined




5.
void main()
{
int i;
for(i=1;i<4,i++)
switch(i)
case 1: printf("%d",i);break;
{
case 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}
Ans: 1,2,3,4

6.
void main()
{
char *s="\12345s\n";
printf("%d",sizeof(s));
}
Ans: 6

7.
void main()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(iprintf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}
Ans: less




8.
void main()
{
float j;
j=1000*1000;
printf("%f",j);
}

1. 1000000
2. Overflow
3. Error
4. None
Ans: 4

9. How do you declare an array of N pointers to functions returning
pointers to functions returning pointers to characters?

Ans: The first part of this question can be answered in at least
three ways:

1. char *(*(*a[N])())();

2. Build the declaration up incrementally, using typedefs:

typedef char *pc; /* pointer to char */
typedef pc fpc(); /* function returning pointer to char */
typedef fpc *pfpc; /* pointer to above */
typedef pfpc fpfpc(); /* function returning... */
typedef fpfpc *pfpfpc; /* pointer to... */
pfpfpc a[N]; /* array of... */

3. Use the cdecl program, which turns English into C and vice
versa:

cdecl> declare a as array of pointer to function returning
pointer to function returning pointer to char
char *(*(*a[])())()

cdecl can also explain complicated declarations, help with
casts, and indicate which set of parentheses the arguments
go in (for complicated function definitions, like the one
above).
Any good book on C should explain how to read these complicated
C declarations "inside out" to understand them ("declaration
mimics use").
The pointer-to-function declarations in the examples above have
not included parameter type information. When the parameters
have complicated types, declarations can *really* get messy.
(Modern versions of cdecl can help here, too.)


10. A structure pointer is defined of the type time . With 3 fields min,sec hours having pointers to intergers.
Write the way to initialize the 2nd element to 10.

11. In the above question an array of pointers is declared.
Write the statement to initialize the 3rd element of the 2 element to 10;

12.
int f()
void main()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf("%d %d %d",i,j,k);
}

What are the number of syntax errors in the above?

Ans: None.

13.
void main()
{
int i=7;
printf("%d",i++*i++);
}

Ans: 56

14.
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");

Ans: "one is defined"




15.
void main()
{
int count=10,*temp,sum=0;
temp=&count;
*temp=20;
temp=∑
*temp=count;
printf("%d %d %d ",count,*temp,sum);
}

Ans: 20 20 20


16. There was question in c working only on unix machine with pattern matching.


14. what is alloca()
Ans : It allocates and frees memory after use/after getting out of scope

17.
main()
{
static i=3;
printf("%d",i--);
return i>0 ? main():0;
}

Ans: 321

18.
char *foo()
{
char result[100]);
strcpy(result,"anything is good");
return(result);
}
void main()
{
char *j;
j=foo()
printf("%s",j);
}

Ans: anything is good.

19.
void main()
{
char *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s",++*p);
printf("%s",*p++);
printf("%s",++*p);
}
Ans: "harma" (p->add(dharma) && (*p)->harma)
"harma" (after printing, p->add(hewlett-packard) &&(*p)->harma)
"ewlett-packard"
20. Output of the following program is
main()
{int i=0;
for(i=0;i<20;i++)
{switch(i)
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default i+=4;
break;}
printf("%d,",i);
}
}
a) 0,5,9,13,17
b) 5,9,13,17
c) 12,17,22
d) 16,21
e) Syntax error
Ans. (d)
21. What is the ouptut in the following program
main()
{char c=-64;
int i=-32
unsigned int u =-16;
if(c>i)
{printf("pass1,");
if(cprintf("pass2");
else
printf("Fail2");
}
else
printf("Fail1);
if(iprintf("pass2");
else
printf("Fail2")
}
a) Pass1,Pass2
b) Pass1,Fail2
c) Fail1,Pass2
d) Fail1,Fail2
e) None of these
Ans. (c)
22. What will the following program do?
void main()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("(%s, %s)",a,p);
free(p);
free(a);
} //Line number 15//
a) Swap contents of p & a and print:(New string, string)
b) Generate compilation error in line number 8
c) Generate compilation error in line number 5
d) Generate compilation error in line number 7
e) Generate compilation error in line number 1
Ans. (b)
23. In the following code segment what will be the result of the function,
value of x , value of y
{unsigned int x=-1;
int y;
y = ~0;
if(x == y)
printf("same");
else
printf("not same");
}
a) same, MAXINT, -1
b) not same, MAXINT, -MAXINT
c) same , MAXUNIT, -1
d) same, MAXUNIT, MAXUNIT
e) not same, MAXINT, MAXUNIT
Ans. (a)
24. What will be the result of the following program ?
char *gxxx()
{static char xxx[1024];
return xxx;
}
main()
{char *g="string";
strcpy(gxxx(),g);
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
a) The string is : string
b) The string is :Oldstring
c) Run time error/Core dump
d) Syntax error during compilation
e) None of these
Ans. (b)
25. Find the output for the following C program
main()
{
char *p1="Name";
char *p2;
p2=(char *)malloc(20);
while(*p2++=*p1++);
printf("%s\n",p2);
}
Ans. An empty string
26. Find the output for the following C program
main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d\n",x,y);
}
Ans. 57 94
27. Find the output for the following C program
main()
{
int x=5;
printf("%d %d %d\n",x,x<<2,x>>2);
}
Ans. 5 20 1
28 Find the output for the following C program
#define swap1(a,b) a=a+b;b=a-b;a=a-b;
main()
{
int x=5,y=10;
swap1(x,y);
printf("%d %d\n",x,y);
swap2(x,y);
printf("%d %d\n",x,y);
}
int swap2(int a,int b)
{
int temp;
temp=a;
b=a;
a=temp;
return;
}
Ans. 10 5

29 Find the output for the following C program
main()
{
char *ptr = "Ramco Systems";
(*ptr)++;
printf("%s\n",ptr);
ptr++;
printf("%s\n",ptr);
}
Ans. Samco Systems

30 Find the output for the following C program
#include
main()
{
char s1[]="Ramco";
char s2[]="Systems";
s1=s2;
printf("%s",s1);
}
Ans. Compilation error giving it cannot be an modifiable 'lvalue'

31 Find the output for the following C program
#include
main()
{
char *p1;
char *p2;
p1=(char *) malloc(25);
p2=(char *) malloc(25);
strcpy(p1,"Ramco");
strcpy(p2,"Systems");
strcat(p1,p2);
printf("%s",p1);
}
Ans. RamcoSystems

32. Find the output for the following C program given that
[1]. The following variable is available in file1.c
static int average_float;
Ans. All the functions in the file1.c can access the variable

33. Find the output for the following C program
# define TRUE 0
some code
while(TRUE)
{
some code
}
Ans. This won't go into the loop as TRUE is defined as 0
34. struct list{
int x;
struct list *next;
}*head;

the struct head.x =100

Is the above assignment to pointer is correct or wrong ?
Ans. Wrong
35.What is the output of the following ?

int i;
i=1;
i=i+2*i++;
printf(%d,i);
Ans. 4
36. FILE *fp1,*fp2;

fp1=fopen("one","w")
fp2=fopen("one","w")
fputc('A',fp1)
fputc('B',fp2)
fclose(fp1)
fclose(fp2)
}

Find the Error, If Any?
Ans. no error. But It will over writes on same file.
37. What are the output(s) for the following ?
38. #include
char *f()
{char *s=malloc(8);
strcpy(s,"goodbye");
}

main()
{
char *f();
printf("%c",*f()='A'); }


39. #define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
Ans. 10 5 0
40.
void main()
{
int i=7;
printf("%d",i++*i++);
}

Ans: 56


C Aptitude Questions

1. void main()
2. {
3. int const * p=5;
4. printf("%d",++(*p));
5. }
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".
6. main()
7. {
8. char s[ ]="man";
9. int i;
10. for(i=0;s[ i ];i++)
11. printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
12. }
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].
13. main()
14. {
15. float me = 1.1;
16. double you = 1.1;
17. if(me==you)
18. printf("I love U");
19. else
20. printf("I hate U");
21. }
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()
5. {
6. static int var = 5;
7. printf("%d ",var--);
8. if(var)
9. main();
10. }
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.
11. main()
12. {
13. int c[ ]={2.8,3.4,4,6.7,5};
14. int j,*p=c,*q=c;
15. for(j=0;j<5;j++) {
16. printf(" %d ",*c);
17. ++q; }
18. for(j=0;j<5;j++){
19. printf(" %d ",*p);
20. ++p; }
21. }
22. Answer:
2 2 2 2 2 2 3 4 6 5
Explanation:
Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.
23. main()
24. {
25. extern int i;
26. i=20;
27. printf("%d",i);
28. }
Answer:
Linker Error : Undefined symbol '_i'
Explanation:
extern storage class in the following declaration,
extern int i;
specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .
29. main()
30. {
31. int i=-1,j=-1,k=0,l=2,m;
32. m=i++&&j++&&k++||l++;
33. printf("%d %d %d %d %d",i,j,k,l,m);
34. }
Answer:
0 0 1 3 1
Explanation :
Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression 'i++ && j++ && k++' is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for '0 || 0' combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.
8. main()
9. {
10. char *p;
11. printf("%d %d ",sizeof(*p),sizeof(p));
12. }
Answer:
1 2
Explanation:
The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.
13. main()
14. {
15. int i=3;
16. switch(i)
17. {
18. default:printf("zero");
19. case 1: printf("one");
20. break;
21. case 2:printf("two");
22. break;
23. case 3: printf("three");
24. break;
25. }
26. }
Answer :
three
Explanation :
The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.
27. main()
28. {
29. printf("%x",-1<<4);
30. }
Answer:
fff0
Explanation :
-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.
31. main()
32. {
33. char string[]="Hello World";
34. display(string);
35. }
36. void display(char *string)
37. {
38. printf("%s",string);
39. }
Answer:
Compiler Error : Type mismatch in redeclaration of function display
Explanation :
In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.
12. main()
13. {
14. int c=- -2;
15. printf("c=%d",c);
16. }
Answer:
c=2;
Explanation:
Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
Note:
However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.
17. #define int char
18. main()
19. {
20. int i=65;
21. printf("sizeof(i)=%d",sizeof(i));
22. }
Answer:
sizeof(i)=1
Explanation:
Since the #define replaces the string int by the macro char
23. main()
24. {
25. int i=10;
26. i=!i>14;
27. printf("i=%d",i);
28. }
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).
29. #include‹stdio.h›
30. main()
31. {
32. char s[]={'a','b','c','\n','c','\0'};
33. char *p,*str,*str1;
34. p=&s[3];
35. str=p;
36. str1=s;
37. printf("%d",++*p + ++*str1-32);
38. }
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).
39. #include‹stdio.h›
40. main()
41. {
42. int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
43. int *p,*q;
44. p=&a[2][2][2];
45. *q=***a;
46. printf("%d----%d",*p,*q);
47. }
Answer:
SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.
17. #include‹stdio.h›
18. main()
19. {
20. struct xx
21. {
22. int x=3;
23. char name[]="hello";
24. };
25. struct xx *s;
26. printf("%d",s->x);
27. printf("%s",s->name);
28. }
Answer:
Compiler Error
Explanation:
You should not initialize variables in declaration
29. #include‹stdio.h›
30. main()
31. {
32. struct xx
33. {
34. int x;
35. struct yy
36. {
37. char s;
38. struct xx *p;
39. };
40. struct yy *q;
41. };
42. }
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.
43. main()
44. {
45. printf("\nab");
46. printf("\bsi");
47. printf("\rha");
48. }
Answer:
hai
Explanation:
\n - newline
\b - backspace
\r - linefeed
49. main()
50. {
51. int i=5;
52. printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
53. }
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.
54. #define square(x) x*x
55. main()
56. {
57. int i;
58. i = 64/square(4);
59. printf("%d",i);
60. }
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()
23. {
24. char *p="hai friends",*p1;
25. p1=p;
26. while(*p!='\0') ++*p++;
27. printf("%s %s",p,p1);
28. }
Answer:
ibj!gsjfoet
Explanation:
++*p++ will be parse in the given order
o *p that is value at the location currently pointed by p will be taken
o ++*p the retrieved value will be incremented
o 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.
29. #include‹stdio.h›
30. #define a 10
31. main()
32. {
33. #define a 50
34. printf("%d",a);
35. }
36.
37. Answer:
50

Explanation:
The preprocessor directives can be redefined anywhere in the program. So the most recently assigned value will be taken.


38. #define clrscr() 100
39. main()
40. {
41. clrscr();
42. printf("%d\n",clrscr());
43. }
44.
45. 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


46. main()
47. {
48. printf("%p",main);
49. }
50.
51. 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.

26. main()
27. {
28. clrscr();
29. }
30. 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).
31. enum colors {BLACK,BLUE,GREEN}
32. main()
33. {
34.
35. printf("%d..%d..%d",BLACK,BLUE,GREEN);
36.
37. return(1);
38. }
Answer:
0..1..2
Explanation: enum assigns numbers starting from 0, if not explicitly defined.
39. void main()
40. {
41. char far *farther,*farthest;
42.
43. printf("%d..%d",sizeof(farther),sizeof(farthest));
44.
45. }
Answer:
4..2
Explanation:
the second pointer is of char type and not a far pointer
46. main()
47. {
48. int i=400,j=300;
49. printf("%d..%d");
50. }
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.
51. main()
52. {
53. char *p;
54. p="Hello";
55. printf("%c\n",*&*p);
56. }
Answer:
H
Explanation:
* is a dereference operator & is a reference operator. They can be applied any number of times provided it is meaningful. Here p points to the first character in the string "Hello". *p dereferences it and so its value is H. Again & references it to an address and * dereferences it to the value H.
31. main()
32. {
33. int i=1;
34. while (i<=5)
35. {
36. printf("%d",i);
37. if (i>2)
38. goto here;
39. i++;
40. }
41. }
42. fun()
43. {
44. here:
45. printf("PP");
46. }
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.
47. main()
48. {
49. static char names[5][20]={"pascal","ada","cobol","fortran","perl"};
50. int i;
51. char *t;
52. t=names[3];
53. names[3]=names[4];
54. names[4]=t;
55. for (i=0;i<=4;i++)
56. printf("%s",names[i]);
57. }
Answer:
Compiler error: Lvalue required in function main
Explanation:
Array names are pointer constants. So it cannot be modified.
58. void main()
59. {
60. int i=5;
61. printf("%d",i++ + ++i);
62. }
Answer:
Output Cannot be predicted exactly.
Explanation:
Side effects are involved in the evaluation of i
63. void main()
64. {
65. int i=5;
66. printf("%d",i+++++i);
67. }
Answer:
Compiler Error
Explanation:
The expression i+++++i is parsed as i ++ ++ + i which is an illegal combination of operators.
68. #include‹stdio.h›
69. main()
70. {
71. int i=1,j=2;
72. switch(i)
73. {
74. case 1: printf("GOOD");
75. break;
76. case j: printf("BAD");
77. break;
78. }
79. }
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.
36. main()
37. {
38. int i;
39. printf("%d",scanf("%d",&i)); // value 10 is given as input here
40. }
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.
41. #define f(g,g2) g##g2
42. main()
43. {
44. int var12=100;
45. printf("%d",f(var,12));
46. }
Answer:
100
47. main()
48. {
49. int i=0;
50.
51. for(;i++;printf("%d",i)) ;
52. printf("%d",i);
53. }
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).
54. #include‹stdio.h›
55. main()
56. {
57. char s[]={'a','b','c','\n','c','\0'};
58. char *p,*str,*str1;
59. p=&s[3];
60. str=p;
61. str1=s;
62. printf("%d",++*p + ++*str1-32);
63. }
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");
64. #include‹stdio.h›
65. main()
66. {
67. struct xx
68. {
69. int x=3;
70. char name[]="hello";
71. };
72. struct xx *s=malloc(sizeof(struct xx));
73. printf("%d",s->x);
74. printf("%s",s->name);
75. }
Answer:
Compiler Error
Explanation:
Initialization should not be done for structure members inside the structure declaration
41. #include‹stdio.h›
42. main()
43. {
44. struct xx
45. {
46. int x;
47. struct yy
48. {
49. char s;
50. struct xx *p;
51. };
52. struct yy *q;
53. };
54. }
Answer:
Compiler Error
Explanation:
in the end of nested structure yy a member have to be declared.
55. main()
56. {
57. extern int i;
58. i=20;
59. printf("%d",sizeof(i));
60. }
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.
61. main()
62. {
63. printf("%d", out);
64. }
65. 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.
66. main()
67. {
68. extern out;
69. printf("%d", out);
70. }
71. int out=100;
Answer:
100
Explanation:
This is the correct way of writing the previous program.
72. main()
73. {
74. show();
75. }
76. void show()
77. {
78. printf("I'm the greatest");
79. }
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().
80. main( )
81. {
82. int a[2][3][2] = {{{2,4},{7,8},{3,4}},{{2,2},{2,3},{3,4}}};
83. printf("%u %u %u %d \n",a,*a,**a,***a);
84. printf("%u %u %u %d \n",a+1,*a+1,**a+1,***a+1);
85. }
Answer:
100, 100, 100, 2
114, 104, 102, 3
Explanation:
The given array is a 3-D one. It can also be viewed as a 1-D array.
2 4 7 8 3 4 2 2 2 3 3 4
100 102 104 106 108 110 112 114 116 118 120 122
thus, for the first printf statement a, *a, **a give address of first element . since the indirection ***a gives the value. Hence, the first line of the output.
for the second printf a+1 increases in the third dimension thus points to value at 114, *a+1 increments in second dimension thus points to 104, **a +1 increments the first dimension thus points to 102 and ***a+1 first gets the value at first location and then increments it by 1. Hence, the output.
86. main( )
87. {
88. int a[ ] = {10,20,30,40,50},j,*p;
89. for(j=0; j<5; j++)
90. {
91. printf("%d" ,*a);
92. a++;
93. }
94. p = a;
95. for(j=0; j<5; j++)
96. {
97. printf("%d " ,*p);
98. p++;
99. }
100. }
Answer:
Compiler error: lvalue required.
Explanation:
Error is in line with statement a++. The operand must be an lvalue and may be of any of scalar type for the any operator, array name only when subscripted is an lvalue. Simply array name is a non-modifiable lvalue.
101. main( )
102. {
103. static int a[ ] = {0,1,2,3,4};
104. int *p[ ] = {a,a+1,a+2,a+3,a+4};
105. int **ptr = p;
106. ptr++;
107. printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);
108. *ptr++;
109. printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);
110. *++ptr;
111. printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);
112. ++*ptr;
113. printf("\n %d %d %d", ptr-p, *ptr-a, **ptr);
114. }
Answer:
111
222
333
344
Explanation:
Let us consider the array and the two pointers with some address
a
0 1 2 3 4
100 102 104 106 108
p
100 102 104 106 108
1000 1002 1004 1006 1008
ptr
1000
2000
After execution of the instruction ptr++ value in ptr becomes 1002, if scaling factor for integer is 2 bytes. Now ptr - p is value in ptr - starting location of array p, (1002 - 1000) / (scaling factor) = 1, *ptr - a = value at address pointed by ptr - starting value of array a, 1002 has a value 102 so the value is (102 - 100)/(scaling factor) = 1, **ptr is the value stored in the location pointed by the pointer of ptr = value pointed by value pointed by 1002 = value pointed by 102 = 1. Hence the output of the firs printf is 1, 1, 1.
After execution of *ptr++ increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the second printf are ptr - p = 2, *ptr - a = 2, **ptr = 2.
After execution of *++ptr increments value of the value in ptr by scaling factor, so it becomes1004. Hence, the outputs for the third printf are ptr - p = 3, *ptr - a = 3, **ptr = 3.
After execution of ++*ptr value in ptr remains the same, the value pointed by the value is incremented by the scaling factor. So the value in array p at location 1006 changes from 106 10 108,. Hence, the outputs for the fourth printf are ptr - p = 1006 - 1000 = 3, *ptr - a = 108 - 100 = 4, **ptr = 4.
49. main( )
50. {
51. char *q;
52. int j;
53. for (j=0; j<3; j++) scanf("%s" ,(q+j));
54. for (j=0; j<3; j++) printf("%c" ,*(q+j));
55. for (j=0; j<3; j++) printf("%s" ,(q+j));
56. }
Explanation:
Here we have only one pointer to type char and since we take input in the same pointer thus we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE, TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as
M O U S E \0
When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101.
M T R A C K \0
The third input starts filling from the location 102
M T V I R T U A L \0
This is the final value stored .
The first printf prints the values at the position q, q+1 and q+2 = M T V
The second printf prints three strings starting from locations q, q+1, q+2
i.e MTVIRTUAL, TVIRTUAL and VIRTUAL.
57. main( )
58. {
59. void *vp;
60. char ch = 'g', *cp = "goofy";
61. int j = 20;
62. vp = &ch;
63. printf("%c", *(char *)vp);
64. vp = &j;
65. printf("%d",*(int *)vp);
66. vp = cp;
67. printf("%s",(char *)vp + 3);
68. }
Answer:
g20fy
Explanation:
Since a void pointer is used it can be type casted to any other type pointer. vp = &ch stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is 'g'. Similarly the output from second printf is '20'. The third printf statement type casts it to print the string from the 4th value hence the output is 'fy'.
69. main ( )
70. {
71. static char *s[ ] = {"black", "white", "yellow", "violet"};
72. char **ptr[ ] = {s+3, s+2, s+1, s}, ***p;
73. p = ptr;
74. **++p;
75. printf("%s",*--*++p + 3);
76. }
Answer:
ck
Explanation:
In this problem we have an array of char pointers pointing to start of 4 strings. Then we have ptr which is a pointer to a pointer of type char and a variable p which is a pointer to a pointer to a pointer of type char. p hold the initial value of ptr, i.e. p = s+3. The next statement increment value in p by 1 , thus now value of p = s+2. In the printf statement the expression is evaluated *++p causes gets value s+1 then the pre decrement is executed and we get s+1-1 = s . the indirection operator now gets the value from the array of s and adds 3 to the starting address. The string is printed starting from this position. Thus, the output is 'ck'.
77. main()
78. {
79. int i, n;
80. char *x = "girl";
81. n = strlen(x);
82. *x = x[n];
83. for(i=0; i‹n; ++i)
84. {
85. printf("%s\n",x);
86. x++;
87. }
88. }
89. Answer:
(blank space)
irl
rl
l
Explanation:
Here a string (a pointer to char) is initialized with a value "girl". The strlen function returns the length of the string, thus n has a value 4. The next statement assigns value at the nth location ('\0') to the first location. Now the string becomes "\0irl" . Now the printf statement prints the string after each iteration it increments it starting position. Loop starts from 0 to 4. The first time x[0] = '\0' hence it prints nothing and pointer value is incremented. The second time it prints from x[1] i.e "irl" and the third time it prints "rl" and the last time it prints "l" and the loop terminates.
53. int i,j;
54. for(i=0;i<=10;i++)
55. {
56. j+=5;
57. assert(i<5);
58. }
Answer:
Runtime error: Abnormal program termination.
assert failed (i<5), ‹file name›,‹line number›
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.
59. main()
60. {
61. int i=-1;
62. +i;
63. printf("i = %d, +i = %d \n",i,+i);
64. }
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).
65. What are the files which are automatically opened when a C file is executed?
Answer: stdin, stdout, stderr (standard input,standard output,standard error).
66. 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.
67. main()
68. {
69. char name[10],s[12];
70. scanf(" \"%[^\"]\"",s);
71. }

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.
72. 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.
73. main()
74. {
75. main();
76. }
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.
60. main()
61. {
62. char *cptr,c;
63. void *vptr,v;
64. c=10; v=0;
65. cptr=&c; vptr=&v;
66. printf("%c%v",c,v);
67. }
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.
68. main()
69. {
70. char *str1="abcd";
71. char str2[]="abcd";
72. printf("%d %d %d",sizeof(str1),sizeof(str2),sizeof("abcd"));
73. }
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.
74. main()
75. {
76. char not;
77. not=!2;
78. printf("%d",not);
79. }
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.
80. #define FALSE -1
81. #define TRUE 1
82. #define NULL 0
83. main() {
84. if(NULL)
85. puts("NULL");
86. else if(FALSE)
87. puts("TRUE");
88. else
89. puts("FALSE");
90. }
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.
91. main()
92. {
93. int k=1;
94. printf("%d==1 is ""%s",k,k==1?"TRUE":"FALSE");
95. }
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".
65. main()
66. {
67. int y;
68. scanf("%d",&y); // input given is 2000
69. if( (y%4==0 && y%100 != 0) || y%100 == 0 )
70. printf("%d is a leap year");
71. else
72. printf("%d is not a leap year");
73. }
Answer:
2000 is a leap year
Explanation:
An ordinary program to check if leap year or not.
74. #define max 5
75. #define int arr1[max]
76. main()
77. {
78. typedef char arr2[max];
79. arr1 list={0,1,2,3,4};
80. arr2 name="name";
81. printf("%d %s",list[0],name);
82. }
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.
83. int i=10;
84. main()
85. {
86. extern int i;
87. {
88. int i=20;
89. {
90. const volatile unsigned i=30;
91. printf("%d",i);
92. }
93. printf("%d",i);
94. }
95. printf("%d",i);
96. }
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.
97. main()
98. {
99. int *j;
100. {
101. int i=10;
102. j=&i;
103. }
104. printf("%d",*j);
105. }
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.
106. main()
107. {
108. int i=-1;
109. -i;
110. printf("i = %d, -i = %d \n",i,-i);
111. }
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.
70. #include‹stdio.h›
71. main()
72. {
73. const int i=4;
74. float j;
75. j = ++i;
76. printf("%d %f", i,++j);
77. }
Answer:
Compiler error
Explanation:
i is a constant. you cannot change the value of constant
78. #include‹stdio.h›
79. main()
80. {
81. int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
82. int *p,*q;
83. p=&a[2][2][2];
84. *q=***a;
85. printf("%d..%d",*p,*q);
86. }
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.
87. #include‹stdio.h›
88. main()
89. {
90. register i=5;
91. char j[]= "hello";
92. printf("%s %d",j,i);
93. }
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.
94. main()
95. {
96. int i=5,j=6,z;
97. printf("%d",i+++j);
98. }
Answer:
11
Explanation:
the expression i+++j is treated as (i++ + j)
99. struct aaa{
100. struct aaa *prev;
101. int i;
102. struct aaa *next;
103. };
104. main()
105. {
106. struct aaa abc,def,ghi,jkl;
107. int x=100;
108. abc.i=0;abc.prev=&jkl;
109. abc.next=&def;
110. def.i=1;def.prev=&abc;def.next=&ghi;
111. ghi.i=2;ghi.prev=&def;
112. ghi.next=&jkl;
113. jkl.i=3;jkl.prev=&ghi;jkl.next=&abc;
114. x=abc.next->next->prev->next->i;
115. printf("%d",x);
116. }
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.
75. struct point
76. {
77. int x;
78. int y;
79. };
80. struct point origin,*pp;
81. main()
82. {
83. pp=&origin;
84. printf("origin is(%d%d)\n",(*pp).x,(*pp).y);
85. printf("origin is (%d%d)\n",pp->x,pp->y);
86. }
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
87. main()
88. {
89. int i=_l_abc(10);
90. printf("%d\n",--i);
91. }
92. int _l_abc(int i)
93. {
94. return(i++);
95. }
Answer:
9
Explanation:
return(i++) it will first return i and then increments. i.e. 10 will be returned.
96. main()
97. {
98. char *p;
99. int *q;
100. long *r;
101. p=q=r=0;
102. p++;
103. q++;
104. r++;
105. printf("%p...%p...%p",p,q,r);
106. }
Answer:
0001...0002...0004
Explanation:
++ operator when applied to pointers increments address according to their corresponding data-types.
107. main()
108. {
109. char c=' ',x,convert(z);
110. getc(c);
111. if((c>='a') && (c<='z'))
112. x=convert(c);
113. printf("%c",x);
114. }
115. convert(z)
116. {
117. return z-32;
118. }
Answer:
Compiler error
Explanation:
declaration of convert and format of getc() are wrong.
119. main(int argc, char **argv)
120. {
121. printf("enter the character");
122. getchar();
123. sum(argv[1],argv[2]);
124. }
125. sum(num1,num2)
126. int num1,num2;
127. {
128. return num1+num2;
129. }
Answer:
Compiler error.
Explanation:
argv[1] & argv[2] are strings. They are passed to the function sum without converting it to integer values.
80. include ‹stdio.h›
81. int one_d[]={1,2,3};
82. main()
83. {
84. int *ptr;
85. ptr=one_d;
86. ptr+=3;
87. printf("%d",*ptr);
88. }
Answer:
garbage value
Explanation:
ptr pointer is pointing to out of the array range of one_d.
89. # include‹stdio.h›
90. aaa() {
91. printf("hi");
92. }
93. bbb(){
94. printf("hello");
95. }
96. ccc(){
97. printf("bye");
98. }
99. main()
100. {
101. int (*ptr[3])();
102. ptr[0]=aaa;
103. ptr[1]=bbb;
104. ptr[2]=ccc;
105. ptr[2]();
106. }
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.
107. #include‹stdio.h›
108. main()
109. {
110. FILE *ptr;
111. char i;
112. ptr=fopen("zzz.c","r");
113. while((i=fgetch(ptr))!=EOF)
114. printf("%c",i);
115. }
Answer:
contents of zzz.c followed by an infinite loop
Explanation:
The condition is checked against EOF, it should be checked against NULL.
116. main()
117. {
118. int i =0;j=0;
119. if(i && j++)
120. printf("%d..%d",i++,j);
121. printf("%d..%d,i,j);
122. }
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.
84. int i;
85. i = abc();
86. printf("%d",i);
87. }
88. abc()
89. {
90. _AX = 1000;
91. }
Answer:
1000
Explanation: < blockquote>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.
92. int i;
93. main(){
94. int t;
95. for ( t=4;scanf("%d",&i)-t;printf("%d\n",i))
96. printf("%d--",t--);
97. }
98. // 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
99. main(){
100. int a= 0;int b = 20;char x =1;char y =10;
101. if(a,b,x,y)
102. printf("hello");
103. }
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.
104. main(){
105. unsigned int i;
106. for(i=1;i>-2;i--)
107. printf("c aptitude");
108. }
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.
88. In the following pgm add a stmt in the function fun such that the address of 'a' gets stored in 'j'.
89. main(){
90. int * j;
91. void fun(int **);
92. fun(&j);
93. }
94. void fun(int **k) {
95. int a =0;
96. /* add a stmt here*/
}
Answer:
*k = &a
Explanation:
The argument of the function is a pointer to a pointer.
97. 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 (K&R Notation)
98. main()
99. {
100. char *p;
101. p="%d\n";
102. p++;
103. p++;
104. printf(p-2,300);
105. }
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.
106. main(){
107. char a[100];
108. a[0]='a';a[1]]='b';a[2]='c';a[4]='d';
109. abc(a);
110. }
111. abc(char a[]){
112. a++;
113. printf("%c",*a);
114. a++;
115. printf("%c",*a);
116. }
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.
92. func(a,b)
93. int a,b;
94. {
95. return( a= (a==b) );
96. }
97. main()
98. {
99. int process(),func();
100. printf("The value of process is %d !\n ",process(func,3,6));
101. }
102. process(pf,val1,val2)
103. int (*pf) ();
104. int val1,val2;
105. {
106. return((*pf) (val1,val2));
107. }
Answer:
The value if process is 0 !
Explanation:
The function 'process' has 3 parameters - 1, a pointer to another function 2 and 3, integers. When this function is invoked from main, the following substitutions for formal parameters take place: func for pf, 3 for val1 and 6 for val2. This function returns the result of the operation performed by the function 'func'. The function func has two integer parameters. The formal parameters are substituted as 3 for a and 6 for b. since 3 is not equal to 6, a==b returns 0. therefore the function returns 0 which in turn is returned by the function 'process'.
108. void main()
109. {
110. static int i=5;
111. if(--i){
112. main();
113. printf("%d ",i);
114. }
115. }
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.
116. void main()
117. {
118. int k=ret(sizeof(float));
119. printf("\n here value is %d",++k);
120. }
121. int ret(int ret)
122. {
123. ret += 2.5;
124. return(ret);
125. }
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.
126. void main()
127. {
128. char a[]="12345\0";
129. int i=strlen(a);
130. printf("here in 3 %d\n",++i);
131. }
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.
96. void main()
97. {
98. unsigned giveit=-1;
99. int gotit;
100. printf("%u ",++giveit);
101. printf("%u \n",gotit=--giveit);
102. }
Answer:
0 65535
103. void main()
104. {
105. int i;
106. char a[]="\0";
107. if(printf("%s\n",a))
108. printf("Ok here \n");
109. else
110. printf("Forget it\n");
111. }
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.
112. void main()
113. {
114. void *v;
115. int integer=2;
116. int *i=&integer;
117. v=i;
118. printf("%d",(int*)*v);
119. }
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.
120. void main()
121. {
122. int i=i++,j=j++,k=k++;
123. printf("%d%d%d",i,j,k);
124. }
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).
125. void main()
126. {
127. static int i=i++, j=j++, k=k++;
128. printf("i = %d j = %d k = %d", i, j, k);
129. }
Answer:
i = 1 j = 1 k = 1
Explanation:
Since static variables are initialized to zero by default.
101. void main()
102. {
103. while(1){
104. if(printf("%d",printf("%d")))
105. break;
106. else
107. continue;
108. }
109. }
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.
110. main()
111. {
112. unsigned int i=10;
113. while(i-->=0)
114. printf("%u ",i);
115.
116. }
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.
117. #include‹conio.h›
118. main()
119. {
120. int x,y=2,z,a;
121. if(x=y%2) z=2;
122. a=2;
123. printf("%d %d ",z,x);
124. }
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.
125. main()
126. {
127. int a[10];
128. printf("%d",*a+1-*a+3);
129. }
Answer:
4
Explanation:
*a and -*a cancels out. The result is as simple as 1 + 3 = 4 !
130. #define prod(a,b) a*b
131. main()
132. {
133. int x=3,y=4;
134. printf("%d",prod(x+2,y-1));
135. }
Answer:
10
Explanation:
106. The macro expands and evaluates to as:
x+2*y-1 => x+(2*y)-1 => 10 main()
107. {
108. unsigned int i=65000;
109. while(i++!=0);
110. printf("%d",i);
111. }
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.
112. main()
113. {
114. int i=0;
115. while(+(+i--)!=0)
116. i-=i++;
117. printf("%d",i);
118. }
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.
119. main()
120. {
121. float f=5,g=10;
122. enum{i=10,j=20,k=50};
123. printf("%d\n",++k);
124. printf("%f\n",f<<2);
125. printf("%lf\n",f%g);
126. printf("%lf\n",fmod(f,g));
127. }
Answer:
Line no 5: Error: Lvalue required
Line no 6: Cannot apply leftshift to float
Line no 7: Cannot apply mod to float
Explanation:
Enumeration constants cannot be modified, so you cannot apply ++.
Bit-wise operators and % operators cannot be applied on float values.
fmod() is to find the modulus values for floats as % operator is for ints.
128. main()
129. {
130. int i=10;
131. void pascal f(int,int,int);
132. f(i++,i++,i++);
133. printf(" %d",i);
134. }
135. void pascal f(integer :i,integer:j,integer :k)
136. {
137. write(i,j,k);
138. }
Answer:
Compiler error: unknown type integer Compiler error: undeclared function write
Explanation:
Pascal keyword doesn’t mean that pascal code can be used. It means that the function follows Pascal argument passing mechanism in calling the functions.
139. void pascal f(int i,int j,int k)
140. {
141. printf(“%d %d %d”,i, j, k);
142. }
143. void cdecl f(int i,int j,int k)
144. {
145. printf(“%d %d %d”,i, j, k);
146. }
147. main()
148. {
149. int i=10;
150. f(i++,i++,i++);
151. printf(" %d\n",i);
152. i=10;
153. f(i++,i++,i++);
154. printf(" %d",i);
155. }
Answer:
10 11 12 13
12 11 10 13
Explanation:
Pascal argument passing mechanism forces the arguments to be called from left to right. cdecl is the normal C argument passing mechanism where the arguments are passed from right to left.
111. What is the output of the program given below
112. main()
113. {
114. signed char i=0;
115. for(;i>=0;i++) ;
116. 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.
117. main()
118. {
119. unsigned char i=0;
120. for(;i>=0;i++) ;
121. printf("%d\n",i);
122. }
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.
123. main()
124. {
125. char i=0;
126. for(;i>=0;i++) ;
127. printf("%d\n",i);
128.
129. }
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.
130. 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.
131. What is the output for the program given below
132. typedef enum errorType{warning, error, exception,}error;
133. main()
134. {
135. error g1;
136. g1=1;
137. 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.
116. typedef struct error{int warning, error, exception;}error;
117. main()
118. {
119. error g1;
120. g1.error =1;
121. printf("%d",g1.error);
122. }
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!
123. #ifdef something
124. int some=0;
125. #endif
126.
127. main()
128. {
129. int thing = 0;
130. printf("%d %d\n", some ,thing);
131. }
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.
132. #if something == 0
133. int some=0;
134. #endif
135.
136. main()
137. {
138. int thing = 0;
139. printf("%d %d\n", some ,thing);
140. }
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.
141. void main()
142. {
143. if(~0 == (unsigned int)-1)
144. printf("You can answer this if you know how values are represented in memory");
145. }
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.
146. int swap(int *a,int *b)
147. {
148. *a=*a+*b;*b=*a-*b;*a=*a-*b;
149. }
150. main()
151. {
152. int x=10,y=20;
153. swap(&x,&y);
154. printf("x= %d y = %d\n",x,y);
155. }
Answer:
x = 20 y = 10
Explanation
This is one way of swapping two values. Simple checking will help understand this.

121. main()
122. {
123. char *p = "ayqm";
124. printf("%c",++*(p++));
125. }
Answer:
b
126. main()
127. {
128. int i=5;
129. printf("%d",++i++);
130. }
Answer:
Compiler error: Lvalue required in function main
Explanation:
++i yields an rvalue. For postfix ++ to operate an lvalue is required.
131. main()
132. {
133. char *p = "ayqm";
134. char c;
135. c = ++*p++;
136. printf("%c",c);
137. }
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.
138. int aaa() {printf("Hi");}
139. int bbb(){printf("hello");}
140. iny ccc(){printf("bye");}
141.
142. main()
143. {
144. int ( * ptr[3]) ();
145. ptr[0] = aaa;
146. ptr[1] = bbb;
147. ptr[2] =ccc;
148. ptr[2]();
149. }
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".
150. main()
151. {
152. int i=5;
153. printf("%d",i=++i ==6);
154. }
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.
126. main()
127. {
128. char p[ ]="%d\n";
129. p[1] = 'c';
130. printf(p,65);
131. }
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.
132. void ( * abc( int, void ( *def) () ) ) ();
Answer:
abc is a ptr to a function which takes 2 parameters (a) an integer variable (b)a ptrto a funtion which returns void. the return type of the function is void.
Explanation:
Apply the clock-wise rule to find the result.
133. main()
134. {
135. while (strcmp("some","some\0"))
136. printf("Strings are not equal\n");
137. }
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.
138. main()
139. {
140. char str1[] = {'s','o','m','e'};
141. char str2[] = {'s','o','m','e','\0'};
142. while (strcmp(str1,str2))
143. printf("Strings are not equal\n");
144. }
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.
145. main()
146. {
147. int i = 3;
148. for (;i++=0;) printf("%d",i);
149. }
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.
131. void main()
132. {
133. int *mptr, *cptr;
134. mptr = (int*)malloc(sizeof(int));
135. printf("%d",*mptr);
136. int *cptr = (int*)calloc(sizeof(int),1);
137. printf("%d",*cptr);
138. }
Answer:
garbage-value 0
Explanation:
The memory space allocated by malloc is uninitialized, whereas calloc returns the allocated memory space initialized to zeros.
139. void main()
140. {
141. static int i;
142. while(i<=10)
143. (i>2)?i++:i--;
144. printf("%d", i);
145. }
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.
146. main()
147. {
148. int i=10,j=20;
149. j = i, j?(i,j)?i:j:j;
150. printf("%d %d",i,j);
151. }
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;
152.
1. const char *a;
2. char* const a;
3. char const *a;

-Differentiate the above declarations.
Answer:
4. 'const' applies to char * rather than 'a' ( pointer to a constant char )
*a='F' : illegal
a="Hi" : legal
5. 'const' applies to 'a' rather than to the value of a (constant pointer to char )
*a='F' : legal
a="Hi" : illegal
6. Same as 1.
153. main()
154. {
155. int i=5,j=10;
156. i=i&=j&&10;
157. printf("%d %d",i,j);
158. }
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.
136. main()
137. {
138. int i=4,j=7;
139. j = j || i++ && printf("YOU CAN");
140. printf("%d %d", i, j);
141. }
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.
142. main()
143. {
144. register int a=2;
145. printf("Address of a = %d",&a);
146. printf("Value of a = %d",a);
147. }
Answer:
Compier Error: '&' on register variable
Rule to Remember:
& (address of ) operator cannot be applied on register variables.
148. main()
149. {
150. float i=1.5;
151. switch(i)
152. {
153. case 1: printf("1");
154. case 2: printf("2");
155. default : printf("0");
156. }
157. }
Answer: Compiler Error: switch expression not integral
Explanation: Switch statements can be applied only to integral types.
158. main()
159. {
160. extern i;
161. printf("%d\n",i);
162. {
163. int i=20;
164. printf("%d\n",i);
165. }
166. }
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.
167. main()
168. {
169. int a=2,*f1,*f2;
170. f1=f2=&a;
171. *f2+=*f2+=a+=2.5;
172. printf("\n%d %d %d",a,*f1,*f2);
173. }
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
141. main()
142. {
143. char *p="GOOD";
144. char a[ ]="GOOD";
145. printf("\n sizeof(p) = %d, sizeof(*p) = %d, strlen(p) = %d", sizeof(p), sizeof(*p), strlen(p));
146. printf("\n sizeof(a) = %d, strlen(a) = %d", sizeof(a), strlen(a));
147. }
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.
148. #define DIM( array, type) sizeof(array)/sizeof(type)
149. main()
150. {
151. int arr[10];
152. printf("The dimension of the array is %d", DIM(arr, int));
153. }
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.
154. int DIM(int array[])
155. {
156. return sizeof(array)/sizeof(int );
157. }
158. main()
159. {
160. int arr[10];
161. printf("The dimension of the array is %d", DIM(arr));
162. }
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.
163. main()
164. {
165. static int a[3][3]={1,2,3,4,5,6,7,8,9};
166. int i,j;
167. static *p[]={a,a+1,a+2};
168. for(i=0;i<3;i++)
169. {
170. for(j=0;j<3;j++)
171. printf("%d\t%d\t%d\t%d\n",*(*(p+i)+j),
172. *(*(j+p)+i),*(*(i+p)+j),*(*(p+j)+i));
173. }
174. }
Answer:
1 1 1 1
2 4 2 4
3 7 3 7
4 2 4 2
5 5 5 5
6 8 6 8
7 3 7 3
8 6 8 6
9 9 9 9
Explanation:
*(*(p+i)+j) is equivalent to p[i][j].
175. main()
176. {
177. void swap();
178. int x=10,y=8;
179. swap(&x,&y);
180. printf("x=%d y=%d",x,y);
181. }
182. void swap(int *a, int *b)
183. {
184. *a ^= *b, *b ^= *a, *a ^= *b;
185. }
Answer:
x=10 y=8
Explanation:
Using ^ like this is a way to swap two variables without using a temporary variable and that too in a single statement.
Inside main(), void swap(); means that swap is a function that may take any number of arguments (not no arguments) and returns nothing. So this doesn't issue a compiler error by the call swap(&x,&y); that has two arguments.
This convention is historically due to pre-ANSI style (referred to as Kernighan and Ritchie style) style of function declaration. In that style, the swap function will be defined as follows, void swap()
int *a, int *b
{
*a ^= *b, *b ^= *a, *a ^= *b;
}
where the arguments follow the (). So naturally the declaration for swap will look like, void swap() which means the swap can take any number of arguments.
146. main()
147. {
148. int i = 257;
149. int *iPtr = &i;
150. printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
151. }
Answer:
1 1
Explanation:
The integer value 257 is stored in the memory as, 00000001 00000001, so the individual bytes are taken by casting it to char * and get printed.
152. main()
153. {
154. int i = 258;
155. int *iPtr = &i;
156. printf("%d %d", *((char*)iPtr), *((char*)iPtr+1) );
157. }
Answer:
2 1
Explanation:
The integer value 257 can be represented in binary as, 00000001 00000001. Remember that the INTEL machines are 'small-endian' machines. Small-endian means that the lower order bytes are stored in the higher memory addresses and the higher order bytes are stored in lower addresses. The integer value 258 is stored in memory as: 00000001 00000010.
158. main()
159. {
160. int i=300;
161. char *ptr = &i;
162. *++ptr=2;
163. printf("%d",i);
164. }
Answer:
556
Explanation:
The integer value 300 in binary notation is: 00000001 00101100. It is stored in memory (small-endian) as: 00101100 00000001. Result of the expression *++ptr = 2 makes the memory representation as: 00101100 00000010. So the integer corresponding to it is 00000010 00101100 => 556.
165. #include ‹stdio.h›
166. main()
167. {
168. char * str = "hello";
169. char * ptr = str;
170. char least = 127;
171. while (*ptr++)
172. least = (*ptr < least ) ?*ptr :least;
173. printf("%d",least);
174. }
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.
175. main()
176. {
177. struct student
178. {
179. char name[30];
180. struct date dob;
181. }stud;
182. struct date
183. {
184. int day,month,year;
185. };
186. scanf("%s%d%d%d", stud.rollno, &student.dob.day, &student.dob.month, &student.dob.year);
187. }
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.