Sie sind auf Seite 1von 92

DBMS It is a constant value that gives the name, structure of table

############################## and the constraints laid on it.

1. What is database?
9. What is System R? What are its two major subsystems?
A database is a logically coherent collection of data with System R was designed and developed over a period of
some inherent meaning, representing some aspect of real 1974-79 at IBM San Jose Research Center. It is a prototype
world and which is designed, built and populated with data and its purpose was to demonstrate that it is possible to build
for a specific purpose. a Relational System that can be used in a real life
environment to solve real life problems, with performance at
2. What is DBMS? least comparable to that of existing system.
It is a collection of programs that enables user to create and Its two subsystems are
maintain a database. In other words it is general-purpose Ø Research Storage
software that provides the users with the processes of Ø System Relational Data System.
defining, constructing and manipulating the database for
various applications. 10. How is the data structure of System R different from the
relational structure?
3. What is a Database system? Unlike Relational systems in System R
The database and DBMS software together is called as Ø Domains are not supported
Database system. Ø Enforcement of candidate key uniqueness is optional
Ø Enforcement of entity integrity is optional
4. Advantages of DBMS? Ø Referential integrity is not enforced
Ø Redundancy is controlled.
Ø Unauthorised access is restricted. 11. What is Data Independence?
Ø Providing multiple user interfaces. Data independence means that “the application is
Ø Enforcing integrity constraints. independent of the storage structure and access strategy of
Ø Providing backup and recovery. data”. In other words, The ability to modify the schema
definition in one level should not affect the schema
5. Disadvantage in File Processing System? definition in the next higher level.
Ø Data redundancy & inconsistency. Two types of Data Independence:
Ø Difficult in accessing data. Ø Physical Data Independence: Modification in physical
Ø Data isolation. level should not affect the logical level.
Ø Data integrity. Ø Logical Data Independence: Modification in logical level
Ø Concurrent access is not possible. should affect the view level.
Ø Security Problems. NOTE: Logical Data Independence is more difficult to
6. Describe the three levels of data abstraction? 12. What is a view? How it is related to data independence?
The are three levels of abstraction: A view may be thought of as a virtual table, that is, a table
Ø Physical level: The lowest level of abstraction describes that does not really exist in its own right but is instead
how data are stored. derived from one or more underlying base table. In other
Ø Logical level: The next higher level of abstraction, words, there is no stored file that direct represents the view
describes what data are stored in database and what instead a definition of view is stored in data dictionary.
relationship among those data. Growth and restructuring of base tables is not reflected in
Ø View level: The highest level of abstraction describes only views. Thus the view can insulate users from the effects of
part of entire database. restructuring and growth in the database. Hence accounts for
7. Define the "integrity rules" logical data independence.
There are two Integrity rules.
Ø Entity Integrity: States that “Primary key cannot have 13. What is Data Model?
NULL value” A collection of conceptual tools for describing data, data
Ø Referential Integrity: States that “Foreign Key can be relationships data semantics and constraints.
either a NULL value or should be Primary Key value of
other relation. 14. What is E-R model?
This data model is based on real world that consists of basic
8. What is extension and intension? objects called entities and of relationship among these
Extension - objects. Entities are described in a database by a set of
It is the number of tuples present in a table at any instance. attributes.
This is time dependent.
Intension - 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 26. What is VDL (View Definition Language)?
object. An object also contains bodies of code that operate It specifies user views and their mappings to the conceptual
on the object. These bodies of code are called methods. schema.
Objects that contain same types of values and the same
methods are grouped together into classes. Page 4

16. What is an Entity? 27. What is SDL (Storage Definition Language)?

It is a 'thing' in the real world with an independent existence. This language is to specify the internal schema. This
language may specify the mapping between two schemas.
17. What is an Entity type?
It is a collection (set) of entities that have same attributes. 28. What is Data Storage - Definition Language?
The storage structures and access methods used by database
18. What is an Entity set? system are specified by a set of definition in a special type of
It is a collection of all entities of particular entity type in the DDL called data storage-definition language.
29. What is DML (Data Manipulation Language)?
19. What is an Extension of entity type? This language that enable user to access or manipulate data
The collections of entities of a particular entity type are as organised by appropriate data model.
grouped together into an entity set. Ø Procedural DML or Low level: DML requires a user to
specify what data are needed and how to get those data.
Page 3 Ø Non-Procedural DML or High level: DML requires a user
to specify what data are needed without specifying how to
20. What is Weak Entity set? get those data.
An entity set may not have sufficient attributes to form a
primary key, and its primary key compromises of its partial 31. What is DML Compiler?
key and primary key of its parent entity, then it is said to be It translates DML statements in a query language into low-
Weak Entity set. level instruction that the query evaluation engine can
21. What is an attribute?
It is a particular property, which describes the entity. 32. What is Query evaluation engine?
It executes low-level instruction generated by compiler.
22. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up 33. What is DDL Interpreter?
of the relation name R and the list of attributes Ai that it It interprets DDL statements and record them in tables
contains. A relation is defined as a set of tuples. Let r be the containing metadata.
relation which contains set tuples (t1, t2, t3, ..., tn). Each
tuple is an ordered list of n-values t=(v1,v2, ..., vn). 34. What is Record-at-a-time?
The Low level or Procedural DML can specify and retrieve
23. What is degree of a Relation? each record from a set of records. This retrieve of a record is
It is the number of attribute of its relation schema. said to be Record-at-a-time.

24. What is Relationship? 35. What is Set-at-a-time or Set-oriented?

It is an association among two or more entities. The High level or Non-procedural DML can specify and
retrieve many records in a single DML statement. This
25. What is Relationship set? retrieve of a record is said to be Set-at-a-time or Set-
The collection (or set) of similar relationships. oriented.

26. What is Relationship type? 36. What is Relational Algebra?

Relationship type defines a set of associations or a It is procedural query language. It consists of a set of
relationship set among a given set of entity types. operations that take one or two relations as input and
produce a new relation.
27. What is degree of Relationship type?
It is the number of entity type participating. 37. What is Relational Calculus?
It is an applied predicate calculus specifically tailored for
25. What is DDL (Data Definition Language)? relational databases proposed by E.F. Codd. E.g. of
A data base schema is specifies by a set of definitions languages based on it are DSL ALPHA, QUEL.
expressed by a special language called DDL.
38. How does Tuple-oriented relational calculus differ from 46. What is 2NF?
domain-oriented relational calculus A relation schema R is in 2NF if it is in 1NF and every non-
The tuple-oriented calculus uses a tuple variables i.e., prime attribute A in R is fully functionally dependent on
variable whose only permitted values are tuples of that primary key.
relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., 47. What is 3NF?
variables that range over the underlying domains instead of A relation schema R is in 3NF if it is in 2NF and for every
over relation. E.g. ILL, DEDUCE. FD X A either of the following is true
Ø X is a Super-key of R.
39. What is normalization? Ø A is a prime attribute of R.
It is a process of analysing the given relation schemas based In other words, if every non prime attribute is non-
on their Functional Dependencies (FDs) and primary key to transitively dependent on primary key.
achieve the properties
Ø Minimizing redundancy 48. What is BCNF (Boyce-Codd Normal Form)?
Ø Minimizing insertion, deletion and update anomalies. 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
40. What is Functional Dependency? candidate key.
A Functional dependency is denoted by X Y between
two sets of attributes X and Y that are subsets of R specifies 49. What is 4NF?
a constraint on the possible tuple that can form a relation A relation schema R is said to be in 4NF if for every
state r of R. The constraint is for any two tuples t1 and t2 in r Multivalued dependency X Y that holds over R, one of
if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the following is true
value of X component of a tuple uniquely determines the Ø X is subset or equal to (or) XY = R.
value of component Y. Ø X is a super key.

41. When is a functional dependency F said to be minimal? 50. What is 5NF?

Ø Every dependency in F has a single attribute for its right A Relation schema R is said to be 5NF if for every join
hand side. dependency {R1, R2, ..., Rn} that holds R, one the following
Ø We cannot replace any dependency X A in F with a is true
dependency Y A where Y is a proper subset of X and still Ø Ri = R for some i.
have a set of dependency that is equivalent to F. Ø The join dependency is implied by the set of FD, over R in
Ø We cannot remove any dependency from F and still have which the left side is key of R.
set of dependency that is equivalent to F. 51. What is Domain-Key Normal Form?
A relation is said to be in DKNF if all constraints and
42. What is Multivalued dependency? dependencies that should hold on the the constraint can be
Multivalued dependency denoted by X Y specified on enforced by simply enforcing the domain constraint and key
relation schema R, where X and Y are both subsets of R, constraint on the relation.
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 52. What are partial, alternate,, artificial, compound and
and t4 should also exist in r with the following properties natural key?
Ø t3[x] = t4[X] = t1[X] = t2[X] Partial Key:
Ø t3[Y] = t1[Y] and t4[Y] = t2[Y] It is a set of attributes that can uniquely identify weak
Ø t3[Z] = t2[Z] and t4[Z] = t1[Z] entities and that are related to same owner entity. It is
where [Z = (R-(X U Y)) ] sometime called as Discriminator.
43. What is Lossless join property? Alternate Key:
It guarantees that the spurious tuple generation does not All Candidate Keys excluding the Primary Key are known as
occur with respect to relation schemas after decomposition. Alternate Keys.
Artificial Key:
44. What is 1 NF (Normal Form)? If no obvious key, either stand alone or compound is
The domain of attribute must include only atomic (simple, available, then the last resort is to simply create a key, by
indivisible) values. assigning a unique number to each record or occurrence.
Then this is known as developing an artificial key.
45. What is Fully Functional dependency? Compound Key:
It is based on concept of full functional dependency. A If no single data element uniquely identifies occurrences
functional dependency X Y is full functional dependency if within a construct, then combining multiple elements to
removal of any attribute A from X means that the create a unique identifier for the construct is known as
dependency does not hold any more. creating a compound key.
Natural Key:
When one of the data elements stored within a construct is In distributed deadlock detection, the delay in propagating
utilized as the primary key, then it is called the natural key. local information might cause the deadlock detection
algorithms to identify deadlocks that do not really exist.
53. What is indexing and what are the different kinds of Such situations are called phantom deadlocks and they lead
indexing? to unnecessary aborts.
Indexing is a technique for determining how quickly specific
data can be found. 60. What is a checkpoint and When does it occur?
Types: A Checkpoint is like a snapshot of the DBMS state. By
Ø Binary search style indexing taking checkpoints, the DBMS can reduce the amount of
Ø B-Tree indexing work to be done during restart in the event of subsequent
Ø Inverted list indexing crashes.
Ø Memory resident table 61. What are the different phases of transaction?
Ø Table indexing Different phases are
Ø Analysis phase
54. What is system catalog or catalog relation? How is better Ø Redo Phase
known as? Ø Undo phase
A RDBMS maintains a description of all the data that it
contains, information about every relation and index that it 62. What do you mean by flat file database?
contains. This information is stored in a collection of It is a database in which there are no programs or user access
relations maintained by the system called metadata. It is also languages. It has no cross-file capabilities but is user-
called data dictionary. friendly and provides user-interface management.
55. What is meant by query optimization?
The phase that identifies an efficient execution plan for 63. What is "transparent DBMS"?
evaluating a query that has the least estimated cost is It is one, which keeps its Physical Structure hidden from
referred to as query optimization. user.

56. What is join dependency and inclusion dependency? 64. Brief theory of Network, Hierarchical schemas and their
Join Dependency: properties
A Join dependency is generalization of Multivalued Network schema uses a graph data structure to organize
dependency.A JD {R1, R2, ..., Rn} is said to hold over a records example for such a database management system is
relation R if R1, R2, R3, ..., Rn is a lossless-join CTCG while a hierarchical schema uses a tree data structure
decomposition of R . There is no set of sound and complete example for such a system is IMS.
inference rules for JD.
Inclusion Dependency: 65. What is a query?
An Inclusion Dependency is a statement of the form that A query with respect to DBMS relates to user commands
some columns of a relation are contained in other columns. that are used to interact with a data base. The query language
A foreign key constraint is an example of inclusion can be classified into data definition language and data
dependency. manipulation language.

57. What is durability in DBMS? 66. What do you mean by Correlated subquery?
Once the DBMS informs the user that a transaction has Subqueries, or nested queries, are used to bring back a set of
successfully completed, its effects should persist even if the rows to be used by the parent query. Depending on how the
system crashes before all its changes are reflected on disk. subquery is written, it can be executed once for the parent
This property is called durability. query or it can be executed once for each row returned by
the parent query. If the subquery is executed for each row of
58. What do you mean by atomicity and aggregation? the parent, this is called a correlated subquery.
Atomicity: A correlated subquery can be easily identified if it contains
Either all actions are carried out or none are. Users should any references to the parent subquery columns in its
not have to worry about the effect of incomplete WHERE clause. Columns from the subquery cannot be
transactions. DBMS ensures this by undoing the actions of referenced anywhere else in the parent query. The following
incomplete transactions. example demonstrates a non-correlated subquery.
Aggregation: E.g. Select * From CUST Where '10/03/1990' IN (Select
A concept which is used to model a relationship between a ODATE From ORDER Where CUST.CNUM =
collection of entities and relationships. It is used when we ORDER.CNUM)
need to express a relationship among relationships.
67. What are the primitive operations common to all record
59. What is a Phantom Deadlock? management systems?
Addition, deletion and modification.
68. Name the buffer in which all the commands that are SQL is a nonprocedural language that is designed
typed in are stored specifically for data access operations on normalized
‘Edit’ Buffer relational database structures. The primary difference
between SQL and other conventional programming
69. What are the unary operations in Relational Algebra? languages is that SQL statements specify what data
PROJECTION and SELECTION. operations should be performed rather than how to perform
70. Are the resulting relations of PRODUCT and JOIN
operation the same? 78. Name the three major set of files on disk that compose a
No. database in Oracle
PRODUCT: Concatenation of every row in one relation with There are three major sets of files on disk that compose a
every row in another. database. All the files are binary. These are
JOIN: Concatenation of rows from one relation and related Ø Database files
rows from another. Ø Control files
Ø Redo logs
71. What is RDBMS KERNEL? The most important of these are the database files where the
Two important pieces of RDBMS architecture are the kernel, actual data resides. The control files and the redo logs
which is the software, and the data dictionary, which consists support the functioning of the architecture itself.
of the system-level data structures used by the kernel to All three sets of files must be present, open, and available to
manage the database Oracle for any data on the database to be useable. Without
You might think of an RDBMS as an operating system (or these files, you cannot access the database, and the database
set of subsystems), designed specifically for controlling data administrator might have to recover some or all of the
access; its primary functions are storing, retrieving, and database using a backup, if there is one.
securing data. An RDBMS maintains its own list of
authorized users and their associated privileges; manages 79. What is an Oracle Instance?
memory caches and paging; controls locking for concurrent The Oracle system processes, also known as Oracle
resource usage; dispatches and schedules user requests; and background processes, provide functions for the user
manages space usage within its table-space structures processes—functions that would otherwise be done by the
. user processes themselves
72. Name the sub-systems of a RDBMS Oracle database-wide system memory is known as the SGA,
I/O, Security, Language Processing, Process Control, the system global area or shared global area. The data and
Storage Management, Logging and Recovery, Distribution control structures in the SGA are shareable, and all the
Control, Transaction Control, Memory Management, Lock Oracle background processes and user processes can use
Management them.
The combination of the SGA and the Oracle background
73. Which part of the RDBMS takes care of the data processes is known as an Oracle instance
dictionary? How
Data dictionary is a set of tables and database objects that is 80. What are the four Oracle system processes that must
stored in a special area of the database and maintained always be up and running for the database to be useable
exclusively by the kernel. The four Oracle system processes that must always be up
and running for the database to be useable include DBWR
74. What is the job of the information stored in data- (Database Writer), LGWR (Log Writer), SMON (System
dictionary? Monitor), and PMON (Process Monitor).
The information in the data dictionary validates the existence 81. What are database files, control files and log files. How
of the objects, provides access to them, and maps the actual many of these files should a database have at least? Why?
physical storage location. Database Files
The database files hold the actual data and are typically the
75. Not only RDBMS takes care of locating data it also largest in size. Depending on their sizes, the tables (and
determines an optimal access path to store or retrieve the other objects) for all the user accounts can go in one
data database file—but that's not an ideal situation because it does
not make the database structure very flexible for controlling
76. How do you communicate with an RDBMS? access to storage for different users, putting the database on
You communicate with an RDBMS using Structured Query different disk drives, or backing up and restoring just part of
Language (SQL) the database.
You must have at least one database file but usually, more
77. Define SQL and state the differences between SQL and than one files are used. In terms of accessing and using the
other conventional programming Languages 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 Each Oracle block is numbered sequentially for each
than the size at which they were created database file starting at 1. Two blocks can have the same
Control Files block address if they are in different database files.
The control files and redo logs support the rest of the
architecture. Any database must have at least one control 84. What is database Trigger?
file, although you typically have more than one to guard A database trigger is a PL/SQL block that can defined to
against loss. The control file records the name of the automatically execute for insert, update, and delete
database, the date and time it was created, the location of the statements against a table. The trigger can e defined to
database and redo logs, and the synchronization information execute once for the entire statement or once for every row
to ensure that all three sets of files are always in step. Every that is inserted, updated, or deleted. For any one table, there
time you add a new database or redo log file to the database, are twelve events for which you can define database triggers.
the information is recorded in the control files. A database trigger can call database procedures that are also
Redo Logs written in PL/SQL.
Any database must have at least two redo logs. These are the
journals for the database; the redo logs record all changes to 85. Name two utilities that Oracle provides, which are use
the user objects or system objects. If any type of failure for backup and recovery.
occurs, the changes recorded in the redo logs can be used to Along with the RDBMS software, Oracle provides two
bring the database to a consistent state without losing any utilities that you can use to back up and restore the database.
committed transactions. In the case of non-data loss failure, These utilities are Export and Import.
Oracle can apply the information in the redo logs The Export utility dumps the definitions and data for the
automatically without intervention from the DBA. specified part of the database to an operating system binary
The redo log files are fixed in size and never grow file. The Import utility reads the file produced by an export,
dynamically from the size at which they were created. recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and
82. What is ROWID? recovering the database, all the changes made to the database
The ROWID is a unique database-wide physical address for cannot be recovered since the export was performed. The
every row on every table. Once assigned (when the row is best you can do is recover the database to the time when the
first inserted into the database), it never changes until the export was last performed.
row is deleted or the table is dropped.
The ROWID consists of the following three components, the 86. What are stored-procedures? And what are the
combination of which uniquely identifies the physical advantages of using them.
storage location of the row. Stored procedures are database objects that perform a user
Ø Oracle database file number, which contains the block defined operation. A stored procedure can have a set of
with the rows compound SQL statements. A stored procedure executes the
Ø Oracle block address, which contains the row SQL commands and returns the result to the client. Stored
Ø The row within the block (because each block can hold procedures are used to reduce network traffic.
many rows)
The ROWID is used internally in indexes as a quick means 87. How are exceptions handled in PL/SQL? Give some of
of retrieving rows with a particular key value. Application the internal exceptions' name
developers also use it in SQL statements as a quick way to PL/SQL exception handling is a mechanism for dealing with
access a row once they know the ROWID run-time errors encountered during procedure execution. Use
of this mechanism enables execution to continue if the error
83. What is Oracle Block? Can two Oracle Blocks have the is not severe enough to cause procedure termination.
same address? The exception handler must be defined within a subprogram
Oracle "formats" the database files into a number of Oracle specification. Errors cause the program to raise an exception
blocks when they are first created—making it easier for the with a transfer of control to the exception-handler block.
RDBMS software to manage the files and easier to read data After the exception handler executes, control returns to the
into the memory areas. block in which the handler was defined. If there are no more
The block size should be a multiple of the operating system executable statements in the block, control returns to the
block size. Regardless of the block size, the entire block is caller.
not available for holding data; Oracle takes up some space to User-Defined Exceptions
manage the contents of the block. This block header has a PL/SQL enables the user to define exception handlers in the
minimum size, but it can grow. declarations area of subprogram specifications. User
These Oracle blocks are the smallest unit of storage. accomplishes this by naming an exception as in the
Increasing the Oracle block size can improve performance, following example:
but it should be done only when the database is first created. ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code a) Are totally unnormalised
associated with this handler is written in the EXCEPTION b) Are always in 1NF
specification area as follows: c) Can be further denormalised
EXCEPTION d) May have multi-valued attributes
when OT_FAILURE then
out_status_code := g_out_status_code; (b) Are always in 1NF
out_msg := g_out_msg;
The following is an example of a subprogram exception: 90. Spurious tuples may occur due to
EXCEPTION i. Bad normalization
when NO_DATA_FOUND then ii. Theta joins
g_out_status_code := 'FAIL'; iii. Updating tables from join
RAISE ot_failure; a) i & ii b) ii & iii
Within this exception is the RAISE statement that transfers c) i & iii d) ii & iii
control back to the ot_failure exception handler. This
technique of raising the exception is used to invoke all user- (a) i & iii because theta joins are joins made on keys that are
defined exceptions. not primary keys.
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon 91. A B C is a set of attributes. The functional dependency is
error. NO_DATA_FOUND is a system-defined exception. as follows
Table below gives a complete list of internal exceptions. AB -> B
AC -> C
PL/SQL internal exceptions. C -> B
PL/SQL internal exceptions. a) is in 1NF
b) is in 2NF
Exception Name Oracle Error c) is in 3NF
INVALID_CURSOR ORA-01001 (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the
INVALID_NUMBER ORA-01722 primary key. Since C B is a FD given, where neither C is a
LOGIN_DENIED ORA-01017 Key nor B is a prime attribute, this it is not in 3NF. Further
NO_DATA_FOUND ORA-01403 B is not functionally dependent on key AC thus it is not in
NOT_LOGGED_ON ORA-01012 2NF. Thus the given FDs is in 1NF.
STORAGE_ERROR ORA-06500 92. In mapping of ERD to DFD
TIMEOUT_ON_RESOURCE ORA-00051 a) entities in ERD should correspond to an existing
TOO_MANY_ROWS ORA-01422 entity/store in DFD
TRANSACTION_BACKED_OUT ORA-00061 b) entity in DFD is converted to attributes of an entity in
ZERO_DIVIDE ORA-01476 c) relations in ERD has 1 to 1 correspondence to processes in
In addition to this list of exceptions, there is a catch-all d) relationships in ERD has 1 to 1 correspondence to flows
exception named OTHERS that traps all errors for which in DFD
specific error handling has not been established.
(a) entities in ERD should correspond to an existing
88. Does PL/SQL support "overloading"? Explain entity/store in DFD
The concept of overloading in PL/SQL relates to the idea
that you can define procedures and functions with the same 93. A dominant entity is the entity
name. PL/SQL does not look only at the referenced name, a) on the N side in a 1 : N relationship
however, to resolve a procedure or function call. The count b) on the 1 side in a 1 : N relationship
and data types of formal parameters are also considered. c) on either side in a 1 : 1 relationship
PL/SQL also attempts to resolve any procedure or function d) nothing to do with 1 : 1 or 1 : N relationship
calls in locally defined packages before looking at globally
defined packages or internal functions. To further ensure (b) on the 1 side in a 1 : N relationship
calling the proper procedure, you can use the dot notation. 94. Select 'NORTH', CUSTOMER From CUST_DTLS
Prefacing a procedure or function name with the package Where REGION = 'N' Order By
name fully qualifies any procedure or function reference. CUSTOMER Union Select 'EAST', CUSTOMER From
89. Tables derived from the ERD The above is
a) Not an error If a cold backup is performed, the only option available in
b) Error - the string in single quotes 'NORTH' and 'SOUTH' the event of data file loss is restoring all the files from the
c) Error - the string should be in double quotes latest backup. All work performed on the database since the
d) Error - ORDER BY clause last backup is lost.
Ø Hot Backup:
(d) Error - the ORDER BY clause. Since ORDER BY clause Some sites (such as worldwide airline reservations systems)
cannot be used in UNIONS cannot shut down the database while making a backup copy
of the files. The cold backup is not an available option.
95. What is Storage Manager? So different means of backing up database must be used —
It is a program module that provides the interface between the hot backup. Issue a SQL command to indicate to Oracle,
the low-level data stored in database, application programs on a tablespace-by-tablespace basis, that the files of the
and queries submitted to the system. tablespace are to backed up. The users can continue to make
full use of the files, including making changes to the data.
96. What is Buffer Manager? Once the user has indicated that he/she wants to back up the
It is a program module, which is responsible for fetching tablespace files, he/she can use the operating system to copy
data from disk storage into main memory and deciding what those files to the desired backup destination.
data to be cache in memory. The database must be running in ARCHIVELOG mode for
the hot backup option.
97. What is Transaction Manager? If a data loss failure does occur, the lost database files can be
It is a program module, which ensures that database, remains restored using the hot backup and the online and offline redo
in a consistent state despite system failures and concurrent logs created since the backup was done. The database is
transaction execution proceeds without conflicting. restored to the most consistent state without any loss of
committed transactions.
98. What is File Manager?
It is a program module, which manages the allocation of 103. What are Armstrong rules? How do we say that they are
space on disk storage and data structure used to represent complete and/or sound
information stored on a disk. The well-known inference rules for FDs
Ø Reflexive rule :
99. What is Authorization and Integrity manager? If Y is subset or equal to X then X Y.
It is the program module, which tests for the satisfaction of Ø Augmentation rule:
integrity constraint and checks the authority of user to access If X Y then XZ YZ.
data. Ø Transitive rule:
If {X Y, Y Z} then X Z.
Ø Decomposition rule :
100. What are stand-alone procedures?
Procedures that are not part of a package are known as stand- If X YZ then X Y.
alone because they independently defined. A good example Ø Union or Additive rule:
of a stand-alone procedure is one written in a SQL*Forms If {X Y, X Z} then X YZ.
application. These types of procedures are not available for Ø Pseudo Transitive rule :
reference from other Oracle tools. Another limitation of If {X Y, WY Z} then WX Z.
stand-alone procedures is that they are compiled at run time, Of these the first three are known as Amstrong Rules. They
which slows execution. are sound because it is enough if a set of FDs satisfy these
three. They are called complete because using these three
101. What are cursors give different types of cursors. rules we can generate the rest all inference rules.
PL/SQL uses cursors for all database information accesses
statements. The language supports the use two types of 104. How can you find the minimal key of relational
cursors schema?
Ø Implicit Minimal key is one which can identify each tuple of the
Ø Explicit given relation schema uniquely. For finding the minimal key
it is required to find the closure that is the set of all attributes
102. What is cold backup and hot backup (in case of that are dependent on any given set of attributes under the
Oracle)? given set of functional dependency.
Ø Cold Backup: Algo. I Determining X+, closure for X, given set of FDs F
It is copying the three sets of files (database files, redo logs, 1. Set X+ = X
and control file) when the instance is shut down. This is a 2. Set Old X+ = X+
straight file copy, usually from the disk directly to tape. You 3. For each FD Y Z in F and if Y belongs to X+ then add Z
must shut down the instance to guarantee a consistent copy. to X+
4. Repeat steps 2 and 3 until Old X+ = X+
7. What are the wildcards used for pattern matching?
Algo.II Determining minimal K for relation schema R, given _ for single character substitution and % for multi-character
set of FDs F substitution
1. Set K to R that is make K a set of all attributes in R
2. For each attribute A in K 8. State true or false. EXISTS, SOME, ANY are operators in
a. Compute (K – A)+ with respect to F SQL.
b. If (K – A)+ = R then set K = (K – A)+ True

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

105. What do you understand by dependency preservation? operation.
Given a relation R and a set of FDs F, dependency True
preservation states that the closure of the union of the
projection of F on each decomposed relation Ri is equal to 10. What are the privileges that can be granted on a table by
the closure of F. i.e., a user to others?
((PR1(F)) U … U (PRn(F)))+ = F+ Insert, update, delete, select, references, index, execute, alter,
if decomposition is not dependency preserving, then some all
dependency is lost in the decomposition.
11. What command is used to get back the privileges offered
106. What is meant by Proactive, Retroactive and by the GRANT command?
Simultaneous Update. REVOKE
Proactive Update:
The updates that are applied to database before it becomes 12. Which system tables contain information on privileges
effective in real world . granted and privileges obtained?
The updates that are applied to database after it becomes
effective in real world . 13. Which system table contains information on constraints
Simulatneous Update: on all the tables created?
The updates that are applied to database at the same time USER_CONSTRAINTS
when it becomes effective in real world .
107. What are the different types of JOIN operations? DELETE FROM EMP;
Equi Join: This is the most common type of join which Will the outputs of the above two commands differ?
involves only equality comparisions. The disadvantage in Both will result in deleting all the rows in the table EMP.
this type of join is that there
15. What is the difference between TRUNCATE and
FAQ In SQL DELETE commands?
TRUNCATE is a DDL command whereas DELETE is a
DML command. Hence DELETE operation can be rolled
1. Which is the subset of SQL commands used to manipulate back, but TRUNCATE operation cannot be rolled back.
Oracle Database structures, including tables? WHERE clause can be used with DELETE and not with
Data Definition Language (DDL) TRUNCATE.

2. What operator performs pattern matching? 16. What command is used to create a table by copying the
LIKE operator structure of another table?
Answer :
3. What operator tests column for the absence of data? CREATE TABLE .. AS SELECT command
IS NULL operator Explanation :
To copy only the structure, the WHERE clause of the
4. Which command executes the contents of a specified file? SELECT command should contain a FALSE statement as in
START <filename> or @<filename> the following.
5. What is the parameter substitution symbol used with EXISTINGTABLE WHERE 1=2;
INSERT INTO command? 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?
6. Which command displays the SQL command in the SQL SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!!
buffer, and then executes it? ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM

18. What will be the output of the following query? 28. What is the output of the following query?
DECODE(TRANSLATE('A','1234567890','1111111111'), 1200
'1','YES', 'NO' );
Answer :
Explanation :
The query checks whether a given string is a numerical digit.
19. What does the following query do?
This displays the total salary of all employees. The null
values in the commission column will be replaced by 0 and Table 1 : STUDIES
added to salary.
20. Which date function is used to find the difference
between two dates? Table 2 : SOFTWARE
21. Why does the following command give a compilation (VARCHAR), SCOST (NUMBER), DCOST (NUMBER),
error? SOLD (NUMBER)
Variable names should start with an alphabet. Here the table Table 3 : PROGRAMMER
name starts with an '&' symbol.
22. What is the advantage of specifying WITH GRANT (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL
OPTION in the GRANT command? (NUMBER)
The privilege receiver can further grant the privileges he/she LEGEND :
has obtained from the owner to any other user.
PNAME – Programmer Name, SPLACE – Study Place,
23. What is the use of the DROP option in the ALTER CCOST – Course Cost, DEVIN – Developed in, SCOST –
TABLE command? Software Cost, DCOST – Development Cost, PROF1 –
It is used to drop constraints specified on the table. Proficiency 1

24. What is the value of ‘comm’ and ‘sal’ after executing the QUERIES :
following query if the initial value of ‘sal’ is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = 1. Find out the selling cost average for packages developed
SAL*0.1; in Oracle.
sal = 11000, comm = 1000 2. Display the names, ages and experience of all
25. What is the use of DESC in SQL? 3. Display the names of those who have done the PGDCA
Answer : course.
DESC has two purposes. It is used to describe a schema as 4. What is the highest number of copies sold by a package?
well as to retrieve rows from table in descending order. 5. Display the names and date of birth of all programmers
Explanation : born in April.
The query SELECT * FROM EMP ORDER BY ENAME 6. Display the lowest course fee.
DESC will display the output sorted on ENAME in 7. How many programmers have done the DCA course.
descending order. 8. How much revenue has been earned through the sale of
packages developed in C.
26. What is the use of CASCADE CONSTRAINTS? 9. Display the details of software developed by Rakesh.
When this clause is used with the DROP command, a parent 10. How many programmers studied at Pentafour.
table can be dropped even when a child table exists. 11. Display the details of packages whose sales crossed the
5000 mark.
27. Which function is used to find the largest integer less
than or equal to a specific value?
12. Find out the number of copies which should be sold in 8. SELECT SUM(SCOST*SOLD-DCOST) FROM
order to recover the development cost of each package. SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C';
13. Display the details of packages for which the
development cost has been recovered. 9. SELECT * FROM SOFTWARE WHERE PNAME =
14. What is the price of costliest software developed in VB? 'RAKESH';
15. How many packages were developed in Oracle ?
16. How many programmers studied at PRAGATHI? 10. SELECT * FROM STUDIES WHERE SPLACE =
17. How many programmers paid 10000 to 15000 for the 'PENTAFOUR';
18. What is the average course fee? 11. SELECT * FROM SOFTWARE WHERE
19. Display the details of programmers knowing C. SCOST*SOLD-DCOST > 5000;
20. How many programmers know either C or Pascal?
21. How many programmers don’t know C and C++? 12. SELECT CEIL(DCOST/SCOST) FROM SOFTWARE;
22. How old is the oldest male programmer?
23. What is the average age of female programmers? 13. SELECT * FROM SOFTWARE WHERE
24. Calculate the experience in years for each programmer SCOST*SOLD >= DCOST;
and display along with their names in descending order.
25. Who are the programmers who celebrate their birthdays 14. SELECT MAX(SCOST) FROM SOFTWARE GROUP
during the current month? BY DEVIN HAVING DEVIN = 'VB';
26. How many female programmers are there?
27. What are the languages known by the male 15. SELECT COUNT(*) FROM SOFTWARE WHERE
programmers? DEVIN = 'ORACLE';
28. What is the average salary?
29. How many people draw 5000 to 7500? 16. SELECT COUNT(*) FROM STUDIES WHERE
30. Display the details of those who don’t know C, C++ or SPLACE = 'PRAGATHI';
31. Display the costliest package developed by each 17. SELECT COUNT(*) FROM STUDIES WHERE
programmer. CCOST BETWEEN 10000 AND 15000;
32. Produce the following output for all the male
Mr. Arvind – has 15 years of experience 19. SELECT * FROM PROGRAMMER WHERE PROF1 =
'C' OR PROF2 = 'C';
2. SELECT NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++');
/12) "AGE", 22. SELECT



SEX = 'F';
27. SELECT DISTINCT(PROF1) FROM PROGRAMMER 10. Which department has the highest annual remuneration
WHERE SEX = 'M'; bill?
11. Write a query to display a ‘*’ against the row of the most
28. SELECT AVG(SAL) FROM PROGRAMMER; recently hired employee.
12. Write a correlated sub-query to list out the employees
29. SELECT COUNT(*) FROM PROGRAMMER WHERE who earn more than the average salary of their department.
SAL BETWEEN 5000 AND 7500; 13. Find the nth maximum salary.
14. Select the duplicate records (Records, which are inserted,
30. SELECT * FROM PROGRAMMER WHERE PROF1 that already exist) in the EMP table.
NOT IN ('C','C++','PASCAL') AND PROF2 NOT 15. Write a query to list the length of service of the
IN ('C','C++','PASCAL'); employees (of the form n years and m months).


years of experience' “Programmer” FROM PROGRAMMER
(SYSDATE,DOJ)/12) || ' years of experience' “Programmer” COUNT(EMPNO)>10 AND DEPTNO=10);



MGR is the empno of the employee whom the employee JOB;
reports to. DEPTNO is a foreign key.
1. List all the employees who have at least one person HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE)
reporting to them. FROM EMP GROUP BY DEPTNO);
2. List the employee details if and only if more than 10
employees are present in department no 10. 9. SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR",
3. List the name of the employees with their immediate COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP
4. List all the employees who do not manage any one. COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO))
5. List the employee details whose salary is greater than the FROM EMP GROUP BY
lowest salary of an employee belonging to deptno 20. TO_CHAR(HIREDATE,'YYYY'));
6. List the details of the employee earning more than the
highest paid manager. 10. SELECT DEPTNO,
7. List the highest salary paid for each job. LPAD(SUM(12*(SAL+NVL(COMM,0))),15)
8. Find the most recently hired employee in each department. "COMPENSATION" FROM EMP GROUP BY DEPTNO
9. In which year did most people join the company? Display HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT
the year and the number of employees.
MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP device by repeated requests to that track. This generally
GROUP BY DEPTNO); happens with most common device scheduling algorithms
(LIFO, SSTF, C-SCAN, etc). High-density multisurface
11. SELECT ENAME, HIREDATE, LPAD('*', disks are more likely to be affected by this than low density
SELECT ENAME NAME, HIREDATE, LPAD(' ',15) 4. What are the stipulations of C2 level security?
"RECENTLY HIRED" FROM EMP WHERE HIREDATE ! C2 level security provides for:
= (SELECT MAX(HIREDATE) FROM EMP); > Discretionary Access Control
> Identification and Authentication
5. What is busy waiting?
13. SELECT ENAME, SAL FROM EMP A WHERE &N = The repeated execution of a loop of code while waiting for
(SELECT COUNT (DISTINCT(SAL)) FROM EMP B an event to occur is called busy-waiting. The CPU is not
WHERE A.SAL<=B.SAL); engaged in any real productive activity during this period,
and the process does not progress toward completion.
(SELECT EMPNO FROM EMP GROUP BY EMPNO 6. What are short-, long- and medium-term scheduling?
HAVING COUNT(EMPNO)>1) AND A.ROWID!=MIN Long term scheduler determines which programs are
(ROWID)); admitted to the system for processing. It controls the degree
of multiprogramming. Once admitted, a job becomes a
15. SELECT ENAME process.
"EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEE Medium term scheduling is part of the swapping function.
N(SYSDATE,HIREDATE)/12))||' YEARS '|| This relates to processes that are in a blocked or suspended
TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN state. They are swapped out of real-memory until they are
(SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH ready to execute. The swapping-in decision is based on
OF SERVICE" FROM EMP; memory-management criteria.
Short term scheduler, also know as a dispatcher executes
most frequently, and makes the finest-grained decision of
which process should execute next. This scheduler is
invoked whenever an event occurs. It may lead to
OPERATING SYSTEM interruption of one process by preemption.
6. What are short-, long- and medium-term scheduling?
FAQ In Operating System Long term scheduler determines which programs are
admitted to the system for processing. It controls the degree
Following are a few basic questions that cover the essentials of multiprogramming. Once admitted, a job becomes a
of OS: process.
Medium term scheduling is part of the swapping function.
1. When is a system in safe state? This relates to processes that are in a blocked or suspended
The set of dispatchable processes is in a safe state if there state. They are swapped out of real-memory until they are
exists at least one temporal order in which all processes can ready to execute. The swapping-in decision is based on
be run to completion without resulting in a deadlock. memory-management criteria.
Short term scheduler, also know as a dispatcher executes
2. What is cycle stealing? most frequently, and makes the finest-grained decision of
We encounter cycle stealing in the context of Direct Memory which process should execute next. This scheduler is
Access (DMA). Either the DMA controller can use the data invoked whenever an event occurs. It may lead to
bus when the CPU does not need it, or it may force the CPU interruption of one process by preemption.
to temporarily suspend operation. The latter technique is
called cycle stealing. Note that cycle stealing can be done 7. What are turnaround time and response time?
only at specific break points in an instruction cycle. Turnaround time is the interval between the submission of a
job and its completion. Response time is the interval
3. What is meant by arm-stickiness? between submission of a request, and the first response to
If one or a few processes have a high access rate to data on that request.
one track of a storage disk, then they may monopolize the
8. What are the typical elements of a process image?
> User data: Modifiable part of user space. May include
program data, user stack area, and programs that may be 14. What is thrashing?
modified. It is a phenomenon in virtual memory schemes when the
> User program: The instructions to be executed. processor spends most of its time swapping pages, rather
> System Stack: Each process has one or more LIFO stacks than executing instructions. This is due to an inordinate
associated with it. Used to store parameters and calling number of page faults.
addresses for procedure and system calls.
> Process control Block (PCB): Info needed by the OS to 15. List the Coffman's conditions that lead to a deadlock.
control processes. > Mutual Exclusion: Only one process may use a critical
resource at a time.
9. What is the Translation Lookaside Buffer (TLB)? > Hold & Wait: A process may be allocated some resources
In a cached system, the base addresses of the last few while waiting for others.
referenced pages is maintained in registers called the TLB > No Pre-emption: No resource can be forcible removed
that aids in faster lookup. TLB contains those page-table from a process holding it.
entries that have been most recently used. Normally, each > Circular Wait: A closed chain of processes exist such that
virtual memory reference causes 2 physical memory each process holds at least one resource needed by another
accesses-- one to fetch appropriate page-table entry, and one process in the chain.
to fetch the desired data. Using TLB in-between, this is 16. Explain the popular multiprocessor thread-scheduling
reduced to just one physical memory access in cases of TLB- strategies.
hit. > Load Sharing: Processes are not assigned to a particular
processor. A global queue of threads is maintained. Each
10. What is the resident set and working set of a process? processor, when idle, selects a thread from this queue. Note
Resident set is that portion of the process image that is that load balancing refers to a scheme where work is
actually in real-memory at a particular instant. Working set allocated to processors on a more permanent basis.
is that subset of resident set that is actually needed for > Gang Scheduling: A set of related threads is scheduled to
execution. (Relate this to the variable-window size method run on a set of processors at the same time, on a 1-to-1 basis.
for swapping techniques.) Closely related threads / processes may be scheduled this
11. Explain the concept of Reentrancy. way to reduce synchronization blocking, and minimize
It is a useful, memory-saving technique for process switching. Group scheduling predated this strategy.
multiprogrammed timesharing systems. A Reentrant > Dedicated processor assignment: Provides implicit
Procedure is one in which multiple users can share a single scheduling defined by assignment of threads to processors.
copy of a program during the same period. Reentrancy has 2 For the duration of program execution, each program is
key aspects: The program code cannot modify itself, and the allocated a set of processors equal in number to the number
local data for each user process must be stored separately. of threads in the program. Processors are chosen from the
Thus, the permanent part is the code, and the temporary part available pool.
is the pointer back to the calling program and local variables > Dynamic scheduling: The number of thread in a program
used by that program. Each execution instance is called can be altered during the course of execution.
activation. It executes the code in the permanent part, but has
its own copy of local variables/parameters. The temporary 17. When does the condition 'rendezvous' arise?
part associated with each activation is the activation record. In message passing, it is the condition in which, both, the
Generally, the activation record is kept on the stack. sender and receiver are blocked until the message is
Note: A reentrant procedure can be interrupted and called by delivered.
an interrupting program, and still execute correctly on
returning to the procedure. 18. What is a trap and trapdoor?
Trapdoor is a secret undocumented entry point into a
12. Explain Belady's Anomaly. program used to grant access without normal methods of
Also called FIFO anomaly. Usually, on increasing the access authentication. A trap is a software interrupt, usually
number of frames allocated to a process' virtual memory, the the result of an error condition.
process execution is faster, because fewer page faults occur.
Sometimes, the reverse happens, i.e., the execution time 19. What are local and global page replacements?
increases even when more frames are allocated to the Local replacement means that an incoming page is brought
process. This is Belady's Anomaly. This is true for certain in only to the relevant process' address space. Global
page reference patterns. replacement policy allows any page frame from any process
to be replaced. The latter is applicable to variable partitions
13. What is a binary semaphore? What is its use? model only.
A binary semaphore is one, which takes only 0 and 1 as
values. They are used to implement mutual exclusion and 20. Define latency, transfer and seek time with respect to
synchronize concurrent processes. disk I/O.
Seek time is the time required to move the disk arm to the With run-time dynamic loading: Some of the linking is
required track. Rotational delay or latency is the time it takes postponed until actual reference during execution. Then the
for the beginning of the required sector to reach the head. correct module is loaded and linked.
Sum of seek time (if any) and latency is the access time. 25. In loading programs into memory, what is the difference
Time taken to actually transfer a span of data is transfer between load-time dynamic linking and run-time dynamic
time. linking?
21. Describe the Buddy system of memory allocation. For load-time dynamic linking: Load module to be loaded is
Free memory is maintained in linked lists, each of equal read into memory. Any reference to a target external module
sized blocks. Any such block is of size 2^k. When some causes that module to be loaded and the references are
memory is required by a process, the block size of next updated to a relative address from the start base address of
higher order is chosen, and broken into two. Note that the the application module.
two such pieces differ in address only in their kth bit. Such With run-time dynamic loading: Some of the linking is
pieces are called buddies. When any used block is freed, the postponed until actual reference during execution. Then the
OS checks to see if its buddy is also free. If so, it is rejoined, correct module is loaded and linked.
and put into the original free-block linked-list.
26. What are demand- and pre-paging?
22. What is time-stamping? With demand paging, a page is brought into memory only
It is a technique proposed by Lamport, used to order events when a location on that page is actually referenced during
in a distributed system without the use of clocks. This execution. With pre-paging, pages other than the one
scheme is intended to order events consisting of the demanded by a page fault are brought in. The selection of
transmission of messages. Each system 'i' in the network such pages is done based on common access patterns,
maintains a counter Ci. Every time a system transmits a especially for secondary memory devices.
message, it increments its counter by 1 and attaches the time-
stamp Ti to the message. When a message is received, the 27. Paging a memory management function, while
receiving system 'j' sets its counter Cj to 1 more than the multiprogramming a processor management function, are the
maximum of its current value and the incoming time-stamp two interdependent?
Ti. At each site, the ordering of messages is determined by Yes.
the following rules: For messages x from site i and y from
site j, x precedes y if one of the following conditions holds.... 28. What is page cannibalizing?
(a) if Ti<Tj or (b) if Ti=Tj and i<j. Page swapping or page replacements are called page
23. How are the wait/signal operations for monitor different
from those for semaphores? 29. What has triggered the need for multitasking in PCs?
If a process in a monitor signal and no task is waiting on the > Increased speed and memory capacity of microprocessors
condition variable, the signal is lost. So this allows easier together with the support fir virtual memory and
program design. Whereas in semaphores, every operation > Growth of client server computing
affects the value of the semaphore, so the wait and signal
operations should be perfectly balanced in the program. 30. What are the four layers that Windows NT have in order
to achieve independence?
24. In the context of memory management, what are > Hardware abstraction layer
placement and replacement algorithms? > Kernel
Placement algorithms determine where in available real- > Subsystems
memory to load a program. Common methods are first-fit, > System Services.
next-fit, best-fit. Replacement algorithms are used when
memory is full, and one process (or part of a process) needs 31. What is SMP?
to be swapped out to accommodate a new program. The To achieve maximum efficiency and reliability a mode of
replacement algorithm determines which are the partitions to operation known as symmetric multiprocessing is used. In
be swapped out. essence, with SMP any process or threads can be assigned to
any processor.
25. In loading programs into memory, what is the difference 32. What are the key object oriented concepts used by
between load-time dynamic linking and run-time dynamic Windows NT?
linking? > Encapsulation
For load-time dynamic linking: Load module to be loaded is > Object class and instance
read into memory. Any reference to a target external module
causes that module to be loaded and the references are 33. Is Windows NT a full blown object oriented operating
updated to a relative address from the start base address of system? Give reasons.
the application module. No Windows NT is not so, because its not implemented in
object oriented language and the data structures reside within
one executive component and are not represented as objects > Terminated.
and it does not support object oriented capabilities . 44. What are rings in Windows NT?
Windows NT uses protection mechanism called rings
34. What is a drawback of MVT? provides by the process to implement separation between the
It does not have the features like user mode and kernel mode.
> ability to support multiple processors
> virtual storage 45. What is Executive in Windows NT?
> source level debugging In Windows NT, executive refers to the operating system
code that runs in kernel mode.
35. What is process spawning?
When the OS at the explicit request of another process 46. What are the sub-components of I/O manager in
creates a process, this action is called process spawning. Windows NT?
> Network redirector/ Server
36. How many jobs can be run concurrently on MVT? > Cache manager.
15 jobs > File systems
> Network driver
37. List out some reasons for process termination. > Device driver

> Normal completion 47. What are DDks? Name an operating system that includes
> Time limit exceeded this feature.
> Memory unavailable DDks are device driver kits, which are equivalent to SDKs
> Bounds violation for writing device drivers. Windows NT includes DDks.
> Protection error
> Arithmetic error 48. What level of security does Windows NT meets?
> Time overrun C2 level security.
> I/O failure
> Invalid instruction
> Privileged instruction
> Data misuse
> Operator or OS intervention @------> C LANGUAGE
> Parent termination. @@@@@@@@@@@@@@@@@@@@@@@@@@
38. What are the reasons for process suspension? @@@@
> swapping C is interviewer’s favorite language. If you have good
> interactive user request command on C language you can get through Technical
> timing Interview easily. Most of the interviewers ask basic
> parent process request questions in C. Some times they may ask you to write small
programs like reversal of a string, determining whether the
39. What is process migration? given number is a palindrome or not and finding factorial of
It is the transfer of sufficient amount of the state of process a given number using recursion etc. You should be able to
from one machine to the target machine write these programs quickly.

40. What is mutant? Most favorite question for interviewers is interchanging two
In Windows NT a mutant provides kernel mode or user variables with out using the third variable. Another favorite
mode mutual exclusion with the notion of ownership. topic for interviewers is Pointers. Please go through pointers
once before going to the interview.
41. What is an idle thread?
The special thread a dispatcher will execute when no ready Many interviewers look for logic in your program rather
thread is found. than syntax. Once you write the program you should be able
to explain the logic to the interviewer with the help of flow-
42. What is FtDisk? chart or algorithm. If there are more than one logic for a
It is a fault tolerance disk driver for Windows NT. single program, choose the logic that is simple and easy to
understand at the same time it should efficient one.
43. What are the possible threads a thread can have?
> Ready Below are around 100 FAQ in C language. Try to answer
> Standby these questions on your own. I believe that if you are able to
> Running answer these questions, you can easily get through the
> Waiting technical interview.
> Transition
1.What will be the output of the following code? 5. How do I write code that reads data at memory location
specified by segment and offset?
void main ()
{ int i = 0 , a[3] ; Ans: Use peekb( ) function. This function returns byte(s)
a[i] = i++; read from specific segment and offset locations in memory.
printf (“%d",a[i]) ; The following program illustrates use of this function. In this
} program from VDU memory we have read characters and its
Ans: The output for the above code would be a garbage attributes of the first row. The information stored in file is
value. In the statement a[i] = i++; the value of the variable i then further read and displayed using peek( ) function.
would get assigned first to a[i] i.e. a[0] and then the value of
i would get incremented by 1. Since a[i] i.e. a[1] has not #include <stdio.h>
been initialized, a[i] will have a garbage value. #include <dos.h>
main( )
2. Why doesn't the following code give the desired result? {
char far *scr = 0xB8000000 ;
int x = 3000, y = 2000 ; FILE *fp ;
long int z = x * y ; int offset ;
Ans: Here the multiplication is carried out between two ints char ch ;
x and y, and the result that would overflow would be if ( ( fp = fopen ( "scr.dat", "wb" ) ) == NULL )
truncated before being assigned to the variable z of type long {
int. However, to get the correct output, we should use an printf ( "\nUnable to open file" ) ;
explicit cast to force long arithmetic as shown below: exit( ) ;
long int z = ( long int ) x * y ; // reads and writes to file
Note that ( long int )( x * y ) would not give the desired for ( offset = 0 ; offset < 160 ; offset++ )
effect. fprintf ( fp, "%c", peekb ( scr, offset ) ) ;
fclose ( fp ) ;

3.Why doesn't the following statement work? if ( ( fp = fopen ( "scr.dat", "rb" ) ) == NULL )
char str[ ] = "Hello" ; printf ( "\nUnable to open file" ) ;
strcat ( str, '!' ) ; exit( ) ;
Ans: The string function strcat( ) concatenates strings and }
not a character. The basic difference between a string and a // reads and writes to file
character is that a string is a collection of characters, for ( offset = 0 ; offset < 160 ; offset++ )
represented by an array of characters whereas a character is a {
single character. To make the above statement work writes
the statement as shown below: fscanf ( fp, "%c", &ch ) ;
strcat ( str, "!" ) ; printf ( "%c", ch ) ;
4. How do I know how many elements an array can hold? fclose ( fp ) ;
Ans: The amount of memory an array can consume depends
on the data type of an array. In DOS environment, the 6. How do I compare character data stored at two different
amount of memory an array can consume depends on the memory locations?
current memory model (i.e. Tiny, Small, Large, Huge, etc.).
In general an array cannot consume more than 64 kb. Ans: Sometimes in a program we require to compare
Consider following program, which shows the maximum memory ranges containing strings. In such a situation we can
number of elements an array of type int, float and char can use functions like memcmp( ) or memicmp( ). The basic
have in case of Small memory model. difference between two functions is that memcmp( ) does a
main( ) case-sensitive comparison whereas memicmp( ) ignores case
{ of characters. Following program illustrates the use of both
int i[32767] ; the functions.
float f[16383] ;
char s[65535] ; #include <mem.h>
} main( )
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ; is then restarted. The following program demonstrates use of
int c ; spawnl( ) function.
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
if ( c == 0 ) /* Mult.c */
printf ( "\nStrings arr1 and arr2 compared using memcmp
are identical" ) ; int main ( int argc, char* argv[ ] )
else {
printf ( "\nStrings arr1 and arr2 compared using memcmp int a[3], i, ret ;
are not identical" if ( argc < 3 || argc > 3 )
); {
printf ( "Too many or Too few arguments..." ) ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ; exit ( 0 ) ;
if ( c == 0 ) }
printf ( "\nStrings arr1 and arr2 compared using memicmp
are identical" ) for ( i = 1 ; i < argc ; i++ )
; a[i] = atoi ( argv[i] ) ;
else ret = a[1] * a[2] ;
printf ( "\nStrings arr1 and arr2 compared using memicmp return ret ;
are not }
identical" ) ;
} /* Spawn.c */
#include <process.h>
#include <stdio.h>
7. Fixed-size objects are more appropriate as compared to
variable size data objects. Using variable-size data objects main( )
saves very little space. Variable size data objects usually {
have some overhead. Manipulation of fixed-size data objects int val ;
is usually faster and easier. Use fixed size when maximum val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10",
size is clearly bounded and close to average. And use "20", NULL ) ;
variable-size data objects when a few of the data items are printf ( "\nReturned value is: %d", val ) ;
bigger than the average size. For example, }

char *num[10] = { "One", "Two", "Three", "Four", Here, there are two programs. The program 'Mult.exe' works
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ; as a child process whereas 'Spawn.exe' works as a parent
process. On execution of 'Spawn.exe' it invokes 'Mult.exe'
Instead of using the above, use and passes the command-line arguments to it. 'Mult.exe' in
turn on execution, calculates the product of 10 and 20 and
char num[10][6] = { "One", "Two", "Three", "Four", returns the value to val in 'Spawn.exe'. In our call to
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ; spawnl( ) function, we have passed 6 parameters, P_WAIT
as the mode of execution, path of '.exe' file to run as child
The first form uses variable-size data objects. It allocates 10 process, total number of arguments to be passed to the child
pointers, which are pointing to 10 string constants of process, list of command line arguments and NULL.
variable size. Assuming each pointer is of 4 bytes, it requires P_WAIT will cause our application to freeze execution until
90 bytes. On the other hand, the second form uses fixed size the child process has completed its execution. This
data objects. It allocates 10 arrays of 6 characters each. It parameter needs to be passed as the default parameter if you
requires only 60 bytes of space. So, the variable-size in this are working under DOS. under other operating systems that
case does not offer any advantage over fixed size. support multitasking, this parameter can be P_NOWAIT or
P_OVERLAY. P_NOWAIT will cause the parent process to
8. The Spawnl( ) function... execute along with the child process, P_OVERLAY will
load the child process on top of the parent process in the
DOS is a single tasking operating system, thus only one memory.
program runs at a time. The Spawnl( ) function provides us -------------------------------------------------------------------------
with the capability of starting the execution of one program ------------------------
from within another program. The first program is called the 9.
parent process and the second program that gets called from
within the first program is called a child process. Once the Are the following two statements identical?
second program starts execution, the first is put on hold until
the second program completes execution. The first program char str[6] = "Kicit" ;
char *str = "Kicit" ; How do I change the type of cursor and hide a cursor?
Ans: No! Arrays are not pointers. An array is a single, pre-
allocated chunk of contiguous elements (all of the same Ans: We can change the cursor type by using function
type), fixed in size and location. A pointer on the other hand, _setcursortype( ). This function can change the cursor type
is a reference to any data element (of a particular type) to solid cursor and can even hide a cursor. Following code
located anywhere. A pointer must be assigned to point to shows how to change the cursor type and hide cursor.
space allocated elsewhere, but it can be reassigned any time.
The array declaration char str[6] ; requests that space for 6 #include <conio.h>
characters be set aside, to be known main( )
by name str. In other words there is a location named str at {
which six characters are stored. The pointer declaration char /* Hide cursor */
*str ; on the other hand, requests a place that holds a pointer, _setcursortype ( _NOCURSOR ) ;
to be known by the name str. This pointer can point almost
anywhere to any char, to any contiguous array of chars, or /* Change cursor to a solid cursor */
nowhere. _setcursortype ( _SOLIDCURSOR ) ;
------------------------ /* Change back to the normal cursor */
10. _setcursortype ( _NORMALCURSOR ) ;
Is the following code fragment correct? -------------------------------------------------------------------------
const int x = 10 ; 13.
int arr[x] ;
Ans: No! Here, the variable x is first declared as an int so How do I write code that would get error number and display
memory is reserved for it. Then it is qualified by a const error message if any standard error occurs?
qualifier. Hence, const qualified object is not a constant
fully. It is an object with read only attribute, and in C, an Ans: Following code demonstrates this.
object associated with memory cannot be used in array
dimensions. #include <stdio.h>
#include <stdlib.h>
#include <errno.h>

11. main( )
How do I write code to retrieve current date and time from char *errmsg ;
the system and display it as a string? FILE *fp ;
fp = fopen ( "C:\file.txt", "r" ) ;
Ans: Use time( ) function to get current date and time and if ( fp == NULL )
then ctime( ) function to display it as a string. This is shown {
in following code snippet. errmsg = strerror ( errno ) ;
printf ( "\n%s", errmsg ) ;
#include <sys\types.h> }
void main( ) Here, we are trying to open 'file.txt' file. However, if the file
{ does not exist, then it would cause an error. As a result, a
time_t curtime ; value (in this case 2) related to the error generated would get
char ctm[50] ; set in errno. errno is an external int variable declared in
'stdlib.h' and also in 'errno.h'. Next, we have called sterror( )
time ( &curtime ) ; //retrieves current time & function which takes an error number and returns a pointer
stores in curtime to standard error message related to the given error number.
printf ( "\nCurrent Date & Time: %s", ctime ( -------------------------------------------------------------------------
&curtime ) ) ; ------------------------
} 14.

------------------------------------------------------------------------- How do I write code to get the current drive as well as set
------------------------ the current drive?
Ans: The function getdisk( ) returns the drive number of show ( result ) ;
current drive. The drive number 0 indicates 'A' as the current }
drive, 1 as 'B' and so on. The Setdisk( ) function sets the
current drive. This function takes one argument which is an show ( int r )
integer indicating the drive to be set. Following program {
demonstrates use of both the functions. if ( r == 0 )
printf ( "\nThe buffer str1 and str2 hold
#include <dir.h> identical data" ) ;
if ( r > 0 )
main( ) printf ( "\nThe buffer str1 is bigger than buffer
{ str2" ) ;
int dno, maxdr ; if ( r < 0 )
printf ( "\nThe buffer str1 is less than buffer
dno = getdisk( ) ; str2" ) ;
printf ( "\nThe current drive is: %c\n", 65 + dno }
); -------------------------------------------------------------------------
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ; 16.
printf ( "\nNow the current drive is: %c\n", 65 +
dno ) ; How do I write code to find an amount of free disk space
} available on current drive?
------------------------ Ans: Use getdfree( ) function as shown in follow code.
#include <stdio.h>
The functions memcmp( ) and memicmp( ) #include <stdlib.h>
#include <dir.h>
The functions memcmp( ) and memicmp( ) compares first n #include <dos.h>
bytes of given two blocks of memory or strings. However,
memcmp( ) performs comparison as unsigned chars whereas main( )
memicmp( ) performs comparison as chars but ignores case {
(i.e. upper or lower case). Both the functions return an int dr ; struct dfree disk ;
integer value where 0 indicates that two memory buffers long freesp ;
compared are identical. If the value returned is greater than 0
then it indicates that the first buffer is bigger than the second dr = getdisk( ) ;
one. The value less than 0 indicate that the first buffer is less getdfree ( dr + 1 , &disk ) ;
than the second buffer. The following code snippet
demonstrates use of both if ( disk.df_sclus == 0xFFFF )
#include <stdio.h> printf ( "\ngetdfree( ) function failed\n");
#include <mem.h> exit ( 1 ) ;
main( )
{ freesp = ( long ) disk.df_avail
char str1[] = "This string contains some * ( long ) disk.df_bsec
characters" ; * ( long ) disk.df_sclus ;
char str2[] = "this string contains" ; printf ( "\nThe current drive %c: has %ld bytes
int result ; available as free space\n", 'A' + dr, freesp ) ;
result = memcmp ( str1, str2, strlen ( str2 ) ) ;
printf ( "\nResult after comapring buffer using
memcmp( )" ) ; 17.
show ( result ) ;
Use of array indices...
result = memicmp ( str1, str2, strlen ( str2 ) ) ; If we wish to store a character in a char variable ch and the
printf ( "\nResult after comapring buffer using character to be stored depends on the value of another
memicmp( )" ) ;
variable say color (of type int), then the code would be as 19.
shown below:
How do I write a user-defined function, which deletes each
switch ( color ) character in a string str1, which matches any character in
{ string str2?
case 0 :
ch = 'R' ; Ans: The function is as shown below:
break ;
case 1 : Compress ( char str1[], char str2[] )
ch = 'G' ; {
break ; int i, j, k ;
case 2 :
ch = 'B' ; for ( i = k = 0 ; str1[i] != ‘\0’ ; i++ )
break ; {
} for ( j = 0 ; str2[j] != ‘\0’ && str2[j] !=
In place of switch-case we can make use of the value in str1[i] ; j++ )
color as an index for a character array. How to do this is ;
shown in following code snippet. if ( str2[j] == ‘\0’ )
str1[k++] = str1[I] ;
char *str = "RGB' ; }
char ch ; str1[k] = ‘\0’
int color ; }
// code -------------------------------------------------------------------------
ch = str[ color ] ; ------------------------
------------------------ 20.
How does free( ) know how many bytes to free?
Function atexit( ) recevies parameter as the address of
function of the type void fun ( void ). The function whose Ans: The malloc( ) / free( ) implementation remembers the
address is passed to atexit( ) gets called before the size of each block allocated and returned, so it is not
termination of program. If atexit( ) is called for more than necessary to remind it of the size when freeing.
one function then the functions are called in "first in last out" -------------------------------------------------------------------------
order. You can verify that from the output. ------------------------
#include <stdio.h>
#include <stdlib.h> What is the use of randomize( ) and srand( ) function?
void fun1( )
{ Ans: While generating random numbers in a program,
printf("Inside fun1\n"); sometimes we require to control the series of numbers that
} random number generator creates. The process of assigning
the random number generators starting number is called
void fun2( ) seeding the generator. The randomize( ) and srand( )
{ functions are used to seed the random number generators.
printf("Inside fun2\n"); The randomize( ) function uses PC's clock to produce a
} random seed, whereas the srand( ) function allows us to
main( ) specify the random number generator's starting value.
atexit ( fun1 ) ; -------------------------------------------------------------------------
/* some code */ ------------------------
atexit ( fun2 ) ; 22.
printf ( "This is the last statement of
program?\n" ); How do I determine amount of memory currently available
} for allocating?

------------------------------------------------------------------------- Ans: We can use function coreleft( ) to get the amount of

------------------------ memory available for allocation. However, this function
does not give an exact amount of unused memory. If, we are
using a small memory model, coreleft( ) returns the amount Sometimes while working with far pointers we need to break
of unused memory between the top of the heap and stack. If a far address into its segment and offset. In such situations
we are using a larger model, this function returns the amount we can use FP_SEG and FP_OFF macros. Following
of memory between the highest allocated memory and the program illustrates the use of these two macros.
end of conventional memory. The function returns amount of #include <dos.h>
memory in terms of bytes.
main( )
------------------------------------------------------------------------- {
------------------------ unsigned s, o ;
23. char far *ptr = "Hello!" ;

How does a C program come to know about command line s = FP_SEG ( ptr ) ;
arguments? o = FP_OFF ( ptr ) ;
printf ( "\n%u %u", s, o ) ;
Ans: When we execute our C program, operating system }
loads the program into memory. In case of DOS, it first loads
256 bytes into memory, called program segment prefix. This -------------------------------------------------------------------------
contains file table, environment segment, and command line ------------------------
information. When we compile the C program the compiler 27.
inserts additional code that parses the command, assigning it
to the argv array, making the arguments easily accessible How do I write a program to convert a string containing
within our C program. number in a hexadecimal form to its equivalent decimal?
24. Ans: The following program demonstrates this:
main( )
When we open a file, how does functions like fread( )/fwrite( {
), etc. get to know from where to read or to write the data? char str[] = "0AB" ;
int h, hex, i, n ;
Ans: When we open a file for read/write operation using n=0;h=1;
function like fopen( ), it returns a pointer to the structure of for ( i = 0 ; h == 1 ; i++ )
type FILE. This structure stores the file pointer called {
position pointer, which keeps track of current location within if ( str[i] >= '0' && str[i] <= '9' )
the file. On opening file for read/write operation, the file hex = str[i] - '0' ;
pointer is set to the start of the file. Each time we read/write else
a character, the position pointer advances one character. If {
we read one line of text at a step from the file, then file if ( str[i] >= 'a' && str[i] <= 'f' )
pointer advances to the start of the next line. If the file is hex = str[i] - 'a' + 10 ;
opened in append mode, the file pointer is placed at the very else
end of the file. Using fseek( ) function we can set the file if ( str[i] >= 'A' && str[i] <= 'F' )
pointer to some other place within the file. hex = str[i] - 'A' + 10 ;
------------------------------------------------------------------------- else
------------------------ h=0;
if ( h == 1 )
n = 16 * n + hex ;
25. }
printf ( "\nThe decimal equivalent of %s is %d",
The sizeof( ) function doesn’t return the size of the block of str, n ) ;
memory pointed to by a pointer. Why? }
The output of this program would be the decimal equivalent
Ans: The sizeof( ) operator does not know that malloc( ) has of 0AB is 171.
been used to allocate a pointer. sizeof( ) gives us the size of -------------------------------------------------------------------------
pointer itself. There is no handy way to find out the size of a ------------------------
block allocated by malloc( ). 28.
------------------------ How do I write code that reads the segment register settings?
FP_SEG And FP_OFF… Ans: We can use segread( ) function to read segment register
settings. There are four segment registers—code segment,
data segment, stack segment and extra segment. Sometimes time_t dtime ;
when we use DOS and BIOS services in a program we need
to know the segment register's value. In such a situation we char str[30] ;
can use segread( ) function. The following program
illustrates the use of this function. time ( &dtime ) ;
#include <dos.h> curtime = localtime ( &dtime ) ;
main( ) strftime ( str, 30, "%A %B %d, %Y", curtime ) ;
struct SREGS s ; printf ( "\n%s", str ) ;
segread ( &s ) ; }
printf ( "\nCS: %X DS: %X SS: %X ES: %X",s.cs, Here we have called time( ) function which returns current
s.ds,, ) ; time. This time is returned in terms of seconds, elapsed since
} 00:00:00 GMT, January 1, 1970. To extract the week day,
------------------------------------------------------------------------- day of month, etc. from this value we need to break down
------------------------ the value to a tm structure. This is done by the function
29. localtime( ). Then we have called strftime( ) function to
format the time and store it in a string str.
What is environment and how do I get environment for a
specific entry? 31.

Ans: While working in DOS, it stores information in a If we have declared an array as global in one file and we are
memory region called environment. In this region we can using it in another file then why doesn't the sizeof operator
place configuration settings such as command path, system works on an extern array?
prompt, etc. Sometimes in a program we need to access the
information contained in environment. The function Ans: An extern array is of incomplete type as it does not
getenv( ) can be used when we want to access environment contain the size. Hence we cannot use sizeof operator, as it
for a specific entry. Following program demonstrates the use cannot get the size of the array declared in another file. To
of this function. resolve this use any of one the following two solutions:
#include <stdio.h> 1. In the same file declare one more variable that holds the
#include <stdlib.h> size of array. For example,

main( ) array.c
char *path = NULL ; int arr[5] ;
int arrsz = sizeof ( arr ) ;
path = getenv ( "PATH" ) ;
if ( *path != NULL ) myprog.c
printf ( "\nPath: %s", path ) ;
else extern int arr[] ;
printf ( "\nPath is not set" ) ; extern int arrsz ;
} 2. Define a macro which can be used in an array
declaration. For example,
------------------------ myheader.h
#define SZ 5
How do I display current date in the format given below?
Saturday October 12, 2002
Ans: Following program illustrates how we can display date #include "myheader.h"
in above given format. int arr[SZ] ;

#include <stdio.h> myprog.c

#include <time.h>
#include "myheader.h"
main( ) extern int arr[SZ] ;
struct tm *curtime ;
------------------------ The access( ) function checks for the existence of a file and
also determines whether it can be read, written to or
32. executed. This function takes two arguments the filename
and an integer indicating the access mode. The values 6, 4, 2,
How do I write printf( ) so that the width of a field can be and 1 checks for read/write, read, write and execute
specified at runtime? permission of a given file, whereas value 0 checks whether
the file exists or not. Following program demonstrates how
Ans: This is shown in following code snippet. we can use access( ) function to check if a given file exists.

main( ) #include <io.h>

int w, no ; main( )
printf ( "Enter number and the width for the {
number field:" ) ; char fname[67] ;
scanf ( "%d%d", &no, &w ) ;
printf ( "%*d", w, no ) ; printf ( "\nEnter name of file to open" ) ;
} gets ( fname ) ;
Here, an '*' in the format specifier in printf( ) indicates that
an int value from the argument list should be used for the if ( access ( fname, 0 ) != 0 )
field width. {
------------------------------------------------------------------------- printf ( "\nFile does not exist." ) ;
------------------------ return ;
33. }
How to find the row and column dimension of a given 2-D
array? -------------------------------------------------------------------------
Ans: Whenever we initialize a 2-D array at the same place 35.
where it has been declared, it is not necessary to mention the
row dimension of an array. The row and column dimensions How do I convert a floating-point number to a string?
of such an array can be determined programmatically as
shown in following program. Ans: Use function gcvt( ) to convert a floating-point number
to a string. Following program demonstrates the use of this
void main( ) function.
{ #include <stdlib.h>
int a[][3] = { 0, 1, 2,
9,-6, 8, main( )
7, 5, 44, {
23, 11,15 } ; char str[25] ;
float no ;
int c = sizeof ( a[0] ) / sizeof ( int ) ; int dg = 5 ; /* significant digits */
int r = ( sizeof ( a ) / sizeof ( int ) ) / c ;
int i, j ; no = 14.3216 ;
gcvt ( no, dg, str ) ;
printf ( "\nRow: %d\nCol: %d\n", r, c ) ; printf ( "String: %s\n", str ) ;
for ( i = 0 ; i < r ; i++ ) }
for ( j = 0 ; j < c ; j++ ) 36.
printf ( "%d ", a[i][j] ) ; What is a stack ?
printf ( "\n" ) ;
} Ans: The stack is a region of memory within which our
} programs temporarily store data as they execute. For
------------------------------------------------------------------------- example, when a program passes parameters to functions, C
------------------------ places the parameters on the stack. When the function
34. completes, C removes the items from the stack. Similarly,
when a function declares local variables, C stores the
The access( ) function... variable's values on the stack during the function's execution.
Depending on the program's use of functions and parameters, Ans: The math function ldexp( ) is used while solving the
the amount of stack space that a program requires will differ. complex mathematical equations. This function takes two
------------------------------------------------------------------------- arguments, a double value and an int respectively. The order
------------------------ in which ldexp( ) function performs calculations is ( n * pow
37. ( 2, exp ) ) where n is the double value and exp is the integer.
Allocating memory for a 3-D array The following program demonstrates the use of this function.

#include "alloc.h" #include <stdio.h>

#define MAXX 3 #include <math.h>
#define MAXY 4
#define MAXZ 5 void main( )
main( ) {
{ double ans ;
int ***p, i, j, k ; double n = 4 ;
p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ;
for ( i = 0 ; i < MAXX ; i++ ) ans = ldexp ( n, 2 ) ;
{ printf ( "\nThe ldexp value is : %lf\n", ans ) ;
p[i] = ( int ** ) malloc ( MAXY * sizeof ( int * ) ) ; }
for ( j = 0 ; j < MAXY ; j++ ) Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ),
p[i][j] = ( int * ) malloc ( MAXZ * sizeof ( int ) ) ; and the output would be the ldexp value is : 16.000000
} -------------------------------------------------------------------------
for ( k = 0 ; k < MAXZ ; k++ ) ------------------------
for ( i = 0 ; i < MAXX ; i++ ) 39.
{ Can we get the mantissa and exponent form of a given
for ( j = 0 ; j < MAXY ; j++ ) number?
p[i][j][k] = i + j + k ; Ans: The function frexp( ) splits the given number into a
printf ( "%d ", p[i][j][k] ) ; mantissa and exponent form. The function takes two
} arguments, the number to be converted as a double value and
printf ( "\n" ) ; an int to store the exponent form. The function returns the
} mantissa part as a double value. Following example
printf ( "\n\n" ) ; demonstrates the use of this function.
} #include <math.h>
Data Structures #include <stdio.h>
How to distinguish between a binary tree and a tree?
void main( )
Ans: A node in a tree can have any number of branches. {
While a binary tree is a tree structure in which any node can double mantissa, number ;
have at most two branches. For binary trees we distinguish int exponent ;
between the subtree on the left and subtree on the right,
whereas for trees the order of the subtrees is irrelevant. number = 8.0 ;
Consider the following figure... mantissa = frexp ( number, &exponent ) ;

This above figure shows two binary trees, but these binary printf ( "The number %lf is ", number ) ;
trees are different. The first has an empty right subtree while printf ( "%lf times two to the ", mantissa ) ;
the second has an empty left subtree. If the above are printf ( "power of %d\n", exponent ) ;
regarded as trees (not the binary trees), then they are same
despite the fact that they are drawn differently. Also, an return 0 ;
empty binary tree can exist, but there is no tree having zero }
nodes. -------------------------------------------------------------------------
------------------------------------------------------------------------- ------------------------
------------------------ 40.
How do I use the function ldexp( ) in a program? How do I write code that executes certain function only at
program termination?
Ans: Use atexit( ) function as shown in following program.
operators like most operators, yields a value, and we cannot
#include <stdlib.h> assign the value of an _expression to a value. However, we
main( ) can use conditional operators as shown in following code
{ snippet.
int ch ;
void fun ( void ) ; main( )
atexit ( fun ) ; {
// code int i, j, k, l ;
} i = 5 ; j = 10 ; k = 12, l = 1 ;
void fun( void ) * ( ( i < 10 ) ? &j : &k ) = l * 2 + 14 ;
{ printf ( "i = %d j = %d k = %d l = %d", i, j, k, l ) ;
printf ( "\nTerminate program......" ) ; }
getch( ) ;
} The output of the above program would be as given below:
------------------------------------------------------------------------- i = 5 j = 16 k = 12 l = 1
------------------------ -------------------------------------------------------------------------
41. ------------------------
What are memory models? 44.
Ans: The compiler uses a memory model to determine how
much memory is allocated to the program. The PC divides How can I find the day of the week of a given date?
memory into blocks called segments of size 64 KB. Usually,
program uses one segment for code and a second segment Ans: The following code snippet shows how to get the day
for data. A memory model defines the number of segments of week from the given date.
the compiler can use for each. It is important to know which
memory model can be used for a program. If we use wrong dayofweek ( int yy, int mm, int dd )
memory model, the program might not have enough memory {
to execute. The problem can be solved using larger memory /*Monday = 1 and Sunday = 0 */
model. However, larger the memory model, slower is your /* month number >= 1 and <= 12, yy > 1752 or so */
program execution. So we must choose the smallest memory static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;
model that satisfies our program needs. Most of the yy = yy - mm < 3 ;
compilers support memory models like tiny, small, medium, return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] +
compact, large and huge. dd ) % 7 ;
How does C compiler store elements in a multi-dimensional void main( )
array? {
printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 )
Ans: The compiler maps multi-dimensional arrays in two );
ways—Row major order and Column order. When the }
compiler places elements in columns of an array first then it -------------------------------------------------------------------------
is called column-major order. When the compiler places ------------------------
elements in rows of an array first then it is called row-major
order. C compilers store multidimensional arrays in row-
major order. For example, if there is a multi-dimensional
array a[2][3], then according row-major order, the elements
would get stored in memory following order:
a[0][0], a[0][1], a[0][2], a[1][0], a[1][1], a[1][2] 45.
------------------------ What's the difference between these two declarations?
struct str1 { ... } ;
If the result of an _expression has to be stored to one of two typedef struct { ... } str2 ;
variables, depending on a condition, can we use conditional Ans : The first form declares a structure tag whereas the
operators as shown below? second declares a typedef. The main difference is that the
second declaration is of a slightly more abstract type -- its
( ( i < 10 ) ? j : k ) = l * 2 + p ; users don't necessarily know that it is a structure, and the
Ans: No! The above statement is invalid. We cannot use the keyword struct is not used when declaring instances of it.
conditional operators in this fashion. The conditional
------------------------------------------------------------------------- Ans: For the above given program, we expect the output as
------------------------ Good Evening and Good Afternoon, for the second and third
46. printf( ). However, the output would be as shown below.

How do I print the contents of environment variables? First string = Good MorningGood EveningGood Afternoon
Second string = ( null )
Ans:. The following program shows how to achieve this: Third string =
main( int argc, char *argv[ ], char *env[ ] )
{ What is missing in the above given code snippet is a comma
int i = 0 ; separator which should separate the strings Good Morning,
clrscr( ) ; Good Evening and Good Afternoon. On adding comma, we
while ( env[ i ] ) would get the output as shown below.
printf ( "\n%s", env[ i++ ] ) ;
} First string = Good Morning
Second string = Good Evening
main( ) has the third command line argument env, which is Third string = Good Afternoon
an array of pointers to the strings. Each pointer points to an -------------------------------------------------------------------------
environment variable from the list of environment variables. ------------------------
------------------------------------------------------------------------- 49.
47. How do I use scanf( ) to read the date in the form 'dd-mm-
div( )... yy' ?
Ans: There are two ways to read the date in the form of 'dd-
The function div( ) divides two integers and returns the mm-yy' one possible way is...
quotient and remainder. This function takes two integer
values as arguments; divides first integer with the second int dd, mm, yy ;
one and returns the answer of division of type div_t. The char ch ; /* for char '-' */
data type div_t is a structure that contains two long ints, printf ( "\nEnter the date in the form of dd-mm-yy : " ) ;
namely quot and rem, which store quotient and remainder of scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ;
division respectively. The following example shows the use
of div( ) function. And another best way is to use suppression character * as...

#include <stdlib.h> int dd, mm, yy ;

void main( ) scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ;
div_t res ; The suppression character * suppresses the input read from
the standard input buffer for the assigned control character.
res = div ( 32, 5 ) ; -------------------------------------------------------------------------
printf ( "\nThe quotient = %d and remainder = %d ", ------------------------
res.quot, res.rem ) ; 50.
48. How do I print a floating-point number with higher precision
What would the second and the third printf( ) output the say 23.34568734 with only precision up to two decimal
following program? places?

main( ) Ans: This can be achieved through the use of suppression

{ char '*' in the format string of printf( ) as shown in the
char *str[ ] = { following program.
"Good Morning" main( )
"Good Evening" {
"Good Afternoon" int i = 2 ;
}; float f = 23.34568734 ;
printf ( "\nFirst string = %s", str[0] ) ; printf ( "%.*f", i, f ) ;
printf ( "\nSecond string = %s", str[1] ) ; }
printf ( "\nThird string = %s", str[2] ) ; The output of the above program would be 23.35.
51. -------------------------------------------------------------------------
Are the expressions *ptr++ and ++*ptr same? ------------------------
Ans: No. *ptr++ increments the pointer and not the value ceil( ) and floor( )
pointed by it, whereas ++*ptr increments the value being
pointed to by ptr. The math function ceil( ) takes a double value as an
------------------------------------------------------------------------- argument. This function finds the smallest possible integer to
------------------------ which the given number can be rounded up. Similarly, floor(
) being a math function, takes a double value as an argument
52. and returns the largest possible integer to which the given
strpbrk( ) double value can be rounded down. The following program
demonstrates the use of both the functions.
The function strpbrk( ) takes two strings as parameters. It
scans the first string, to find, the first occurrence of any #include <math.h>
character appearing in the second string. The function void main( )
returns a pointer to the first occurrence of the character it {
found in the first string. The following program double no = 1437.23167 ;
demonstrates the use of string function strpbrk( ). double down, up ;

#include <string.h> down = floor ( no ) ;

main( ) up = ceil ( no ) ;
char *str1 = "Hello!" ; printf ( "The original number %7.5lf\n", no ) ;
char *str2 = "Better" ; printf ( "The number rounded down %7.5lf\n", down ) ;
char *p ; printf ( "The number rounded up %7.5lf\n", up ) ;
p = strpbrk ( str1, str2 ) ; }

if ( p ) The output of this program would be,

printf ( "The first character found in str1 is %c", *p ) ; The original number 1437.23167
else The number rounded down 1437.00000
printf ( "The character not found" ) ; The number rounded up 1438.00000
} -------------------------------------------------------------------------
The output of the above program would be the first character ------------------------
found in str1 is e 55.

How do I use function ecvt( ) in a program?

Ans: The function ecvt( ) converts a floating-point value to a
Can we convert an unsigned long integer value to a string? null terminated string. This function takes four arguments,
such as, the value to be converted to string, the number of
Ans: The function ultoa( ) can be used to convert an digits to be converted to string, and two integer pointers. The
unsigned long integer value to a string. This function takes two-integer pointer stores the position of the decimal point
three arguments, first the value that is to be converted, (relative to the string) and the sign of the number,
second the base address of the buffer in which the converted respectively. If the value in a variable, used to store sign is 0,
number has to be stored (with a string terminating null then the number is positive and, if it is non-zero, then the
character '\0') and the last argument specifies the base to be number is negative. The function returns a pointer to the
used in converting the value. Following example string containing digits. Following program demonstrates the
demonstrates the use of this function. use of this function.

#include <stdlib.h> #include <stdlib.h>

void main( ) main( )
{ {
unsigned long ul = 3234567231L ; char *str ;
char str[25] ; double val ;
int dec, sign ;
ultoa ( ul, str, 10 ) ; int ndig = 4 ;
printf ( "str = %s unsigned long = %lu\n", str, ul ) ;
} val = 22 ;
str = ecvt ( val, ndig, &dec, &sign ) ; can access the other member of the structure using the
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; address of age?
val = -345.67 ; struct emp
ndig = 8 ; {
str = ecvt ( val, ndig, &dec, &sign ) ; char name[20] ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; int age ;
float salary ;
// number with a scientific notation };
val = 3.546712e5 ; main( )
ndig = 5 ; {
str = ecvt ( val, ndig, &dec, &sign ) ; struct emp e ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; printf ( "\nEnter name: " ) ;
} scanf ( "%s", ) ;
printf ( "\nEnter age: " ) ;
The output of this program would be scanf ( "%d", &e.age ) ;
printf ( "\nEnter salary: " ) ;
string = 2200 dec = 2 sign = 0 scanf ( "%f", &e.salary ) ;
string = 34567000 dec = 3 sign = 1 fun ( &e.age ) ;
string = 35467 dec = 6 sign = 0 }
fun ( int *p )
------------------------------------------------------------------------- {
------------------------ struct emp *q ;
int offset ;
56. offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char
How to run DIR command programmatically? struct emp* ) 0 ) ;
q = ( struct emp * ) ( ( char * ) p - offset ) ;
Ans: We can use the system( ) function to execute the DIR printf ( "\nname: %s", q -> name ) ;
command along with its options. Following program shows printf ( "\nage: %d", q -> age ) ;
how this can be achieved: printf ( "\nsalary: %f", q -> salary ) ;
// mydir.c
main ( int argc, char *argv[ ] )
{ How to restrict the program's output to a specific screen
char str[30] ; region?

if ( argc < 2 ) Ans: A C function window( ) can be used to restrict the

exit ( 0 ) ; screen output to a specific region. The window( ) function
defines a text-mode window. The parameters passed to this
sprintf ( str, "dir %s %s", argv[1], argv[2] ) ; function defines the upper-left and lower-right corner of the
system ( str ) ; region within which you want the output. In the following
} program, the string 'Hello!' gets printed within the specified
region. To print the string we must use cprintf( ) function
If we run the executable file of this program at command which prints directly on the text-mode window.
prompt passing the command line arguments as follows:
#include <conio.h>
> mydir abc.c /s main( )
This will search the file 'abc.c' in the current directory. int i, j ;
------------------------ window ( 20, 8, 60, 17 ) ;
57. for ( i = 0 ; i < 8 ; i++ )
for ( j = 0 ; j < 10 ; j++ )
Suppose I have a structure having fields name, age, salary cprintf ( "Hello!" ) ;
and have passed address of age to a function fun( ). How I }
------------------------------------------------------------------------- int i, j ;
59. for ( i =1, j = 1; j <= 100, i <= 5; i++, j++ )
Sometimes you need to prompt the user for a password. gotoxy ( 1, 1 ) ;
When the user types in the password, the characters the user printf ( "%d %d", i, j ) ;
enters should not appear on the screen. A standard library }
function getpass( ) can be used to perform such function. }
Maximum number of characters that can be entered as
password is 8. Output -> 5 5
Even if logic of both the programs is same the output of the
main( ) first program comes out to be 100, 100, but of the second
{ program it is 5, 5. The comma operator plays a vital role
char *pwd ; inside the for loop. It always considers the value of the latest
variable. So, at the time of testing the condition in for loop,
pwd = getpass ( "Enter Password" ) ; the value of j will be considered in the first program and
value of i in the second.
if ( strcmp ( pwd, "orgcity" ) ) -------------------------------------------------------------------------
printf ( "\nPassword %s is incorrect", pwd ) ; ------------------------
else 62.
printf ( "\nCorrect Password" ) ; Can we get the x and y coordinate of the current cursor
} position ?
------------------------ Ans : The function wherex( ) and wherey( ) returns the x-
60. coordinate and y-coordinate of the current cursor position
How to obtain the current drive through C ? respectively. Both the functions return an integer value. The
value returned by wherex( ) is the horizontal position of
Ans: We can use the function _getdrive( ) to obtain the cursor and the value returned by wherey( ) is the vertical
current drive. The _getdrive( ) function uses DOS function position of the cursor. Following program shows how to use
0X19 to get the current drive number the wherex( ) and wherey( ) functions.

#include <direct.h> #include <conio.h>

main( ) main( )
{ {
int disk ; printf ( "Just\n To\n Test\n Where\n the cursor\n goes" ) ;
disk = _getdrive( ) + 'A' - 1 ;
printf ( "The current drive is: %c\n", disk ) ; printf ( "Current location is X: %d Y: %d\n", wherex( ),
} wherey( ) ) ;
------------------------------------------------------------------------- }
61. 63.
How do I programmatically delete lines in the text window?
How come the output for both the programs is different
when the logic is same? Ans: While writing programs that perform screen-based I/O,
you may want to-delete the current line's contents, moving
main( ) one line up, all of the output that follows. In such cases a
{ function called delline( ) can be used. Following code
int i, j ; snippet illustrates the use of function delline( ).

for ( i = 1, j = 1 ; i <= 5, j <= 100 ; i++, j++ ) #include <conio.h>

{ main( )
gotoxy ( 1, 1, ) ; {
printf ( "%d %d", i, j ) ; int i ;
} clrscr( ) ;
for ( i = 0; i <= 23; i++ )
main( ) printf ( "Line %d\r\n", i ) ;
printf ( "Press a key to continue : " ) ;
getch( ) ; main ( )
gotoxy ( 2, 6 ) ; char *str1 = "hS eesll snsiasl not eh es as oher " ;
char *str2 ;
for ( i = 6; i <= 12; i++ ) clrscr( ) ;
delline( ) ; swab ( str1, str2, strlen ( str1 ) ) ;
printf ( "The target string is : %s\n", str2 ) ; // output -- She
getch( ) ; sells
} snails on the sea shore
------------------------------------------------------------------------- getch( ) ;
------------------------ }
How do I get the time elapsed between two function calls ? ------------------------
Ans: The function difftime( ) finds the difference between
two times. It calculates the elapsed time in seconds and Turbo C provides various command line compiler options
returns the difference between two times as a double value. which we can use through TCC. The compiler options
include : displaying specific warning messages, generating
#include <time.h> 8087 hardware instructions, using a filename for generating
#include <stdio.h> assembly code, etc. Instead of compiler options being
#include <dos.h> executed at command line we can use these compiler options
in our program. This can be achieved using #pragma options.
main( ) We can use various flags with #pragma options to use the
{ compiler options. All these flags are available in turbo C's
int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ; online help.
int s ; -------------------------------------------------------------------------
time_t t1, t2 ; // time_t defines the value used for time ------------------------
function 67.

s = sizeof ( a ) / 2 ; I have an array declared in file 'F1.C' as,

t1 = time ( NULL ) ; int a[ ] = { 1, 2, 3, 4, 5, 6 } ;
sel_sort ( a, s ) ; // sort array by selection sort and used in the file 'F2.C' as,
bub_sort ( a, s ) ; // sort array by bubble sort method extern int a[ ] ;
t2 = time ( NULL ) ;
printf ( "\nThe difference between two function calls is %f", In the file F2.C, why sizeof doesn't work on the array a[ ]?
difftime (
t2, t1 ) ) ; Ans: An extern array of unspecified size is an incomplete
} type. You cannot apply sizeof to it, because sizeof operates
during compile time and it is unable to learn the size of an
In the above program we have called difftime( ) function that array that is defined in another file. You have three ways to
returns the time elapsed from t1 to t2. resolve this problem:
------------------------------------------------------------------------- 1. In file 'F1.C' define as,
------------------------ int a[ ] = { 1, 2, 3, 4, 5, 6 } ;
65. int size_a = sizeof ( a ) ;
and in file F2.C declare as,
How do I use swab( ) in my program ? extern int a[ ] ;
extern int size_a ;
Ans: The function swab( ) swaps the adjacent bytes of
memory. It copies the bytes from source string to the target 2. In file 'F1.H' define,
string, provided that the number of characters in the source
string is even. While copying, it swaps the bytes which are #define ARR_SIZ 6
then assigned to the target string. In file F1.C declare as,
#include "F1.H"
#include <stdlib.h> int a[ ARR_SIZ ] ;
#include <stdio.h> and in file F2.C declare as,
#include <string.h> #include "F1.H"
extern int a[ ARR_SIZ ] ; printf ( "The little snail was slowly moving up. She
3. In file 'F1.C' define as, wanted\r\n" ) ;
int a[ ] = { 1, 2, 3, 4, 5, 6, -1 } ; printf ( "to reach the top of the tree. It was chilly\r\n" ) ;
printf ( "winter season. Most of the animals were resting
and in file 'F2.C' declare as, in\r\n" ) ;
printf ( "their nests as there was a heavy snow fall.\r\n" ) ;
extern int a[ ] ; printf ( "\r\nPress any key to continue:" ) ;
Here the element -1 is used as a sentinel value, so the code
can gotoxy ( 10, 2 ) ;
understand the end without any explicit size. getch( ) ;
insline( ) ;
68. getch( ) ;
How to delete a line from text displayed on the screen? -------------------------------------------------------------------------
Ans: Sometimes, specially when we are creating a text editor
like program we may wish to allow user to delete a line. We 70.
can do so by using two functions namely clreol( ) and
delline( ). The clreol( ) function deletes the line from the What will be the output of the following program?
current cursor position to the end of line. The delline()
function deletes the entire line at the current cursor position main( )
and {
moves up the following line. Following program shows how unsigned int num ;
to use these functions. int i ;

#include <conio.h> printf ( "\nEnter any number" ) ;

scanf ( "%u", &num ) ;
main( )
{ for ( i = 0 ; i < 16 ; i++ )
int i ; printf ( "%d", ( num << i & 1 << 15 ) ? 1 : 0 ) ;
for ( i = 1 ; i <= 20 ; i++ )
printf ( "This is Line %d\n", i ) ; Ans: The output of this program is the binary equivalent of
the given number. We have used bitwise operators to get the
getch( ) ; binary number.
gotoxy ( 1, 7 ) ; -------------------------------------------------------------------------
clreol( ) ; ------------------------
getch( ) ; Graphics
gotoxy ( 1, 12 ) ;
delline( ) ; Building Mouse Cursors...

getch( ) ; In text mode the mouse cursor appears as a block, whereas in

} graphics mode it appears as an arrow. If we wish we can
------------------------------------------------------------------------- change the graphics cursor to any other shape the way
------------------------ Windows does. The mouse cursor in graphics mode occupies
69. a 16 by 16 pixel box. By highlighting or dehighlighting some
How do I programmatically insert lines in the text window? of the pixels in this box we can get the desired shape. For
example, the following bit-pattern can be used to generate
Ans: We can insert a blank line in the text window using the the cursor which looks like an hour-glass.
insline( ) function. This function inserts line at current cursor 1111111111111111 0000000000000000
position. While doing so, it shifts down the lines that are 1000000000000001 0000000000000000
below the newly inserted line. 1111111111111111 0000000000000000
1000000000000001 0000000000000000
#include <conio.h> 0100000000000010 1000000000000001
void main( ) 0010000000000100 1100000000000011
{ 0000100000010000 1111000000001111
0000001001000000 1111110000111111
0000001001000000 1111110000111111
0000100000010000 1111000000001111 initmouse( )
0010000000000100 1100000000000011 {
0100000000000010 1000000000000001 = 0 ; int86 ( 0x33, &i, &o ) ;
1000000000000001 0000000000000000 return ( == 0 ? -1 : 0 ) ;
1111111111111111 0000000000000000 }
1000000000000001 0000000000000000 showmouseptr( )
1111111111111111 0000000000000000 {
Mouse pointer bitmap Screen Mask the one's in the mouse = 1 ; int86 ( 0x33, &i, &o ) ;
pointer bitmap indicate that the pixel would be drawn }
whereas the zeros indicate that the pixel would stand erased. changecursor ( int *shape )
It is important to note that the mouse pointer bit pattern is 32 {
bytes long. However, while actually writing a program to = 9 ; /* service number */
change the pointer shape we need a 64 byte bit-map. This i.x.bx = 0 ; /* actual cursor position from left */
provision is made to ensure that when the cursor reaches a = 0 ; /* actual cursor position from top */
position on the screen where something is already written or i.x.dx = ( unsigned ) shape ; /* offset address of pointer
drawn only that portion should get overwritten which is to be image*/
occupied by the mouse cursor. Of the 64 bytes the first 32 segread ( &s ) ;
bytes contain a bit mask which is first ANDed with the = s.ds ; /* segment address of pointer */
screen image, and then the second 32 bytes bit mask is int86x ( 0x33, &i, &i, &s ) ;
XORed with the screen image. }

The following program changes the mouse cursor in 72.

graphics mode to resemble an hour glass.
Towers Of Hanoi
# include "graphics.h"
# include "dos.h" Suppose there are three pegs labeled A, B and C. Four disks
are placed on peg A. The bottom-most disk is largest, and
union REGS i, o ; disks go on decreasing in size with the topmost disk being
struct SREGS s ; smallest. The objective of the game is to move the disks
from peg A to peg C, using peg B as an auxiliary peg. The
int cursor[32] = rules of the game are as follows:
/* Hour-glass screen mask */ Only one disk may be moved at a time, and it must be the
0x0000, 0x0000, 0x0000, 0x0000, top disk on one of the pegs. A larger disk should never be
0x8001, 0xc003, 0xf00f, 0xfc3f, placed on the top of a smaller disk. Suppose we are to write
0xfc3f, 0xf00f, 0xc003, 0x8001, a program to print out the sequence in which the disks
0x0000, 0x0000, 0x0000, 0x0000, should be moved such that all disks on peg A are finally
/* The mouse pointer bitmap */ transferred to peg C. Here it is...
0xffff, 0x8001, 0xffff, 0x8001, main( )
0x4002, 0x2004, 0x1008, 0x0240, {
0x0240, 0x0810, 0x2004, 0x4002, int n = 4 ;
0x8001, 0xffff, 0x8001, 0xffff, move ( n, 'A', 'B', 'C' ) ;
}; }
main( )
{ move ( n, sp, ap, ep )
int gd = DETECT, gm ; int n ;
initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ; char sp, ap, ep ;
if ( initmouse( ) == -1 ) {
{ if ( n == 1 )
closegraph( ) ; printf ( "\n Move from %c to %c ", sp, ep ) ;
printf ( "\n Mouse not installed!" ) ; else
exit( ) ; {
} move ( n - 1, sp, ep, ap ) ;
gotoxy ( 10, 1 ) ; printf ( "Press any key to exit..." ) ; move ( 1, sp, ' ', ep ) ;
changecursor ( cursor ) ; showmouseptr( ) ; move ( n - 1, ap, sp, ep ) ;
getch( ) ; }
} }
And here is the output... 74.

Move from A to B How to get the memory size ?

Move from A to C
Move from B to C Ans: Consider the following program
Move from A to B
Move from C to A #include <stdio.h>
Move from C to B #include <bios.h>
Move from A to B main( )
Move from A to C {
Move from B to C int memsize;
Move from B to A memsize = biosmemory( ) ;
Move from C to A printf ( "RAM size = %dK\n",memsize ) ;
Move from B to C return 0 ;
Move from A to B }
Move from A to C
Move from B to C The function biosmemory uses BIOS interrupt 0x12 to return
the size of memory.
This problem is the famous Towers of Hanoi problem, -------------------------------------------------------------------------
wherein three pegs are to be employed for transferring the ------------------------
disks with the given criteria. Here's how we go about it. We 75.
have three pegs: the starting peg, sp, the auxiliary peg ap,
and the ending peg, ep, where the disks must finally be. Float Format
First, using the ending peg as an auxiliary or supporting peg, How does C compiler stores float values ?
we transfer all but the last disk to ap. Next the last disk is
moved from sp to ep. Now, using sp as the supporting peg, Ans: In C, the float values are stored in a mantissa and
all the disks are moved from ap to ep. ‘A’, B and C denote exponent form. While writing a number we specify the
the three pegs. The recursive function move( ) is called with exponent part in the form of base 10. But, in case of C
different combinations of these pegs as starting, auxiliary compiler, the exponent for floats is stored in the form of base
and ending pegs. 2. Obviously, because, computer stores the numbers in
------------------------------------------------------------------------- binary form. The C compiler follows an IEEE standard to
------------------------ store a float. The IEEE format expresses a floating-point
number in a binary form known as `normalized' form.
73. Normalization involves adjusting the exponent so that the
"binary point" (the binary analog of the decimal point) in the
What would be the output of following program? mantissa always lies to the right of most significant nonzero
digit. In binary representation, this means that the most
struct syntax significant digit of the mantissa is always a 1. This property
{ of the normalized representation is exploited by the IEEE
int i ; format when storing the mantissa. Let us consider an
float g ; example of generating the normalized form of a floating
char c ; point number. Suppose we want to represent the decimal
} number 5.375. Its binary equivalent can be obtained as
main( ) shown below:
{ 2|5
printf ( "I won't give you any error" ) ; .375 x 2 = 0.750 0
} |------
.750 x 2 = 1.500 1
Ans: The above program would get compiled successfully 2|21
and on execution it would print the message given in printf(). .500 x 2 = 1.000 1
What strikes in the above code snippet is the structure syntax |------
which is declared but not terminated with the statement 2|10
terminator, the semicolon. The compiler would not give any |------
error message for it, as it assumes that main( ) function have |01
a return type of struct syntax and hence would successfully Writing remainders in reverse writing whole parts in the
compile and execute the program. same order we get 101 order in which they are obtained we
------------------------------------------------------------------------- get 011 thus the binary equivalent of 5.375 would be
------------------------ 101.011. The normalized form of this binary number is
obtained by adjusting the exponent until the decimal point is Radix sort : It is reasonably efficient if the number of digits
to the right of most significant 1. In this case the result is in the keys is not too large.
1.01011 x 22. The IEEE format for floating point storage
uses a sign bit, a mantissa and an exponent for representing 76.
the power of 2. The sign bit denotes the sign of the number:
a 0 represents a positive value and a 1 denotes a negative Calculating Wasted Bytes On Disk
value. The mantissa is represented in binary. Converting the
floating-point number to its normalized form results in a When a file gets stored on the disk, at a time DOS allocates
mantissa whose most significant digit is always 1. The IEEE one cluster for it. A cluster is nothing but a group of sectors.
format takes advantage of this by not storing this bit at all. However, since all file sizes cannot be expected to be a
The exponent is an integer stored in unsigned binary format multiple of 512 bytes, when a file gets stored often part of
after adding a positive integer bias. This ensures that the the cluster remains unoccupied. This space goes waste unless
stored exponent is always positive. The value of the bias is the file size grows to occupy these wasted bytes. The
127 for floats and 1023 for doubles. Thus, 1.01011 x 22 is following program finds out how much space is wasted for
represented as shown below: all files in all the directories of the current drive.
--- --------------- ----------------------------------------------
| 0 | 100 0000 1 | 010 1100 0000 0000 0000 0000 | #include <dir.h>
--- ---------------- --------------------------------------------- #include <dos.h>
sign bit exponent- mantissa stored in normalized form #include <stdio.h>
obtained after adding a bias #include <string.h>
127 to exponent 2 #include <stdlib.h>
unsigned bytes_per_cluster ;
Data Structures unsigned long wasted_bytes ;
unsigned long num_files = 0 ;
Which is the best sorting method? main( )
Ans: There is no sorting method that is universally superior int ptr = 0, flag = 0, first = 0 ;
to all others. The programmer must carefully examine the struct ffblk f[50] ;
problem and the desired results before deciding the struct dfree free ;
particular sorting method. Some of the sorting methods are /* get cluster information and calculate bytes per cluster */
given below: getdfree ( 0, &free ) ;
Bubble sort : When a file containing records is to be sorted bytes_per_cluster = free.df_bsec * free.df_sclus ;
then Bubble sort is the best sorting method when sorting by chdir ( "\\" ) ;
address is used. /* check out files in root directory first */
cal_waste( ) ;
Bsort : It can be recommended if the input to the file is /* loop until all directories scanned */
known to be nearly sorted. while ( ptr != -1 )
Meansort : It can be recommended only for input known to /* should I do a findfirst or a findnext? */
be very nearly sorted. if ( first == 0 )
flag = findfirst ( "*.*", &f[ptr], FA_DIREC ) ;
Quick Sort : In the virtual memory environment, where else
pages of data are constantly being swapped back and forth flag = findnext ( &f[ptr] ) ;
between external and internal storage. In practical situations, while ( flag == 0 )
quick sort is often the fastest available because of its low {
overhead and its average behavior. /* make sure its a directory and skip over . & .. entries */
if ( f[ptr].ff_attrib == FA_DIREC && f[ptr].ff_name[0] != '.'
Heap sort : Generally used for sorting of complete binary )
tree. Simple insertion sort and straight selection sort : Both {
are more efficient than bubble sort. Selection sort is flag = chdir ( f[ptr].ff_name ) ; /* try changing directories */
recommended for small files when records are large and for if ( flag == 0 ) /* did change dir work? */
reverse situation insertion sort is recommended. The heap {
sort and quick sort are both more efficient than insertion or cal_waste( ) ;
selection for large number of data. first = 0 ; /* set for findfirst on next pass */
break ;
Shell sort : It is recommended for moderately sized files of }
several hundred elements. }
flag = findnext ( &f[ptr] ) ; /* search for more dirs */
} 77.
if ( flag != 0 || ptr == 49 ) /* didn't find any more dirs */ The Longjmp And Setjmp
ptr-- ; The C programming language does not let you nest
chdir ( ".." ) ; /* go back one level */ functions. You cannot write a function definition inside
first = 1 ; /* set to findnext on next pass */ another function definition, as in:
else int fun1( )
ptr++ ; {
} int fun2() /* such nesting of functions is not allowed */
printf ( "There are %lu bytes wasted in %lu files.\n", {
wasted_bytes, .....
num_files ) ; }
} }
cal_waste( ) Because of this restriction it is not possible to hide function
{ names inside a hierarchy. As a result all the functions that
int flag = 0 ; you declare within a program are visible to each other. This
long full_cluster ; of course is not a major drawback since one can limit
struct ffblk ff ; visibility by grouping functions within separate C source
/* look for all file types */ files that belong to different logical units of the program. C
flag = findfirst ( "*.*", &ff, FA_RDONLY | FA_HIDDEN | does, however, suffer in another way because of this design
FA_SYSTEM | FA_ARCH decision. It provides no easy way to transfer control out of a
); function except by returning to the expression that called the
while ( flag == 0 ) function. For the vast majority of function calls, that is a
{ desirable limitation. You want the discipline of nested
num_files++ ; function calls and returns to help you understand flow of
full_cluster = ff.ff_fsize / bytes_per_cluster * control through a program. Nevertheless, on some occasions
bytes_per_cluster ; that discipline is too restrictive. The program is sometimes
wasted_bytes += bytes_per_cluster - ( ff.ff_fsize - easier to write, and to understand, if you can jump out of one
full_cluster ) ; or more function invocations at a single stroke. You want to
flag = findnext ( &ff ) ; bypass the normal function returns and transfer control to
} somewhere in an earlier function invocation.
For example, you may want to return to execute some code
Data Structures for error recovery no matter where an error is detected in
your application. The setjmp and the longjmp functions
Polish Notation provide the tools to accomplish this. The setjmp function
saves the "state" or the "context" of the process and the
The method of writing all operators either before their longjmp uses the saved context to revert to a previous point
operation, or after them, is called Polish notation, in honor of in the program. What is the context of the process? In
its discoverer, the Polish mathematician Jan Lukasiewicz. general, the context of a process refers to information that
When the operators are written before their operands, it is enables you to reconstruct exactly the way the process is at a
called the prefix form. When the operators come after their particular point in its flow of execution. In C program the
operands. It is called the postfix form, or, sometimes reverse relevant information includes quantities such as values of
Polish form or suffix form. In this context, it is customary to SP, SS, FLAGS, CS, IP, BP, DI, ES, SI and DS registers.
use the coined phrase infix form to denote the usual custom
of writing binary operators between their operands. For To save this information Turbo C uses the following
example, the expression A + B becomes +AB in prefix form structure, which is defined, in the header file 'setjmp.h'.
and AB+ in postfix form. In the expression A + B x C, the typedef struct
multiplication is done first, so we convert it first, obtaining {
first A + ( BCx ) and then ABCx+ in postfix form. The unsigned j_sp ;
prefix form of this expression is +A x BC. The prefix and unsigned j_ss ;
postfix forms are not related by taking mirror images or unsigned j_flag ;
other such simple transformation. Also all parentheses have unsigned j_cs ;
been omitted in the Polish forms. unsigned j_ip ;
unsigned j_bp ;
------------------------------------------------------------------------- unsigned j_di ;
------------------------ unsigned j_es ;
unsigned j_si ; circle we put the index of the key against which we are
unsigned j_ds ; comparing the target key. Branches (lines) drawn down from
} jmp_buf[1] ; the circle represent the possible outcomes of the comparison
This is a system-dependent data type because different and are labeled accordingly. When the algorithm terminates,
systems might require different amounts of information to we put either F (for failure) or the location where the target
capture the context of a process. In Turbo C, jmp_buf is is found at the end of the appropriate branch, which we call a
simply an array of ten 2-byte integers. To understand the leaf, and draw as a square. Leaves are also sometimes called
mechanics of setjmp and longjmp, look at the following code end vertices or external vertices of the tree. The remaining
fragment. vertices are called the internal vertices of the tree. The
#include "setjmp.h" comparison tree for sequential search is especially simple.
jmp_buf buf ; -------------------------------------------------------------------------
main( ) ------------------------
{ 78.
if ( setjmp ( buf ) == 0 )
process( ) ; Suppose we have a floating-point number with higher
else precision say 12.126487687 and we wish it to be printed
handle_error( ) ; /* executed when longjmp is called */ with only precision up to two decimal places. How can I do
} this?
process( )
{ Ans. This can achieved through the use of suppression char
int flag = 0 ; '*' in the format string of printf( ) which is shown in the
/* some processing is done here */ following program.
/* if an error occurs during processing flag is set up */ main( )
if ( flag ) {
longjmp ( buf, 1 ) ; int p = 2 ;
} float n = 12.126487687 ;
printf ( "%.*f",p, n ) ;
Upon entry to setjmp the stack contains the address of the }
buffer buf and the address of the if statement in the main -------------------------------------------------------------------------
function, to which setjmp will return. The setjmp function ------------------------
copies this return address as well as the current values of 79.
registers, SP, SS, FLAGS, BP, DI, ES, SI and DS, into the Spawning
buffer buf. Then setjmp returns with a zero. In this case, the
if statement is satisfied and the process( ) function is called. All programs that we execute from DOS prompt can be
If something goes wrong in process( ) (indicated by the flag thought of as children of COMMAND.COM. Thus, the
variable), we call longjmp with two arguments: the first is program that we execute is a child process, whereas
the buffer that contains the context to which we will return. COMMAND.COM running in memory is its parent. The
When the stack reverts back to this saved state, and the process of a parent process giving birth to a child process is
return statement in longjmp is executed, it will be as if we known as 'spawning'. If the spawned program so desires, it
were returning from the call to setjmp, which originally may in turn spawn children of its own, which then execute
saved the buffer buf. The second argument to longjmp and return control to their parent. Who is the parent of
specifies the return value to be used during this return. It COMMAND.COM? COMMAND.COM itself. We can trace
should be other than zero so that in the if statement we can the ancestors of our program using the field Parent Process
tell whether the return is induced by a longjmp. ID (PID) present at offset 0x16 in the Program Segment
Prefix (PSP). To trace this ancestry our program should first
The setjmp/longjmp combination enables you to jump locate its PSP, extract the parent process ID from it and then
unconditionally from one C function to another without use this to find PSP of the parent. This process can be
using the conventional return statements. Essentially, setjmp repeated till we reach COMMAND.COM (process ID of
marks the destination of the jump and longjmp is a non-local COMMAND.COM is its own PSP), the father of all
goto that executes the jump. processes. Here is a program which achieves this...
Data Structures
/* SPAWN.C */
Comparison Trees... #include "dos.h"

The comparison trees also called decision tree or search tree unsigned oldpsp, newpsp, far *eb_seg, i ;
of an algorithm, is obtained by tracing through the actions of char far *eb_ptr ;
the algorithm, representing each comparison of keys by a
vertex of the tree (which we draw as a circle). Inside the main( )
{ corresponding file names until the program reaches
oldpsp = _psp ; COMMAND.COM.

while ( 1 ) The printname( ) function first locates the environment block

{ of the program and then extracts the file name from the
printf ( "\n" ) ; environment block. The fnsplit( ) function has been used to
printname ( oldpsp ) ; eliminate the path present prior to the file name. Do not run
printf ( " spawned by " ) ; the program from command line since it would give you
only one level of ancestry.
newpsp = * ( ( unsigned far * ) MK_FP ( oldpsp, 0x16 ) ) ;
Data Structures
if ( * ( ( unsigned * ) MK_FP ( newpsp, 0x16 ) ) ==
newpsp ) Choosing the data structures to be used for information
break ; retrieval. For problems of information retrieval, consider the
else size, number, and location of the records along with the type
oldpsp = newpsp ; and structure of the keys while choosing the data structures
to be used. For small records, high-speed internal memory
printname ( newpsp ) ; will be used, and binary search trees will likely prove
} adequate. For information retrieval from disk files, methods
employing multiway branching, such as trees, B-trees , and
printf ( "%-20s (%04X)", "COMMAND.COM", newpsp ) ; hash tables, will usually be superior. Tries are particularly
} suited to applications where the keys are structured as a
sequence of symbols and where the set of keys is relatively
printname ( unsigned lpsp ) dense in the set of all possible keys. For other applications,
{ methods that treat the key as a single unit will often prove
char drive[5], dir[68], name[13], ext[5] ; superior. B-trees, together with various generalization and
extensions, can be usefully applied to many problems
eb_seg = ( unsigned far * ) MK_FP ( lpsp, 0x2C ) ; concerned with external information retrieval.
eb_ptr = MK_FP ( *eb_seg, 0 ) ;

i=0; 80.
while ( 1 )
{ Variably Dimensioned Arrays
if ( eb_ptr[i] == 0 )
{ While dealing with Scientific or Engineering problems one
if ( eb_ptr[i + 1] == 0 && eb_ptr[i + 2] == 1 ) is often required to make use of multi-dimensioned array.
{ However, when it comes to passing multidimensional arrays
i += 4 ; to a function C is found wanting. This is because the C
break ; compiler wants to know the size of all but the first dimension
} of any array passed to a function. For instance, we can define
} a function compute ( int n, float x[] ), but not compute ( int
i++ ; n, x[][]).
Thus, C can deal with variably dimensioned 1-D arrays, but
fnsplit ( eb_ptr + i, drive, dir, name, ext ) ; when an array has more than one dimension, the C compiler
strcat ( name, ext ) ; has to know the size of the last dimensions expressed as a
printf ( "%-20s (%04X)", name, oldpsp ) ; constant. This problem has long been recognized, and some
} of the solutions that are often used are:

On running the program from within TC the output obtained Declare the arrays in the functions to be big enough to tackle
is shown below. SPWAN.EXE (58A9) spawned by TC.EXE all possible situations. This can lead to a wastage of lot of
(0672) TC.EXE (0672) spawned by COMMAND.COM precious memory in most cases. Another solution is to
(05B8). The program simply copies its own process ID in the construct multiple-dimension array as an array of pointers.
variable oldpsp and then uses it to extract its own filename For example, a matrix (2-D array) of floats can be declared
from its environment block. This is done by the function as a 1-D array of float pointers, with each element pointing
printname( ). The value in oldpsp is then used to retrieve the to an array of floats. The problem with this method is that
parent's PID in newpsp. From there the program loops the calling function has to define all arrays in this fashion.
reporting the values of oldpsp, newpsp and the
This means that any other computations done on the arrays for ( j = 0 ; j < p ; j++ )
must take this special structure into account. *ptrtoc++ += *a * *ptrtob++ ;
a++ ;
Another easy solution, though seldom used, exists. This is }
based on the following method: c += p ;
Pass the array to the function as though it is a pointer to an }
array of floats (or the appropriate data type), no matter how
many dimensions the array actually has, along with the We know that C stores array elements in a row-major order.
dimensions of the array. Reference individual array elements Hence to ensure that the elements are accessed in the storage
as offsets from this pointer. order the above program uses a variation of the normal
Write your algorithm so that array elements are accessed in matrix-multiplication procedure. The pseudo code for this is
storage order. The following program for multiplying two given below:
matrices illustrates this for i = 1 to m
procedure. for j = 1 to p
# define M 3 c[i][j] = 0
# define N 2 end
# define P 4 for k = 1 to n
for j = 1 to p
float a[M][N], b[N][P], c[M][P] ; c[i][j] = c[i][j] + a[i][k] * b[k][j]
void mulmat ( int, int, int, float*, float*, float* ) ; end
main( ) end
{ -------------------------------------------------------------------------
int i, j ; ------------------------
for ( i = 0 ; i < M ; i++ ) 81.
for ( j = 0 ; j < N ; j++ )
a[i][j] = i + j ; Why is it not possible to scan strings from keyboard in case
of array of pointers to string?
for ( i = 0 ; i < N ; i++ )
for ( j = 0 ; j < P ; j++ ) Ans: When an array is declared, dimension of array should
b[i][j] = i + j ; be specified so that compiler can allocate memory for the
array. When array of pointers to strings is declared its
mulmat ( M, N, P, a, b, c ) ; elements would contain garbage addresses. These addresses
for ( i = 0 ; i < M ; i++ ) would be passed to scanf( ). So strings can be received but
{ they would get stored at unkown locations. This is unsafe.
printf ( "\n" ) ; -------------------------------------------------------------------------
for ( j = 0 ; j < P ; j++ ) ------------------------
printf ( "%f\t", c[i][j] ) ; 82.
} Bit Arrays
If in a program a variable is to take only two values 1 and 0,
void mulmat ( int m, int n, int p, float *a, float *b, float *c ) we really need only a single bit to store it. Similarly, if a
{ variable is to take values from 0 to 3, then two bits are
float *ptrtob, *ptrtoc ; sufficient to store these values. And if a variable is to take
int i, j, k, nc ; values from 0 through 7, then three bits will be enough, and
so on. Why waste an entire integer when one or two or three
/* set all elements of matrix c to 0 */ bits will do? Because there aren't any one bit or two bit or
for ( i = 0 ; i < m * p ; i++ ) three bit data types available in C. However, when there are
*( c + i ) = 0 ; several variables whose maximum values are small enough
to pack into a single memory location, we can use `bit fields'
for ( i = 0 ; i < m ; i++ ) to store several values in a single integer. Bit fields are
{ discussed in most standard C texts. They are usually used
ptrtob = b ; when we want to store assorted information which can be
for ( k = 0 ; k < n ; k++ ) accommodated in 1, 2, 3 bits etc.
ptrtoc = c ; For example, the following data about an employee can be
easily stored using bit fields.
main( )
male or female {
single, married, divorced or widowed char arr[NUMSLOTS( MAX )] ;
have one of the eight different hobbies int i, j ;
can choose from any of the fifteen different schemes
proposed by the company to pursue his/her hobby. memset ( arr, 0, NUMSLOTS( MAX ) ) ;
for ( i = 2 ; i < MAX ; i++ )
This means we need one bit to store gender, two to store {
marital status, three for hobby, and four for scheme (with if ( !TEST ( arr, i ) )
one value used for those who are not desirous of availing any {
of the schemes). We need ten bits altogether, which means printf ( "\n%d", i ) ;
we can pack all this information into a single integer, since for ( j = i + i ; j < MAX ; j += i )
an integer is 16 bits long. SET ( arr, j ) ;
At times we may need to store several True or False statuses. }
In such cases instead of using bit fields using an array of bits }
would be more sensible. On this array we may be required to -------------------------------------------------------------------------
perform the following operations: ------------------------
Set a bit (make it 1). Information Hiding in C
Clear a bit (make it 0).
Test the status of a bit in the array. Though C language doesn't fully support encapsulation as
Reach the appropriate bit slot in the array. C++ does, there is a simple technique through which we can
Generate a bit mask for setting and clearing a bit. implement encapsulation in C. The technique that achieves
We can implement these operations using macros given this is modular programming in C. Modular programming
below: requires a little extra work from the programmer, but pays
for itself during maintenance. To understand this technique
#define CHARSIZE 8 let us take the example of the popular stack data structure.
#define MASK ( y ) ( 1 << y % CHARSIZE ) There are many methods of implementing a stack (array,
#define BITSLOT ( y ) ( y / CHARSIZE ) linked list, etc.). Information hiding teaches that users should
#define SET ( x, y ) ( x[BITSLOT( y )] |= MASK( y ) ) be able to push and pop the stack's elements without
#define CLEAR ( x, y ) ( x[BITSLOT( y )] &= knowing about the stack's implementation. A benefit of this
~MASK( y ) ) sort of information hiding is that users don't have to change
#define TEST ( x, y ) ( x[BITSLOT( y )] & MASK( y ) ) their code even if the implementation details change.
#define NUMSLOTS ( n ) ( ( n + CHARSIZE - 1) /
CHARSIZE ) Consider the following scenario:

Using these macros we can declare an array of 50 bits be To be able to appreciate the benefits of modular
saying, programming and thereby information hiding, would first
show a traditional implementation of the stack data structure
char arr[NUMSLOTS(50)] ; using pointers and a linked list of structures. The main( )
To set the 20th bit we can say, function calls the push( ) and pop( ) functions.

SET(arr, 20 ) ; #include <alloc.h>

And if we are to test the status of 40th bit we may say, typedef int element ;
if ( TEST ( arr, 40 ) ) void initialize_stack ( struct node ** ) ;
Using bit arrays often results into saving a lot of precious void push ( struct node **, element ) ;
memory. For example, the following program which element pop ( struct node * ) ;
implements the Sieve of Eratosthenes for generating prime int isempty ( struct node * ) ;
numbers smaller than 100 requires only 13 bytes. Had we struct node
implemented the same logic using an array of integers we {
would have required an array of 100 integers, that is 200 element data ;
bytes. struct node *next ;
#include <stdio.h> };
#include <string.h> void main( )
#define MAX 100 struct node *top ;
element num ;
initialize_stack ( &top ) ; sorter. For example, to sort a collection of numbers where
push ( &top, 10 ) ; each number is a four-digit number, then, All the numbers
push ( &top, 20 ) ; are first sorted according to the the digit at unit's place.
push ( &top, 30 ) ; In the second pass, the numbers are sorted according to the
if ( isempty ( top ) ) digit at tenth place. In the third pass, the numbers are sorted
printf ( "\nStack is empty" ) ; according to the digit at hundredth place. In the forth and last
else pass, the numbers are sorted according to the digit at
{ thousandth place.
num = pop ( top ) ; During each pass, each number is taken in the order in which
printf ( "\n Popped %d", num ) ; it appears in partitions from unit's place onwards. When
} these actions have been performed for each digit, starting
} with the least significant and ending with most significant,
void initialize_stack ( struct node **p ) the numbers are sorted. This sorting method is called the
{ radix sort.
*p = NULL ;
} Let us take another example. Suppose we have a list of
void push ( struct node **p, element n ) names. To sort these names using radix sort method we will
{ have to classify them into 26 groups The list is first sorted on
struct node *r ; the first letter of each name, i.e. the names are arranged in 26
r = ( struct node *) malloc ( sizeof ( struct node ) ) ; classes, where the first class consists of those names that
r -> data = n ; begin with alphabet 'A', the second class consists of those
if ( *p == NULL ) names that begin with alphabet 'B' and so on. During the
r -> next = NULL ; second pass each class is alphabetized according to the
else second letter of the name, and so on.
r -> next = *p ; 84.
*p = r ;
} Exception Handling in C
element pop ( struct node *p )
{ Consider the following program:
element n ;
struct node *r ; #include <math.h>
n = p -> data ; void main( )
r=p; {
p = p -> next ; float i ;
free ( r ) ; i = pow ( -2, 3 ) ;
return ( n ) ; printf ( "%f", i ) ;
} }
int isempty ( struct node *p )
{ int matherr ( struct exception *a )
if ( p == NULL ) {
return ( -1 ) ; if ( a -> type == DOMAIN )
else {
return ( 0 ) ; if ( !strcmp ( a -> name, "pow" ) )
} {
Notice how the specific implementation of the data structure a -> retval = pow ( - ( a -> arg1 ), a -> arg2 ) ;
is strewn throughout main( ). main( ) must see the definition return 1 ;
of the structure node to use the push( ), pop( ), and other }
stack functions. Thus the implementation is not hidden, but }
is mixed with the abstract operations. return 0 ;
Data Structures
If we pass a negative value in pow( ) function a run time
Radix Sort error occurs. If we wish to get the proper output even after
passing a negative value in the pow( ) function we must
This sorting technique is based on the values of the actual handle the run time error. For this, we can define a function
digits in the positional representations of the numbers being matherr( ) which is declared in the 'math.h' file. In this
sorted. Using the decimal base, for example, where the radix function we can detect the run-time error and write our code
is 10, the numbers can be partitioned into ten groups on the to correct the error. The elements of the exception structure
receives the function name and arguments of the function bstp %= fval ;
causing the exception. for ( cnt4 = 0, cnt3 = 1 ; cnt3 <= unit ; cnt3++ )
while ( box[0][++cnt4] == 0 ) ;
Data Structures }
box[1][cnt2] = box[0][cnt4] ;
AVL Trees box[0][cnt4] = 0 ;
For ideal searching in a binary search tree, the heights of the printf ( "\nSeq.No.%ld:", cnt1 ) ;
left and right sub-trees of any node should be equal. But, due for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )
to random insertions and deletions performed on a binary printf ( " %d", box[1][cnt2] ) ;
search tree, it often turns out to be far from ideal. A close }
approximation to an ideal binary search tree is achievable if }
it can be ensured that the difference between the heights of This program computes the total number of steps. But
the left and the right sub trees of any node in the tree is at instead of entering into the loop of the first and last
most one. A binary search tree in which the difference of combination to be generated it uses a loop of 1 to number of
heights of the right and left sub-trees of any node is less than combinations. For example, in case of input being 5 the
or equal to one is known as an AVL tree. AVL tree is also number of possible combinations would be factorial 5, i.e.
called as Balanced Tree. The name "AVL Tree" is derived 120. The program suffers from the limitation that it cannot
from the names of its inventors who are Adelson-Veilskii generate combinations for input beyond 12 since a long int
and Landi. A node in an AVL tree have a new field to store cannot handle the resulting combinations.
the "balance factor" of a node which denotes the difference
of height between the left and the right sub-trees of the tree Data Structures
rooted at that node. And it can assume one of the
three possible values {-1,0,1}. Hashing...
------------------------ Hashing or hash addressing is a searching technique.
85. Usually, search of an element is carried out via a sequence of
comparisons. Hashing differs from this as it is independent
Unique combinations for a given number of the number of elements n in the collection of data. Here,
the address or location of an element is obtained by
How do I write a program which can generate all possible computing some arithmetic function. Hashing is usually used
combinations of numbers from 1 to one less than the given in file management. The general idea is of using the key to
number ? determine the address of a record. For this, a function fun( )
main( ) is applied to each key, called the hash function. Some of the
{ popular hash functions are: 'Division' method, 'Midsquare'
long steps, fval, bstp, cnt1 ; method, and 'Folding' method. Two records cannot occupy
int num, unit, box[2][13], cnt2, cnt3, cnt4 ; the same position. Such a situation is called a hash collision
printf ( "Enter Number " ) ; or a hash clash. There are two basic methods of dealing with
scanf ( "%d", &num ) ; a hash clash. The first technique, called rehashing, involves
num = num < 1 ? 1 : num > 12 ? 12 : num ; using secondary hash function on the hash key of the item.
for ( steps = 1, cnt1 = 2 ; cnt1 <= num ; steps *= cnt1++ ) ; The rehash function is applied successively until an empty
for ( cnt1 = 1 ; cnt1 <= steps ; cnt1++ ) position is found where the item can be inserted. If the hash
{ position of the item is found to be occupied during a search,
for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ ) the rehash function is again used to locate the item. The
box[0][cnt2] = cnt2 ; second technique, called chaining, builds a linked list of all
for ( fval = steps, bstp = cnt1, cnt2 = 1 ; cnt2 <= num ; cnt2+ items whose keys hash to the same values. During search,
+) this short linked list is traversed sequentially for the desired
{ key. This technique involves adding an extra link field to
if ( bstp == 0 ) each table position.
{ -------------------------------------------------------------------------
cnt4=num ; ------------------------
while ( box[0][cnt4] == 0 )
cnt4-- ; 86.
else The following program demonstrates how to get input from
{ the user in graphics mode, echoed in the current colors and
fval /= num - cnt2 + 1 ; font size and font style.
unit = ( bstp + fval - 1 ) / fval ;
#define ON 1 outtext ( outString ) ;
#define OFF 0 ++stringIndex ;
#include <graphics.h> xVal[stringIndex] = getx( ) ;
main( ) }
{ }
char nameString[80], ageString[80] ; } while ( ch != 13 && ch != 10 ) ;
int age, gd = DETECT, gm ; inputString[stringIndex] = 0 ;
initgraph ( &gd, &gm, "c:\\tc\\bgi" ) ; }
setbkcolor ( BLUE ) ; cursor ( int on )
setcolor ( YELLOW ) ; {
settextstyle ( GOTHIC_FONT, HORIZ_DIR, 0 ) ; int curX, oldColor ;
moveto ( 0, 0 ) ; /* we'll use an underscore as a cursor */
outtext ( "Enter your name: " ) ; char uBarStr[2] = { '_', 0 } ;
getGrString ( nameString ) ; if ( !on )
moveto ( 0, gety( ) + textheight ( "A" ) ) ; {
outtext ( "Name: " ) ; oldColor = getcolor( ) ;
outtext ( nameString ) ; setcolor ( getbkcolor( ) ) ;
moveto ( 0, gety( ) + textheight ( "A" ) ) ; }
outtext ( "Press key to exit! " ) ; /* save horizontal position before drawing cursor */
getch( ) ; curX = getx( ) ;
closegraph( ) ; outtext ( uBarStr ) ;
restorecrtmode( ) ; moveto ( curX, gety( ) ) ;
} /* if we changed the color to erase cursor, change it back */
getGrString ( char *inputString ) if ( !on )
{ setcolor ( oldColor ) ;
int stringIndex = 0, oldColor ; }
char ch, outString[2] ; The function getGrString( ) echoes graphically the user input
/* xVal will store the screen position for each char */ and stores it in a buffer, and the function cursor( ) handles
int xVal[255] ; the cursor position.
outString[1] = 0 ;
xVal[0] = getx( ) ; System Utility
{ What is garbage collection?
cursor ( ON ) ;
ch = getch( ) ; Ans: Suppose some memory space becomes reusable
cursor ( OFF ) ; because a node is released from a linked list. Hence, we want
if ( ch == 0 ) /* avoid dealing with all special keys */ the space to be available for future use. One way to bring
getch( ) ; this about is to immediately reinsert the space into the free-
else storage list. However, this method may be too time-
{ consuming for the operating system. The operating system
if ( ch == 8 ) /* backspace */ may periodically collect all the deleted space onto the free-
{ storage list. The technique that does this collection is called
oldColor = getcolor( ) ; Garbage Collection. Garbage Collection usually takes place
--stringIndex ; in two steps: First the Garbage Collector runs through all
if ( stringIndex < 0 ) lists, tagging whose cells are currently in use, and then it
stringIndex = 0 ; runs through the memory, collecting all untagged space onto
/* move to ( old horz position, current vert position ) */ the free-storage list. The Garbage Collection may take place
moveto ( xVal[stringIndex], gety( ) ) ; when there is only some minimum amount of space or no
setcolor ( getbkcolor( ) ) ; space at all left in the free-storage list, or when the CPU is
outString[0] = inputString[stringIndex] ; idle and has time to do the collection. Generally speaking,
outtext ( outString ) ; the Garbage Collection is invisible to the programmer.
moveto ( xVal [stringIndex], gety( ) ) ;
setcolor ( oldColor ) ;
} 87.
{ How do I get the time elapsed between two function calls ?
inputString[stringIndex] = ch ;
outString[0] = ch ;
Ans: The function difftime( ) finds the difference between What is a priority queue?
two times. It calculates the elapsed time in seconds and
returns the difference between two times as a double value. Ans: As we know in a stack, the latest element is deleted and
in a queue the oldest element is deleted. It may be required
#include <time.h> to delete an element with the highest priority in the given set
#include <stdio.h> of values and not only the oldest or the newest one. A data
#include <dos.h> structure that supports efficient insertions of a new element
and deletions of elements with the highest priority is known
main( ) as priority queue. There are two types of priority queues: an
{ ascending priority queue is a collection of items into which
int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ; items can be inserted arbitrarily and from which only the
int s ; smallest item can be removed. A descending order priority
time_t t1, t2 ; // time_t defines the value used for time queue is similar but allows only the largest item to be
function deleted.
s = sizeof ( a ) / 2 ; ------------------------
t1 = time ( NULL ) ; 89.
sel_sort ( a, s ) ; // sort array by selection sort
bub_sort ( a, s ) ; // sort array by bubble sort method What is the difference between const char *p, char const *p,
t2 = time ( NULL ) ; and char* const p ?
printf ( "\nThe difference between two function calls is %f",
difftime ( 'const char *p' and 'char const *p' are the same, i.e. p points
t2, t1 ) ) ; to a constant character. On the other hand, 'char* const p'
} means p is a constant pointer pointing to a character which
means we cannot change the pointer p but we can change the
In the above program we have called difftime( ) function that character which p is pointing to.
returns the time elapsed from t1 to t2. -------------------------------------------------------------------------
------------------------------------------------------------------------- ------------------------
------------------------ 90.
What's the difference between a null pointer, a NULL macro,
General the ASCII NUL character and a null string?
main( )
{ Ans: A null pointer is a pointer which doesn't point
char *s ; anywhere. A NULL macro is used to represent the null
s = fun ( 128, 2 ) ; pointer in source code. It has a value 0 associated with it.
printf ( "\n%s", s ) ; The ASCII NUL character has all its bits as 0 but doesn't
} have any relationship with the null pointer. The null string is
fun ( unsigned int num, int base ) just another name for an empty string "".
static char buff[33] ; System Utility
char *ptr ;
ptr = &buff [ sizeof ( buff ) - 1 ] ; Sparse Matrix...
*ptr = '\0' ;
do A sparse matrix is one where most of its elements are zero.
{ There is no precise definition as to know whether a matrix is
*--ptr = "0123456789abcdef"[ num % base ] ; sparsed or not, but it is a concept which we all can recognize
num /= base ; intuitively. The natural method of representing matrices in
} while ( num != 0 ) ; memory as two-dimensional arrays may not be suitable for
return ptr ; sparse matrices. That is one may save space by storing only
} those entries which may be nonzero. If this is done, then the
The above program would convert the number 128 to the matrix may be thought of as an ordered list of non-zero
base 2. You can convert a number to a hexadecimal or octal elements only. Information about a non-zero element has
form by passing the number and the base, to the function three parts:
fun( ). an integer representing its row,
an integer representing its column and
Data Structures the data associated with this element.
That is, each element of a matrix is uniquely characterized -------------------------------------------------------------------------
by its row and column position, say i, j. We might store that ------------------------
matrix as a list of 3-tuples of the form (i, j, data), as shown 92.
Can we get the remainder of a floating point division ?
Although the non-zero elements may be stored in the array
in any order, keeping them ordered in some fashion may be Ans : Yes. Although the % operator fails to work on float
advantageous for further processing. Note that above array is numbers we can still get the remainder of floating point
arranged in increasing order of the row number of non-zero division by using a function fmod( ). The fmod( ) function
elements. Moreover, for elements in the same row number, divides the two float numbers passed to it as parameters and
the array is arranged in order of increasing column number. returns the remainder as a floating-point value. Following
------------------------------------------------------------------------- program shows fmod( ) function at work.
91. #include <math.h>

Pointers main( )
What does the error "Null Pointer Assignment" mean and printf ( "%f", fmod ( 5.15, 3.0 ) ) ;
what causes this error? }

Ans: The Null Pointer Assignment error is generated only in The above code snippet would give the output as 2.150000.
small and medium memory models. This error occurs in -------------------------------------------------------------------------
programs which attempt to change the bottom of the data ------------------------
segment. In Borland's C or C++ compilers, Borland places 93.
four zero bytes at the bottom of the data segment, followed
by the Borland copyright notice "Borland C++ - Copyright How to extract the integer part and a fractional part of a
1991 Borland Intl.". In the small and medium memory floating point number?
models, a null pointer points to DS:0000. Thus assigning a
value to the memory referenced by this pointer will Ans: C function modf( ) can be used to get the integer and
overwrite the first zero byte in the data segment. At program fractional part of a floating point.
termination, the four zeros and the copyright banner are
checked. If either has been modified, then the Null Pointer #include "math.h"
Assignment error is generated. Note that the pointer may not
truly be null, but may be a wild pointer that references these main( )
key areas in the data segment. {
double val, i, f ;
Data Structures val = 5.15 ;
f = modf ( val, &i ) ;
How to build an expression trees ? printf ( "\nFor the value %f integer part = %f and fractional
part = %f",
Ans: An expression tree is a binary tree which is built from val, i, f ) ;
simple operands and operators of an (arithmetic or logical ) }
expression by placing simple operands as the leaves of a
binary tree and the operators as the interior nodes. If an The output of the above program will be:
operator is binary , then it has two nonempty subtrees, that
are its left and right operands (either simple operands or sub For the value 5.150000 integer part = 5.000000 and
expressions). If an operator is unary, then only one of its fractional part =
subtrees is nonempty, the one on the left or right according 0.150000
as the operator is written on the right or left of its operand.
We traditionally write some unary operators to the left of 94.
their operands, such as "-" ( unary negation) or the standard
functions like log( ), sin( ) etc. Others are written on the How do I define a pointer to a function which returns a char
right, such as the factorial function ()!. If the operator is pointer?
written on the left, then in the expression tree we take its left Ans:
subtree as empty. If it appears on the right, then its right char * ( *p )( ) ;
subtree will be empty. An example of an expression tree is or
shown below for the expression ( -a < b ) or ( c + d ) . typedef char * ( * ptrtofun )( ) ;
ptrtofun p ;
Here is a sample program which uses this definition.
main( ) Can we use scanf( ) function to scan a multiple words string
{ through keyboard?
typedef char * ( * ptrtofun ) ( ) ;
char * fun( ) ; Ans: Yes. Although we usually use scanf( ) function to
ptrtofun fptr ; receive a single word string and gets( ) to receive a multi-
char *cptr ; word string from keyboard we can also use scanf( ) function
fptr = fun ; for scanning a multi-word string from keyboard. Following
cptr = (*fptr) ( ) ; program shows how to achieve this.
printf ( "\nReturned string is \"%s\"", cptr ) ;
} main( )
char * fun( ) {
{ char buff[15] ;
static char s[ ] = "Hello!" ; scanf ( "%[^\n]s", buff ) ;
printf ( "\n%s", s ) ; puts ( buff ) ;
return s ; }
------------------------------------------------------------------------- In the scanf( ) function we can specify the delimiter in
------------------------ brackets after the ^ character. We have specified '\n' as the
95. delimiter. Hence scanf( ) terminates only when the user hits
What's wrong with the following declaration: char* ptr1, Enter key.
ptr2 ; get errors when I try to use ptr2 as a pointer. -------------------------------------------------------------------------
Ans: char * applies only to ptr1 and not to ptr2. Hence ptr1 99.
is getting declared as a char pointer, whereas, ptr2 is being How to set the system date through a C program ?
declared merely as a char. This can be rectified in two ways :
char *ptr1, *ptr2 ; Ans: We can set the system date using the setdate( ) function
typedef char* CHARPTR ; CHARPTR ptr1, ptr2 ; as shown in the following program. The function assigns the
------------------------------------------------------------------------- current time to a
------------------------ structure date.
#include "stdio.h"
How to use scanf( ) to read the date in the form of dd-mm- #include "dos.h"
main( )
Ans: To read the date in the form of dd-mm-yy one possible {
way is, struct date new_date ;
int dd, mm, yy ;
char ch ; /* for char '-' */ new_date.da_mon = 10 ;
printf ( "\nEnter the date in the form of dd-mm-yy : " ) ; new_date.da_day = 14 ;
scanf( "%d%c%d%c%d", &dd, &ch, &mm, &ch, &yy ) ; new_date.da_year = 1993 ;
Another way is to use suppression character * is as follows:
int dd, mm, yy ; setdate ( &new_date ) ;
scanf( "%d%*c%d%*c%d", &dd, &mm, &yy ) ; }
The suppression character '*' suppresses the input read from -------------------------------------------------------------------------
the standard input buffer for the assigned control character. ------------------------
------------------------ 100.
How can I write a general-purpose swap without using
Why the output of sizeof ( 'a' ) is 2 and not 1 ? templates?
Ans: Character constants in C are of type int, hence sizeof
( 'a' ) is equivalent to sizeof ( int ), i.e. 2. Hence the output Ans: Given below is the program which uses the stringizing
comes out to be 2 bytes. preprocessor directive ## for building a general purpose
------------------------------------------------------------------------- swap macro which can swap two integers, two floats, two
------------------------ chars, etc.
#define swap( a, b, t ) ( g ## t = ( a ), ( a ) = ( b ), ( b ) = g ##
98. t)
int gint; process id. uniquely identifies a program. Under DOS, the
char gchar; getpid( ) returns the Program Segment Prefix as the process
float gfloat ; id. Following program illustrates the use of this macro.
main( ) #include <stdio.h>
{ #include <process.h>
int a = 10, b = 20 ;
char ch1 = 'a' , ch2 = 'b' ; void main( )
float f1 = 1.12, f2 = 3.14 ; {
swap ( a, b, int ) ; printf ( "The process identification number of this program is
printf ( "\na = %d b = %d", a, b ) ; %X\n",
swap ( ch1, ch2, char ) ; getpid( ) ) ;
printf ( "\nch1 = %c ch2 = %c", ch1, ch2 ) ; }
swap ( f1, f2, float ) ;
printf ( "\nf1 = %4.2f f2 = %4.2f", f1, f2 ) ; -------------------------------------------------------------------------
} ------------------------
swap ( a, b, int ) would expand to,
( gint = ( a ), ( a ) = ( b ), ( b ) = gint )
------------------------ 104.
What is a heap ? How do I write a function that takes variable number of
Ans : Heap is a chunk of memory. When in a program
memory is allocated dynamically, the C run-time library gets Ans: The following program demonstrates this.
the memory from a collection of unused memory called the
heap. The heap resides in a program's data segment. #include <stdio.h>
Therefore, the amount of heap space available to the #include <stdarg.h>
program is fixed, and can vary from one program to another.
void main( )
102. int i = 10 ;
float f = 2.5 ;
How to obtain a path of the given file? char *str = "Hello!" ;
vfpf ( "%d %f %s\n", i, f, str ) ;
Ans: The function searchpath( ) searches for the specified vfpf ( "%s %s", str, "Hi!" ) ;
file in the subdirectories of the current path. Following }
program shows how to make use of the searchpath( )
function. void vfpf ( char *fmt, ... )
#include "dir.h" va_list argptr ;
va_start ( argptr, fmt ) ;
void main ( int argc, char *argv[] ) vfprintf ( stdout, fmt, argptr ) ;
{ va_end ( argptr ) ;
char *path ; }
if ( path = searchpath ( argv[ 1 ] ) )
printf ( "Pathname : %s\n", path ) ; Here, the function vfpf( ) has called vfprintf( ) that take
else variable argument lists. va_list is an array that holds
printf ( "File not found\n" ) ; information required for the macros va_start and va_end.
} The macros va_start and va_end provide a portable way to
------------------------------------------------------------------------- access the variable argument lists. va_start would set up a
------------------------ pointer argptr to point to the first of the variable arguments
103. being passed to the function. The macro va_end helps the
called function to perform a normal return.
Can we get the process identification number of the current -------------------------------------------------------------------------
program? ------------------------
Ans: Yes! The macro getpid( ) gives us the process Can we change the system date to some other date?
identification number of the program currently running. The
Ans: Yes, We can! The function stime( ) sets the system date On including a file twice I get errors reporting redefinition of
to the specified date. It also sets the system time. The time function.
and date is measured in seconds from the 00:00:00 GMT, How can I avoid duplicate inclusion?
January 1, 1970. The following program shows how to use
this function. Ans: Redefinition errors can be avoided by using the
#include <stdio.h> following macro definition. Include this definition in the
#include <time.h> header file.
#if !defined filename_h
void main( ) #define filename_h
{ /* function definitions */
time_t tm ; #endif
int d ; Replace filename_h with the actual header file name. For
example, if name of file to be included is 'goto.h' then
tm = time ( NULL ) ; replace filename_h with 'goto_h'.
printf ( "The System Date : %s", ctime ( &tm ) ) ; ------------------------
printf ( "\nHow many days ahead you want to set the date : 108.
"); How to write a swap( ) function which swaps the values of
scanf ( "%d", &d ) ; the variables using bitwise operators.

tm += ( 24L * d ) * 60L * 60L ; Ans: Here is the swap( ) function.

swap ( int *x, int *y )
stime ( &tm ) ; {
printf ( "\nNow the new date is : %s", ctime ( &tm ) ) ; *x ^= *y ;
} *y ^= *x ;
In this program we have used function ctime( ) in addition to *x ^= *y ;
function stime( ). The ctime( ) function converts time value }
to a 26-character long string that contains date and time. The swap( ) function uses the bitwise XOR operator and
------------------------------------------------------------------------- does not require any temporary variable for swapping.

How to use function strdup( ) in a program?

Ans : The string function strdup( ) copies the given string to ############################
a new location. The function uses malloc( ) function to 1. What are the two types of transmission technology
allocate space required for the duplicated string. It takes one available?
argument a pointer to the string to be duplicated. The total
number of characters present in the given string plus one (i) Broadcast and (ii) point-to-point
bytes get allocated for the new string. As this function uses
malloc( ) to allocate memory, it is the programmer’s 2. What is subnet?
responsibility to deallocate the memory using free( ).
#include <stdio.h> A generic term for section of a large networks usually
#include <string.h> separated by a bridge or router.
#include <alloc.h>
3. Difference between the communication and transmission.
void main( )
{ Transmission is a physical movement of information and
char *str1, *str2 = "double"; concern issues like bit polarity, synchronisation, clock etc.

str1 = strdup ( str2 ) ; Communication means the meaning full exchange of

printf ( "%s\n", str1 ) ; information between two communication media.
free ( str1 ) ;
} 4. What are the possible ways of data exchange?
------------------------ (i) Simplex (ii) Half-duplex (iii) Full-duplex.
5. What is SAP? When the computers on the network simply listen and
receive the signal, they are referred to as passive because
Series of interface points that allow other computers to they don’t amplify the signal in any way. Example for
communicate with the other layers of network protocol passive topology - linear bus.
14. What is Brouter?
6. What do you meant by "triple X" in Networks?
Hybrid devices that combine the features of both bridges and
The function of PAD (Packet Assembler Disassembler) is routers.
described in a document known as X.3. The standard
protocol has been defined between the terminal and the 15. What is cladding?
PAD, called X.28; another standard protocol exists between
hte PAD and the network, called X.29. Together, these three A layer of a glass surrounding the center fiber of glass inside
recommendations are often called "triple X" a fiber-optic cable.

7. What is frame relay, in which layer it comes? 16. What is point-to-point protocol

Frame relay is a packet switching technology. It will operate A communications protocol used to connect computers to
in the data link layer. remote networking services including Internet service
8.What is terminal emulation, in which layer it comes?
17. How Gateway is different from Routers?
Telnet is also called as terminal emulation. It belongs to
application layer. A gateway operates at the upper levels of the OSI model and
translates information between two completely different
9. What is Beaconing? network architectures or data formats

The process that allows a network to self-repair networks 18. What is attenuation?
problems. The stations on the network notify the other
stations on the ring when they are not receiving the The degeneration of a signal over distance on a network
transmissions. Beaconing is used in Token ring and FDDI cable is called attenuation.
19. What is MAC address?
10. What is redirector?
The address for a device as it is identified at the Media
Redirector is software that intercepts file or prints I/O Access Control (MAC) layer in the network architecture.
requests and translates them into network requests. This MAC address is usually stored in ROM on the network
comes under presentation layer. adapter card and is unique.

20. Difference between bit rate and baud rate.

11. What is NETBIOS and NETBEUI?
Bit rate is the number of bits transmitted during one second
NETBIOS is a programming interface that allows I/O whereas baud rate refers to the number of signal units per
requests to be sent to and received from a remote computer second that are required to represent those bits.
and it hides the networking hardware from applications.
baud rate = bit rate / N
NETBEUI is NetBIOS extended user interface. A transport
protocol designed by microsoft and IBM for the use on small where N is no-of-bits represented by each signal shift.
21. What is Bandwidth?
12. What is RAID?
Every line has an upper limit and a lower limit on the
A method for providing fault tolerance by using multiple frequency of signals it can carry. This limited range is called
hard disk drives. the bandwidth.

13. What is passive topology? 22. What are the types of Transmission media?
Signals are usually transmitted over some transmission 26. What are the different type of networking /
media that are broadly classified in to two categories. internetworking devices?

23. Guided Media: Repeater:

These are those that provide a conduit from one device to Also called a regenerator, it is an electronic device that
another that include twisted-pair, coaxial cable and fiber- operates only at physical layer. It receives the signal in the
optic cable. A signal traveling along any of these media is network before it becomes weak, regenerates the original bit
directed and is contained by the physical limits of the pattern and puts the refreshed copy back in to the link.
medium. Twisted-pair and coaxial cable use metallic that
accept and transport signals in the form of electrical current. Bridges:
Optical fiber is a glass or plastic cable that accepts and
transports signals in the form of light. These operate both in the physical and data link layers of
LANs of same type. They divide a larger network in to
b) Unguided Media: smaller segments. They contain logic that allow them to
keep the traffic for each segment separate and thus are
This is the wireless media that transport electromagnetic repeaters that relay a frame only the side of the segment
waves without using a physical conductor. Signals are containing the intended recipent and control congestion.
broadcast either through air. This is done through radio
communication, satellite communication and cellular Routers:
They relay packets among multiple interconnected networks
24. What is Project 802? (i.e. LANs of different type). They operate in the physical,
data link and network layers. They contain software that
It is a project started by IEEE to set standards to enable enable them to determine which of the several possible paths
intercommunication between equipment from a variety of is the best for a particular transmission.
manufacturers. It is a way for specifying functions of the
physical layer, the data link layer and to some extent the Gateways:
network layer to allow for interconnectivity of major LAN
protocols. They relay packets among networks that have different
protocols (e.g. between a LAN and a WAN). They accept a
It consists of the following: packet formatted for one protocol and convert it to a packet
formatted for another protocol before forwarding it. They
* 802.1 is an internetworking standard for compatibility of operate in all seven layers of the OSI model.
different LANs and MANs across protocols.
* 802.2 Logical link control (LLC) is the upper sublayer 27. What is ICMP?
of the data link layer which is non-architecture-specific, that
is remains the same for all IEEE-defined LANs. ICMP is Internet Control Message Protocol, a network layer
* Media access control (MAC) is the lower sublayer of the protocol of the TCP/IP suite used by hosts and gateways to
data link layer that contains some distinct modules each send notification of datagram problems back to the sender. It
carrying proprietary information specific to the LAN product uses the echo test / reply to test whether a destination is
being used. The modules are Ethernet LAN (802.3), Token reachable and responding. It also handles both control and
ring LAN (802.4), Token bus LAN (802.5). error messages.
* 802.6 is distributed queue dual bus (DQDB) designed to
be used in MANs. 28. What are the data units at different layers of the TCP / IP
25. What is Protocol Data Unit? protocol suite?

The data unit in the LLC level is called the protocol data unit The data unit created at the application layer is called a
(PDU). The PDU contains of four fields a destination service message, at the transport layer the data unit created is called
access point (DSAP), a source service access point (SSAP), either a segment or an user datagram, at the network layer
a control field and an information field. DSAP, SSAP are the data unit created is called the datagram, at the data link
addresses used by the LLC to identify the protocol stacks on layer the datagram is encapsulated in to a frame and finally
the receiving and sending machines that are generating and transmitted as signals along the transmission media.
using the data. The control field specifies whether the PDU
frame is a information frame (I - frame) or a supervisory
frame (S - frame) or a unnumbered frame (U - frame). 29. What is difference between ARP and RARP?
The address resolution protocol (ARP) is used to associate * BUS topology:
the 32 bit IP address with the 48 bit physical address, used
by a host or a router to find the physical address of another In this each computer is directly connected to primary
host on its network by sending a ARP query packet that network cable in a single line.
includes the IP address of the receiver.
The reverse address resolution protocol (RARP) allows a
host to discover its Internet address when it knows only its Inexpensive, easy to install, simple to understand, easy to
physical address. extend.

30. What is the minimum and maximum length of the header STAR topology:
in the TCP segment and IP datagram?
In this all computers are connected using a central hub.
The header should have a minimum length of 20 bytes and
can have a maximum length of 60 bytes. Advantages:

31. What is the range of addresses in the classes of internet Can be inexpensive, easy to install and reconfigure and easy
addresses? to trouble shoot physical problems.

Class A - RING topology:

Class B - In this all computers are connected in loop.

Class C - Advantages:

Class D - All computers have equal access to network media,
installation can be simple, and signal does not degrade as
Class E - much as in other topologies because each computer
regenerates it.
32. What is the difference between TFTP and FTP
application layer protocols? 35. What is mesh network?

The Trivial File Transfer Protocol (TFTP) allows a local host A network in which there are multiple network links
to obtain files from a remote host but does not provide between computers to provide multiple paths for data to
reliability or security. It uses the fundamental packet travel.
delivery services offered by UDP.
36. What is difference between baseband and broadband
The File Transfer Protocol (FTP) is the standard mechanism transmission?
provided by TCP / IP for copying a file from one host to
another. It uses the services offer by TCP and so is reliable In a baseband transmission, the entire bandwidth of the cable
and secure. It establishes two connections (virtual circuits) is consumed by a single signal. In broadband transmission,
between the hosts, one for data transfer and another for signals are sent on multiple frequencies, allowing multiple
control information. signals to be sent simultaneously.

33. What are major types of networks and explain? 37. Explain 5-4-3 rule?

* Server-based network In a Ethernet network, between any two points on the

* Peer-to-peer network network ,there can be no more than five network segments or
four repeaters, and of those five segments only three of
Peer-to-peer network, computers can act as both servers segments can be populated.
sharing resources and as clients using the resources.
38. What MAU?
Server-based networks provide centralized control of
network resources and rely on server computers to provide In token Ring , hub is called Multistation Access
security and network administration Unit(MAU).

34. What are the important topologies for networks? 39. What is the difference between routable and non-
routable protocols?
the details about how to route packets to destinations within
Routable protocols can work with a router and can be used to its own region, but knowing nothing about the internal
build large networks. Non-Routable protocols are designed structure of other regions.
to work on small, local networks and cannot be used with a
router 48. What is silly window syndrome?

40. Why should you care about the OSI Reference Model? It is a problem that can ruin TCP performance. This problem
occurs when data are passed to the sending TCP entity in
It provides a framework for discussing network operations large blocks, but an interactive application on the receiving
and design. side reads 1 byte at a time.

41. What is logical link control? 49. What are Digrams and Trigrams?

One of two sublayers of the data link layer of OSI reference The most common two letter combinations are called as
model, as defined by the IEEE 802 standard. This sublayer is digrams. e.g. th, in, er, re and an. The most common three
responsible for maintaining the link between computers letter combinations are called as trigrams. e.g. the, ing, and,
when they are sending data across the physical network and ion.
50. Expand IDEA.
42. What is virtual channel?
IDEA stands for International Data Encryption Algorithm.
Virtual channel is normally a connection from one source to
one destination, although multicast connections are also 51. What is wide-mouth frog?
permitted. The other name for virtual channel is virtual
circuit. Wide-mouth frog is the simplest known key distribution
center (KDC) authentication protocol.
43. What is virtual path? 52. What is Mail Gateway?

Along any transmission path from a given source to a given It is a system that performs a protocol translation between
destination, a group of virtual circuits can be grouped different electronic mail delivery protocols.
together into what is called path.
53. What is IGP (Interior Gateway Protocol)?
44. What is packet filter?
It is any routing protocol used within an autonomous system.
Packet filter is a standard router equipped with some extra
functionality. The extra functionality allows every incoming 54. What is EGP (Exterior Gateway Protocol)?
or outgoing packet to be inspected. Packets meeting some
criterion are forwarded normally. Those that fail the test are It is the protocol the routers in neighboring autonomous
dropped. systems use to identify the set of networks that can be
reached within or via each autonomous system.
45. What is traffic shaping?
55. What is autonomous system?
One of the main causes of congestion is that traffic is often
busy. If hosts could be made to transmit at a uniform rate, It is a collection of routers under the control of a single
congestion would be less common. Another open loop administrative authority and that uses a common Interior
method to help manage congestion is forcing the packet to Gateway Protocol.
be transmitted at a more predictable rate. This is called
traffic shaping. 56. What is BGP (Border Gateway Protocol)?

46. What is multicast routing? It is a protocol used to advertise the set of networks that can
be reached with in an autonomous system. BGP enables this
Sending a message to a group is called multicasting, and its information to be shared with the autonomous system. This
routing algorithm is called multicast routing. is newer than EGP (Exterior Gateway Protocol).

47. What is region? 57. What is Gateway-to-Gateway protocol?

When hierarchical routing is used, the routers are divided It is a protocol formerly used to exchange routing
into what we will call regions, with each router knowing all information between Internet core routers.
Since the static functions are not any way related to objects,
58. What is NVT (Network Virtual Terminal)? they cannot be declared as virtual.
It is a set of rules defining a very simple virtual terminal ------------------------
interaction. The NVT is used in the start of a Telnet session. 2.
59. What is a Multi-homed Host?
Can user-defined object be declared as static data member of
It is a host that has a multiple network interfaces and that another class?
requires multiple IP addresses is called as a Multi-homed
Host. Ans: Yes. The following code shows how to initialize a user-
defined object.
60. What is Kerberos?
It is an authentication service developed at the
Massachusetts Institute of Technology. Kerberos uses class test
encryption to prevent intruders from discovering passwords {
and gaining unauthorized access to files. int i ;
public :
61. What is OSPF? test ( int ii = 0 )
It is an Internet routing protocol that scales well, can route i = ii ;
traffic along multiple paths, and uses knowledge of an }
Internet's topology to make accurate routing decisions. };

62. What is Proxy ARP? class sample

It is using a router to answer ARP requests. This will be static test s ;
done when the originating host believes that a destination is };
local, when in fact is lies beyond router. test sample::s ( 26 ) ;

63. What is SLIP (Serial Line Interface Protocol)? Here we have initialized the object s by calling the one-
argument constructor. We can use the same convention to
It is a very simple protocol used for transmission of IP initialize the object by calling multiple-argument
datagrams across a serial line. constructor.

64. What is RIP (Routing Information Protocol)? -------------------------------------------------------------------------

It is a simple protocol used to exchange information between 3.
the routers.
What is forward referencing and when should it be used?
65. What is source route?
Ans: Consider the following program:
It is a sequence of IP addresses identifying the route a class test
datagram must follow. A source route may optionally be {
included in an IP datagram header. public :
@@@@@@@@@@@@@@@@@@@@@@@@@@ friend void fun ( sample, test ) ;
@@@@@@@@@@@@@@@@@@@@@@@@@@ };
C++ class sample
@@@@@@@@@@@@@@@@@@@@@@@ {
C++====> public :
1. friend void fun ( sample, test ) ;
Can we declare a static function as virtual?
void fun ( sample s, test t )
Ans: No. The virtual function mechanism is used on the {
specific object that determines which virtual function to call. // code
void main( ) 6.
sample s ; We all know that a const variable needs to be initialized at
test t ; the time of declaration. Then how come the program given
fun ( s, t ) ; below runs properly even when we have not initialized p?
This program would not compile. It gives an error that #include
sample is undeclared identifier in the statement friend void void main( )
fun ( sample, test ) ; of the class test. This is so because the {
class sample is defined below the class test const char *p ;
and we are using it before its definition. To overcome this p = "A const pointer" ;
error we need to give forward reference of the cout << p ;
class sample before the definition of class test. The }
following statement is the forward reference of
class sample. Forward referencing is generally required Ans: The output of the above program is 'A const pointer'.
when we make a class or a function as a friend. This is because in this program p is declared as 'const char*'
------------------------------------------------------------------------- which means that value stored at p will be constant and not p
------------------------ and so the program works properly
The istream_withassign class has been derived from the ------------------------
istream class and overloaded assignment 7.
operator has been added to it. The _withassign classes are
much like their base classes except that How do I refer to a name of class or function that is defined
they include overloaded assignment operators. Using these within a namespace?
operators the objects of the _withassign
classes can be copied. The istream, ostream, and iostream Ans: There are two ways in which we can refer to a name of
classes are made uncopyable by making class or function that is defined within a
their overloaded copy constructor and assignment operators namespace: Using scope resolution operator through the
private. using keyword. This is shown in following example:
------------------------------------------------------------------------- namespace name1
------------------------ {
5. class sample1
How do I write my own zero-argument manipulator that // code
should work same as hex? };
Ans: This is shown in following program. namespace name2
#include class sample2
ostream& myhex ( ostream &o ) // code
{ };
o.setf ( ios::hex) ; using namespace name2 ;
return o ; void main( )
} name1::sample1 s1 ;
sample2 s2 ;
void main( ) }
{ Here, class sample1 is referred using the scope resolution
operator. On the other hand we can
cout << endl << myhex << 2000 ; directly refer to class sample2 because of the statement using
namespace name2 ; the using keyword declares all the names
} in the namespace to be in the current scope. So we can use
------------------------------------------------------------------------- the names without any qualifiers.
------------------------------------------------------------------------- };
------------------------ void main( )
8. rectangle r ( 20, 10 ) ;
circle c;
While overloading a binary operator can we provide default c=r;
values? }
Here, when the statement c = r ; is executed the compiler
Ans: No!. This is because even if we provide the default searches for an overloaded assignment
arguments to the parameters of the operator in the class circle which accepts the object of type
overloaded operator function we would end up using the rectangle. Since there is no such
binary operator incorrectly. This is explained overloaded assignment operator, the conversion operator
in the following example: function that converts the rectangle object
sample operator + ( sample a, sample b = to the circle object is searched in the rectangle class. We
sample (2, 3.5f ) ) have provided such a conversion function
{ in the rectangle class. This conversion operator function
} returns a circle object. By default
conversion operators have the name and return type same as
void main( ) the object type to which it converts to.
{ Here the type of the object is circle and hence the name of
sample s1, s2, s3 ; the operator function as well as the return
s3 = s1 + ; // error type is circle.
} -------------------------------------------------------------------------
------------------------------------------------------------------------- 10.
------------------------ How do I write code that allows to create only one instance
9. of a class?
How do I carry out conversion of one object of user-defined
type to another? Ans: This is shown in following code snippet.

Ans: To perform conversion from one user-defined type to #include

another we need to provide conversion class sample
function. Following program demonstrates how to provide {
such conversion function. static sample *ptr ;
class circle private:
{ sample( )
private : {
int radius ; }
public: public:
circle ( int r = 0 ) static sample* create( )
{ {
radius = r ; if ( ptr == NULL )
} ptr = new sample ;
}; return ptr ;
class rectangle }
{ };
private : sample *sample::ptr = NULL ;
int length, breadth ; void main( )
public : {
rectangle( int l, int b ) sample *a = sample::create( ) ;
{ sample *b = sample::create( ) ;
length = l ; }
breadth = b ; Here, the class sample contains a static data member ptr,
} which is a pointer to the object of same
operator circle( ) class. The constructor is private which avoids us from
{ creating objects outside the class. A static
return circle ( length ) ; member function called create( ) is used to create an object
} of the class. In this function the condition
is checked whether or not ptr is NULL, if it is then an object -------------------------------------------------------------------------
is created dynamically and its address ------------------------
collected in ptr is returned. If ptr is not NULL, then the same 12.
address is returned. Thus, in main( ) on execution of the first
statement one object of sample gets How do I write code to make an object work like a 2-D
created whereas on execution of second statement, b holds array?
the address of the first object. Thus, whatever number of
times you call create( ) function, only one object of sample Ans: Take a look at the following program.
class will be available.
class emp
11. public :
int a[3][3] ;
emp( )
How do I write code to add functions, which would work as {
get and put properties of a class? int c = 1 ;
for ( int i = 0 ; i <= 2 ; i++ )
Ans: This is shown in following code. {
#include for ( int j = 0 ; j <= 2 ; j++ )
class sample a[i][j] = c ;
{ c++ ;
int data ; }
public: }
__declspec ( property ( put = fun1, get = }
fun2 ) )
int x ; int* operator[] ( int i )
void fun1 ( int i ) {
{ return a[i] ;
if ( i < 0 ) }
data = 0 ; };
data = i ; void main( )
} {
int fun2( ) emp e ;
{ cout << e[0][1] ;
return data ; }
} The class emp has an overloaded operator [ ] function. It
}; takes one argument an integer representing an array index
and returns an int pointer. The statement cout << e[0][1] ;
void main( ) would getconverted into a call to the overloaded [ ] function
{ as e.operator[ ] ( 0 ). 0 would get collected in i. The function
sample a ; would return a[i] that represents the base address of the
a.x = -99 ; zeroeth row. Next the statement would get expanded as base
cout << a.x ; address of zeroeth row[1] that can be further expanded as
} *( base address + 1 ). This gives us a value in zeroth row and
Here, the function fun1( ) of class sample is used to set the first column.
given integer value into data, whereas
fun2( ) returns the current value of data. To set these 13.
functions as properties of a class we have What are formatting flags in ios class?
given the statement as shown below:
__declspec ( property ( put = fun1, get = Ans: The ios class contains formatting flags that help users
fun2 )) int x ; to format the stream data. Formatting
As a result, the statement a.x = -99 ; would cause fun1( ) to flags are a set of enum definitions. There are two types of
get called to set the value in data. On the formatting flags:
other hand, the last statement would cause fun2( ) to get On/Off flags
called to return the value of data. Flags that work in-group
The On/Off flags are turned on using the setf( ) function and passed to the next input and may pose
are turned off using the unsetf( ) function. problem.
To set the On/Off flags, the one argument setf( ) function is
used. The flags working in groups are set To get rid of such extra characters the cin::ignore( ) function
through the two-argument setf( ) function. For example, to is used. This is equivalent to fflush ( stdin ) used in C
left justify a string we can set the flag as, language. This function ignores the first n characters (if
cout.setf ( ios::left ) ; present) in the input stream, stops if delimiter d is
cout << "KICIT Nagpur" ; encountered.
To remove the left justification for subsequent output we can
say, -------------------------------------------------------------------------
cout.unsetf ( ios::left ) ; ------------------------
The flags that can be set/unset include skipws, showbase, 17.
showpoint, uppercase, showpos, unitbuf
and stdio. The flags that work in a group can have only one Write a program that implements a date class containing day,
of these flags set at a time. month and year as data members.
Implement assignment operator and copy constructor in this
------------------------------------------------------------------------- class.
Ans: This is shown in following program:
14. #include
What is the purpose of ios::basefield in the following
statement? class date
cout.setf ( ios::hex, ios::basefield ) ; private :
Ans: This is an example of formatting flags that work in a int day ;
group. There is a flag for each numbering int month ;
system (base) like decimal, octal and hexadecimal. int year ;
Collectively, these flags are referred to as public :
basefield and are specified by ios::basefield flag. We can date ( int d = 0, int m = 0, int y = 0 )
have only one of these flags on at a time. {
If we set the hex flag as setf ( ios::hex ) then we will set the day = d ;
hex bit but we won't clear the dec bit month = m ;
resulting in undefined behavior. The solution is to call setf( ) year = y ;
as setf ( ios::hex, ios::basefield ). This call }
first clears all the bits and then sets the hex bit.
------------------------------------------------------------------------- // copy constructor
------------------------ date ( date &d )
15. {
Can we get the value of ios format flags? day = ;
month = d.month ;
Ans: Yes! The ios::flags( ) member function gives the value year = d.year ;
format flags. This function takes no }
arguments and returns a long ( typedefed to fmtflags) that
contains the current format flags. // an overloaded assignment operator
date operator = ( date d )
------------------------------------------------------------------------- {
------------------------ day = ;
16. month = d.month ;
Is there any function that can skip certain number of year = d.year ;
characters present in the input stream? return d ;
Ans: Yes! This can be done using cin::ignore( ) function. void display( )
The prototype of this function is as shown {
below: cout << day << "/" << month << "/" <<
istream& ignore ( int n = 1, int d =EOF ) ; year ;
Sometimes it happens that some extra characters are left in }
the input stream while taking the input };
such as, the '\n' (Enter) character. This extra character is then
void main( ) -------------------------------------------------------------------------
{ ------------------------
date d1 ( 25, 9, 1979 ) ; 22.
date d2 = d1 ; What are put and get pointers?
date d3 ;
d3 = d2 ; Ans: These are the long integers associated with the streams.
d3.display( ) ; The value present in the put pointer
} specifies the byte number in the file from where next write
would take place in the file. The get
18. pointer specifies the byte number in the file from where the
When should I use unitbuf flag? next reading should take place.
Ans: The unit buffering (unitbuf) flag should be turned on ------------------------
when we want to ensure that each 23.
character is output as soon as it is inserted into an output What do the nocreate and noreplace flag ensure when they
stream. The same can be done using are used for opening a file?
unbuffered output but unit buffering provides a better
performance than the unbuffered output. Ans: nocreate and noreplace are file-opening modes. A bit in
------------------------------------------------------------------------- the ios class defines these modes. The flag
------------------------ nocreate ensures that the file must exist before opening it.
19. On the other hand the flag noreplace
ensures that while opening a file for output it does not get
What are manipulators? overwritten with new one unless ate or
Ans: Manipulators are the instructions to the output stream app is set. When the app flag is set then whatever we write
to modify the output in various ways. The gets appended to the existing file. When
manipulators provide a clean and easy way for formatted ate flag is set we can start reading or writing at the end of
output in comparison to the formatting existing file.
flags of the ios class. When manipulators are used, the -------------------------------------------------------------------------
formatting instructions are inserted ------------------------
directly into the stream. Manipulators are of two types, those 24.
that take an argument and those that don't. What is the limitation of cin while taking input for character
------------------------------------------------------------------------- array?
20. Ans: To understand this consider following statements,
char str[5] ;
What is the difference between the manipulator and setf( ) cin >> str ;
function? While entering the value for str if we enter more than 5
characters then there is no provision in cin
Ans: The difference between the manipulator and setf( ) to check the array bounds. If the array overflows, it may be
function are as follows: dangerous. This can be avoided by using
The setf( ) function is used to set the flags of the ios but get( ) function. For example, consider following statement,
manipulators directly insert the cin.get ( str, 5 ) ;
formatting instructions into the stream. We can create user-
defined manipulators but setf( ) function On executing this statement if we enter more than 5
uses data members of ios class only. The flags put on characters, then get( ) takes only first five
through the setf( ) function can be put characters and ignores rest of the characters. Some more
off through unsetf( ) function. Such flexibility is not variations of get( ) are available, such as
available with manipulators. shown below:
------------------------ get ( ch ) - Extracts one character only
How do I get the current position of the file pointer? get ( str, n ) - Extracts up to n characters
Ans: We can get the current position of the file pointer by into str
using the tellp( ) member function of ostream class or tellg( )
member function of istream class. These functions return (in get ( str, DELIM ) - Extracts characters
bytes) positions of put pointer and get into array str until specified delimiter (such as
pointer respectively. '\n'). Leaves delimiting character in stream.
get ( str, n, DELIM ) - Extracts characters Ans: When we want to retrieve the streams of bytes from
into array str until n characters or DELIM character, leaving memory we can use istrestream. The following
delimiting character in stream. example shows the use of istrstream class.
------------------------------------------------------------------------- #include
25. void main( )
What is the purpose of istream class? int age ;
float salary ;
Ans: The istream class performs activities specific to input. char name[50] ;
It is derived from the ios class. The most commonly used char str[] = "22 12004.50 K. Vishwanatth"
member function of this class is the overloaded >> operator ;
which can extract values of all basic types. We can extract
even a string using this operator. istrstream s ( str ) ;
------------------------------------------------------------------------- s >> age >> salary >> name ;
26. cout << age << endl << salary << endl <<
name ;
Would the following code work? cout << endl << s.rdbuf( ) ;
#include }
void main( ) Here, s is the object of the class istrstream. When we are
{ creating the object s, the constructor of
ostream o ; istrstream gets called that receives a pointer to the zero
o << "Dream. Then make it happen!" ; terminated character array str. The
} statement s >> age >> salary >> name ; extracts the age,
Ans: No! This is because we cannot create an object of the salary and the name from the istrstream
ostream class since its constructor and copy constructor are object s. However, while extracting the name, only the first
declared private. word of name gets extracted. The balance
is extracted using rdbuf( ).
Can we use this pointer inside static member function? -------------------------------------------------------------------------
Ans: No! The this pointer cannot be used inside a static 30.
member function. This is because a static When the constructor of a base class calls a virtual function,
member function is never called through an object. why doesn't the override function of the
------------------------------------------------------------------------- derived class gets called?
28. Ans: While building an object of a derived class first the
What is strstream? constructor of the base class and then the
constructor of the derived class gets called. The object is said
Ans: strstream is a type of input/output stream that works an immature object at the stage when the
with the memory. It allows using section constructor of base class is called. This object will be called
of the memory as a stream object. These streams provide the a matured object after the execution of the
classes that can be used for storing the constructor of the derived class. Thus, if we call a virtual
stream of bytes into memory. For example, we can store function when an object is still immature,
integers, floats and strings as a stream of obviously, the virtual function of the base class would get
bytes. There are several classes that implement this in- called. This is illustrated in the following
memory formatting. The class ostrstream derived from example.
ostream is used when output is to be sent to memory, the #include
class istrstream derived from istream is used when input is
taken from memory and strstream class derived from class base
iostream is used for {
memory objects that do both input and output. protected :
int i ;
------------------------------------------------------------------------- public :
------------------------ base ( int ii = 0 )
29. {
i = ii ;
show( ) ; void main( )
} {
int j = 10 ;
virtual void show( ) sample s ( j ) ;
{ ) ;
cout << "base's show( )" << endl ; }
} Here, i refers to a variable j allocated on the stack. A point to
}; note here is that we cannot bind a
reference to an object passed to the constructor as a value. If
class derived : public base we do so, then the reference i would refer
{ to the function parameter (i.e. parameter ii in the
private : constructor), which would disappear as
int j ; soon as the function returns, thereby creating a situation of
public : dangling reference.
derived ( int ii, int jj = 0 ) : base ( ii ) -------------------------------------------------------------------------
{ ------------------------
j = jj ; 32.
show( ) ; Why does the following code fail?
void show( ) #include
cout << "derived's show( )" << endl ; class sample
} {
}; private :
char *str ;
void main( ) public :
{ sample ( char *s )
derived dobj ( 20, 5 ) ; {
} strcpy ( str, s ) ;
The output of this program would be: }
base's show( )
derived's show( ) ~sample( )
31. delete str ;
Can I have a reference as a data member of a class? If yes, }
then how do I initialise it? };

Ans: Yes, we can have a reference as a data member of a void main( )

class. A reference as a data member of a {
class is initialised in the initialisation list of the constructor. sample s1 ( "abc" ) ;
This is shown in following program. }
#include Ans: Here, through the destructor we are trying to deal locate
memory, which has been allocated
class sample statically. To remove an exception, add following statement
{ to the constructor.
private : sample ( char *s )
int& i ; {
public : str = new char[strlen(s) + 1] ;
sample ( int& ii ) : i ( ii ) strcpy ( str, s ) ;
{ }
} Here, first we have allocated memory of required size, which
then would get deal located through the
void show( ) destructor.
{ -------------------------------------------------------------------------
cout << i << endl ; ------------------------
} 33.
}; assert( ) macro...
We can use a macro called assert( ) to test for conditions that As against this, if we allocate memory by calling malloc( )
should not occur in a code. This macro the constructor would not get called. Hence p holds a
expands to an if statement. If test evaluates to 0, assert prints garbage address. Now if the memory is deal located using
an error message and calls abort to abort delete, the destructor would get called
the program. where we have tried to release the memory pointed to by p.
#include Since p contains garbage this may result
#include in a runtime error.
void main( ) ------------------------
int i ;

cout << "\nEnter an integer: " ; 35.

cin >> i ; Can we distribute function templates and class templates in
object libraries?
assert ( i >= 0 ) ;
cout << i << endl ; Ans: No! We can compile a function template or a class
} template into object code (.obj file). The code that contains a
call to the function template or the code that creates an
34. object from a class template can get compiled. This is
Why it is unsafe to deal locate the memory using free( ) if it because the compiler merely checks whether the call
has been allocated using new? matches the declaration (in case of function template) and
Ans: This can be explained with the following example: whether the object definition matches class declaration (in
#include case of class template). Since the function template and the
class template definitions are not found, the compiler leaves
class sample it to the linker to restore this. However, during linking, linker
{ doesn't find the matching definitions for the function call or
int *p ; a matching definition for object creation. In short the
public : expanded versions of templates are not found in
sample( ) the object library. Hence the linker reports error.
{ -------------------------------------------------------------------------
p = new int ; ------------------------
} 36.
What is the difference between an inspector and a mutator ?
~sample( )
{ Ans: An inspector is a member function that returns
delete p ; information about an object's state (information stored in
} object's data members) without changing the object's state. A
}; mutator is a member function that changes the state of an
object. In the class Stack given below we have defined a
void main( ) mutator and an inspector.
sample *s1 = new sample ; class Stack
free ( s1 ) ; {
public :
sample *s2 = ( sample * ) malloc ( sizeof ( int pop( ) ;
sample int getcount( ) ;
)); }
delete s2 ;
} In the above example, the function pop( ) removes top
The new operator allocates memory and calls the element of stack thereby changing the state of an object. So,
constructor. In the constructor we have allocated the function pop( ) is a mutator. The function getcount( ) is
memory on heap, which is pointed to by p. If we release the an inspector because it simply counts the number of
object using the free( ) function the object would die but the elements in the stack without changing the stack.
memory allocated in the constructor would leak. This is
because free( ) being a C library function does not call the 37.
destructor where we have deal located the memory.
The C++ language provides a single global namespace. This cout << sizeof ( user ) ;
can cause problems with global name clashes. For instance, user u1 ;
consider these two C++ header files: cout << endl << sizeof ( u1 ) ;
u1.displaydata( ) ;
// file1.h }
float f ( float, int ) ;
class sample { ... } ; Ans: The output of this program would be,

// file2.h 9 or 7
class sample { ... } ; 9 or 7
With these definitions, it is impossible to use both header Garbage
files in a single program; the sample classes will clash.A Garbage
namespace is a declarative region that attaches an additional
identifier to any names declared inside it. The additional Since the user class contains three elements, int, float and
identifier thus avoids the possibility that a name will conflict char its size would be 9 bytes (int-4, float-4, char-1) under
with names declared elsewhere in the program. It is possible Windows and 7 bytes (int-2, float-4, char-1) under DOS.
to use the same name in separate namespaces without Second output is again the same because u1 is an object of
conflict even if the names appear in the same translation the class user. Finally three garbage values are printed out
unit. As long as they appear in separate namespaces, each because i, f and c are not initialized anywhere in the
name will be unique because of the addition of the program.
namespace identifier. For example:
Note that if you run this program you may not get the answer
// file1.h shown here. This is because packing is done for an object in
namespace file1 memory to increase the access efficiency. For example,
{ under DOS, the object would be aligned on a 2-byte
float f ( float, int ) ; boundary. As a result, the size of the object would be
class sample { ... } ; reported as 6 bytes. Unlike this, Windows being a 32-bit OS
} the object would be aligned on a 4-byte boundary. Hence the
size of the object would be reported as 12 bytes. To force the
// file2.h alignment on a 1-byte boundary, write the following
namespace file2 statement before the class declaration.
{ #pragma pack ( 1 )
class sample { ... } ; -------------------------------------------------------------------------
} ------------------------
Now the class names will not clash because they become
file1::sample and file2::sample, respectively. Write a program that will convert an integer pointer to an
------------------------------------------------------------------------- integer and vice-versa.
38. Ans: The following program demonstrates this.
What would be the output of the following program? #include
void main( )
#include {
class user int i = 65000 ;
int i ; int *iptr = reinterpret_cast ( i ) ;
float f ; cout << endl << iptr ;
char c ;
public : iptr++ ;
void displaydata( ) cout << endl << iptr ;
cout << endl << i << endl << f << endl << c ; i = reinterpret_cast ( iptr ) ;
} cout << endl << i ;
i++ ;
void main( ) cout << endl << i ;
} fun ( s, t ) ;
40. On compiling this program it gives error on the following
What is a const_cast? statement of test class. It gives an error that sample is
undeclared identifier. friend void fun ( sample, test ) ;
Ans. The const_cast is used to convert a const to a non- This is so because the class sample is defined below the class
const. This is shown in the following test and we are using it before its definition. To overcome
program: this error we need to give forward reference of the class
#include sample before the definition of class test. The following
void main( ) statement is the forward reference of class sample.
{ class sample ;
const int a = 0 ; -------------------------------------------------------------------------
int *ptr = ( int * ) &a ; //one way ------------------------
ptr = const_cast_ ( &a ) ; //better way 42.
} How would you give an alternate name to a namespace?
Here, the address of the const variable a is assigned to the
pointer to a non-const variable. The const_cast is also used Ans: An alternate name given to namespace is called a
when we want to change the data members of a class inside namespace-alias. namespace-alias is generally used to save
the const member functions. The following code snippet the typing effort when the names of namespaces are very
shows this: long or complex. The following syntax is used to give an
class sample alias to a namespace.
{ namespace myname =
private: my_old_very_long_name ;
int data;
public: -------------------------------------------------------------------------
void func( ) const ------------------------
{ 43.
(const_cast (this))->data = 70 ; Using a smart pointer can we iterate through a container?
}; Ans: Yes. A container is a collection of elements or objects.
------------------------------------------------------------------------- It helps to properly organize and store the data. Stacks,
------------------------ linked lists, arrays are examples of containers. Following
41. program shows how to iterate through a container using a
What is forward referencing and when should it be used? smart pointer.
Ans: Forward referencing is generally required when we #include
make a class or a function as a friend.
Consider following program: class smartpointer
class test {
{ private :
public: int *p ; // ordinary pointer
friend void fun ( sample, test ) ; public :
}; smartpointer ( int n )
class sample p = new int [ n ] ;
{ int *t = p ;
public: for ( int i = 0 ; i <= 9 ; i++ )
friend void fun ( sample, test ) ; *t++ = i * i ;
}; }

void fun ( sample s, test t ) int* operator ++ ( int )

{ {
// code return p++ ;
} }

void main( ) int operator * ( )

{ {
sample s ; return *p ;
test t ; }
}; << endl << "Age : " << age
<< endl << "Salary :" << salary << endl ;
void main( ) }
{ };
smartpointer sp ( 10 ) ;
void main( )
for ( int i = 0 ; i <= 9 ; i++ ) {
cout << *sp++ << endl ; employee e [ 5 ] ;
Here, sp is a smart pointer. When we say *sp, the operator * for ( int i = 0 ; i <= 4 ; i++ )
( ) function gets called. It returns the integer being pointed to {
by p. When we say sp++ the operator ++ ( ) function gets e [ i ].getdata( ) ;
called. It increments p to point to e [ i ].store( ) ;
the next element in the array and then returns the address of }
this new location.
for ( i = 0 ; i <= 4 ; i++ )
44. {
Can objects read and write themselves? e [ i ].retrieve ( i ) ;
e [ i ].show( ) ;
Ans: Yes! This can be explained with the help of following }
example: }
Here, employee is the class whose objects can write and read
#include themselves. The getdata( ) function has been used to get the
#include data of employee and store it in the data members name, age
and salary. The store( ) function is used to write an object to
class employee the file. In this function a file has been opened in append
{ mode and each time data of current object has been stored
private : after the last record (if any) in the file.Function retrieve( ) is
char name [ 20 ] ; used to get the data of a particular employee from the file.
int age ; This retrieved data has been stored in the data members
float salary ; name, age and salary. Here this has been used to store data
public : since it contains the address of the current object. The
void getdata( ) function show( ) has been used to display the data of
{ employee.
cout << "Enter name, age and salary of employee : " ; -------------------------------------------------------------------------
cin >> name >> age >> salary ; ------------------------
} 45.
Why is it necessary to use a reference in the argument to the
void store( ) copy constructor?
ofstream file ; Ans : If we pass the copy constructor the argument by value, ( "EMPLOYEE.DAT", ios::app | ios::binary ) ; its copy would get constructed using the copy constructor.
file.write ( ( char * ) this, sizeof ( *this ) ) ; This means the copy constructor would call itself to make
file.close( ) ; this copy. This process would go on and on until the
} compiler runs out of memory. This can be explained with the
help of following example:
void retrieve ( int n ) class sample
{ {
ifstream file ; int i ; ( "EMPLOYEE.DAT", ios::binary ) ; public :
file.seekg ( n * sizeof ( employee ) ) ; sample ( sample p ) ( ( char * ) this, sizeof ( *this ) ) ; {
file.close( ) ; i = p.i ;
} }
void show( )
{ void main( )
cout << "Name : " << name {
sample s ; ) ;
sample s1 ( s ) ; cout << d.i ;
} }
While executing the statement sample s1 ( s ), the copy -------------------------------------------------------------------------
constructor would get called. As the copy construct here ------------------------
accepts a value, the value of s would be passed which would 47.
get collected in p. We can think of this statement as sample p
= s. Here p is getting created and initialized. Means again the Can we use this pointer in a class specific, operator-
copy constructor would get called. This would result into overloading function for new operator?
recursive calls. Hence we must use a reference as an
argument in a copy constructor. Ans: No! The this pointer is never passed to the overloaded
46. operator new() member function because this function gets
Virtual Multiple Inheritance: called before the object is created. Hence there is no question
A class b is defined having member variable i. Suppose two of the this pointer getting passed to operator new( ).
classes d1 and d2 are derived from class b and a class -------------------------------------------------------------------------
multiple is derived from both d1 and d2. If variable i is ------------------------
accessed from a member function of multiple then it gives 48.
error as 'member is ambiguous'. To avoid this error derive Can we allocate memory dynamically for a reference?
classes d1 and d2 with modifier virtual as shown in the
following program. Ans: No! It is not possible to allocate memory dynamically
#include for a reference. This is because, when we create a reference,
class b it gets tied with some variable of its type. Now, if we try to
{ allocate memory dynamically for a reference, it is not
public : possible to mention that to which variable the reference
int i ; would get tied.
public :
fun( ) 49.
{ When should I overload new operator on a global basis or a
i=0; class basis?
}; Ans: We overload operator new in our program, when we
class d1 : virtual public b want to initialize a data item or a class object at the same
{ place where it has been allocated memory. The following
public : example shows how to overload new operator on global
fun( ) basis.
i=1; #include
} #include
class d2 : virtual public b void * operator new ( size_t s )
{ {
public : void *q = malloc ( s ) ;
fun( ) return q ;
{ }
} void main( )
}; {
class multiple : public d1, public d2 int *p = new int ;
{ *p = 25 ;
public : cout << *p ;
fun( ) }
{ When the operator new is overloaded on global basis it
i = 10 ; becomes impossible to initialize the data members of a class
} as different classes may have different types of data
}; members. The following example shows how to
void main( ) overload new operator on class-by-class basis.
{ #include
multiple d ; #include
sample s ( π ) ;
class sample cout << ** ( s.*ptr ) ;
{ }
int i ; Here, ptr is the pointer to data member p of class sample,
which in turn is a pointer pointing to an int.
public : -------------------------------------------------------------------------
void* operator new ( size_t s, int ii ) ------------------------
{ 51.
sample *q = ( sample * ) malloc ( s ) ; How do I write a code to catch multiple types of exceptions
q -> i = ii ; in one single catch block?
return q ;
} Ans: The following program demonstrates the use of a single
}; catch block to catch multiple exceptions.

class sample1 #include

float f ; class test
public : {
void* operator new ( size_t s, float ff ) };
sample1 *q = ( sample1 * ) malloc ( s ) ; class sample
q -> f = ff ; {
return q ; public :
} void fun1( )
}; {
throw 99 ;
void main( ) }
{ void fun2( )
sample *s = new ( 7 ) sample ; {
sample1 *s1 = new ( 5.6f ) sample1 ; throw 3.14f ;
} }
Overloading the operator new on class-by-class basis makes void fun3( )
it possible to allocate memory for an object and initialize its {
data members at the same place. throw "error" ;
------------------------------------------------------------------------- }
------------------------ void fun4( )
50. {
How would you define a pointer to a data member of the throw test( ) ;
type pointer to pointer? }
Ans: The following program demonstrates this...
#include void main( )
class sample try
{ {
public : sample s ;
sample ( int **pp ) s.fun4( ) ;
{ s.fun1( ) ;
p = pp ; s.fun2( ) ;
} s.fun3( ) ;
int **p ; }
}; catch ( ... )
int **sample::*ptr = &sample::p ; {
cout << "strange" ;
void main( ) }
{ }
int i = 9 ; Here, different types of exceptions are thrown by the
int *pi = &i ; member functions of the class sample. While catching the
exception instead of four different catch blocks we can as
well define one single catch block. Note the syntax for Here, the first sample indicates the return type of the
defining the catch block, where we have used three dots (…) function and the next sample is used for the scope of
in the formal parameter list. This indicates that any thrown function.
exception should get caught in the same catch block. When -------------------------------------------------------------------------
the exception is thrown from the fun4( ) control reaches the ------------------------
catch block, ignoring the rest of the calls. 54.
How name mangling can be prevented?

52. Ans: To avoid name mangling the function should be

Can we return an error value from the constructor of a declared with an extern "C" attribute. Functions declared as
class? extern "C" are treated as C-style functions. Hence the
compiler does not mangle them. The following code snippet
Ans: No. We cannot return any error value from the shows how to declare such a function.
constructor, as the constructor doesn't have any return type. #include
However, by throwing an exception we can pass value to
catch block. This is shown in the following example: extern "C" void display( )
#include {
cout << "See the effect of C in C++ " ;
class sample }
public : void main( )
sample ( int i ) {
{ display( ) ;
if ( i == 0 ) }
throw "error" ; -------------------------------------------------------------------------
} ------------------------
}; 55.
Can we allocate memory dynamically for a reference?
void main( )
{ Ans: No, it is not possible to allocate memory dynamically
try for a reference. A reference is initialized at the time of
{ creation. Trying to allocate memory dynamically for a
sample s ( 0 ) ; reference creates a problem in initializing it. Thus, the
} compiler does not allow us to dynamically allocate the
catch ( char * str ) memory for references.
{ -------------------------------------------------------------------------
cout << str ; ------------------------
} 56.
} What is RTTI?
In this program, the statement throw "error" ; would throw
an exception when an object s of the class sample would get Ans: RTTI stands for 'Run Time Type Information'. We use
created. The catch block would collect the string error. virtual function mechanism where we can call derived class's
------------------------------------------------------------------------- member functions using base class's pointer. However, many
------------------------ times we wish to know the exact type of the object. We can
53. know the type of the object using RTTI. A function that
returns the type of the object is known as RTTI functions.
How do I define the member function of a template class, C++ supports two ways to obtain information about the
which has to be defined outside the template class. The object's class at run time, they are typeid( ) operator and
function receives an object of its own class as a parameter dynamic_cast operator.
and returns the value of the same type.
Ans: The following example shows how we can define such
a function. What is Data Conversion?
sample sample::fun ( sample s ) Ans: Assignments between types whether they are basic or
{ user-defined, are handled by the compiler. If the variables
// code are of different basic types compiler calls a special routine to
} convert the value. But if we want to convert between user-
defined data type and basic types we have to write cout << endl << typeid ( b1 ).name( ) ;
conversion routine ourselves. A conversion routine to
convert user-defined data type string to integer is shown Der1 d1 ;
below: b1 = &d1 ;
class string cout << endl << typeid ( *b1 ).name( ) ;
private : cout << endl << typeid ( 12 ).name( ) << endl << typeid
char str[20] ; ( 12.5 ).name( ) ;
public : }
string( )
{ The output of this program will be
string ( char *s ) Base*
{ Der1
strcpy ( str, s ) ; int
} double
operator int( )
{ RTTI operators must be used for polymorphic class (class
return 123 ; // Write logic to convert string to integer having virtual function) only. For non-polymorphic class
} static type information is returned.
}; -------------------------------------------------------------------------
main( ) ------------------------
{ 59.
string s2 = "123" ; How to use RTTI with class templates?
int i1 = int ( s2 ) ;
cout << endl << i1 ; Ans: Templates can generate different classes. We may wish
} to get the type of class, which we are working in. The
------------------------------------------------------------------------- following program shows how to use RTTI operator
------------------------ typeid( ) with class template.


58. template
How to obtain type information using typeid( ) operator? class base
Ans: typeid( ) operator takes an object, a reference or a public :
pointer and returns its type. Following program shows how base( )
to use the typeid( ) operator. {
cout << typeid ( *this ).name( ) << "Constructor" << endl
#include ;
#include }

class Base T add ( T a, T b )

{ {
public : return a + b ;
virtual void show( ) }
} ~base( )
}; {
cout << typeid ( *this ).name( ) << "Destructor" << endl ;
class Der1 : public Base }
{ };
void main( )
void main( ) {
{ base b1 ;
Base *b1 ; cout << b1.add ( 10, 20 ) << endl ;
base b2 ; ------------------------
cout << b2.add ( 5.5, 10.5 ) << endl ; 63.
Function template overloading
We can use following C++ operators for One can declare several function templates with the same
typecasting.static_cast is used for castless conversions, name and even declare a combination of function templates
narrowing conversions, conversion from void* and implicit and ordinary functions with the same name. When an
type conversions. const_cast is used to convert a const to a overloaded function is called, overload resolution is
non-const. reinterpret_cast is used to assign one kind of necessary to find the right function or template function to
pointer to another. invoke.
------------------------------------------------------------------------- For example:
------------------------ template < class T > T sqrt ( T ) ;
61. template < class T > complex < T > sqrt ( complex < T
What will be the output of the following program? > ) ;double sqrt (
double ) ;
#include void f ( complex < double > z )
class A {
{ sqrt ( 2 ) ; // sqrt < int > ( int )
public : sqrt ( 2.0 ) ; // sqrt ( double )
A( ) sqrt ( z ) ; // sqrt < complex < double > ( complex <
{ double > )
cout << "Reached in Constructor\n" ; }
} In the same way that a template function is a generalization
}; of the notion of a function, the rules for resolution in the
presence of function templates are generalizations of the
void main( ) function overload resolution rules. Basically, for each
{ template we find the specialization that is best for the set of
A a( ) ; function arguments. Then we apply the usual function
Ab; overload resolution rules to these specializations and all
} ordinary functions.
Output : Reached in Constructor
Constructor gets called only once when the object b is Exception Handling in C++
created. When the statement A a( ) ; gets executed
constructor does not get called. This is because compiler In C++ we can handle run-time errors generated by c++
takes this statement as a prototype declaration of function classes by using three new keywords: throw, catch, and try.
a( ) that returns an object of class A. However, if we pass We also have to create an exception class. If during the
arguments like course of execution of a member function of
A a ( 10 ) ; this class a run-time error occurs, then this member function
Compiler would search for one argument constructor and if informs the application that an error has occurred. This
not found would flash an error. process of informing is called 'throwing' an exception. The
------------------------------------------------------------------------- following code shows how to deal with exception handling.
------------------------ class sample
62. {
public :
What is a container?
class errorclass
Ans: A container is an object that holds other objects. {
Various collection classes like List, Hash Table, };
AbstractArray, etc. are the examples of containers. We can void fun( )
use the classes to hold objects of any derived classes. The {
containers provide various methods using which we can get if ( some error occurs )
the number of objects stored in the container and iterate throw errorclass( ) // throws exception
through the objects stored in it. }
void main( )
{ 2. If we want that only one sub-object should exist we must
try use the concept of virtual base class. The single object of this
{ will represent every base class of given name that is
sample s ; specified to be virtual ) ; class. After making d1 and d2 as virtual base class if we
} create an object of der only one sub-object would exist and
catch ( sample::errorclass ) so accessing data would no longer give us errors.
{ -------------------------------------------------------------------------
// do something about the error ------------------------
} 66.
} How to declare a pointer to a member function?
------------------------ Ans: Suppose, I wish to declare a pointer to a member
65. function that receives an int and returns an int. I will have to
Consider the following code: declare it as int (A::* ) ( int ). Following is an example.

#include #include
class base
{ class A
public : {
int data ; public :
int fun ( int f )
class d1 : public base {
{ cout << "in fun\n" ;
return f * f ;
class d2 : public base }
{ };
typedef int ( A:: *pfun ) ( int ) ;
class der : public d1, public d2
{ void main( )
public : {
void showdata( ) pfun p = A::fun ;
{ Aa;
cout << data ; int s = ( a.*p ) ( 6 ) ;
} cout << s ;
}; }

void main( ) 67.

{ What is the disadvantage of a template function?
der d ;
d.showdata( ) ; Ans: A template function cannot be distributed in the obj
} form. This is because, with which parameters the template
function is going to be called is decided at the run time only.
If you run this program it is bound to give you errors. This is Therefore an obj form of a template function cannot be
because of the rules of inheritance: made by merely compiling it.
1. Each base class not specified virtual will have its own ------------------------
sub-object representing it. In the above program, if we create 68.
object of d1 it will have a sub-object of class base containing
a data member data. If we create an object of class der it will How to declare a pointer to the data members of a class?
have sub-objects of classes d1 and d2 and both the sub-
objects will refer to a separate copy of data. Hence, to access Ans: Following program shows how to declare a pointer to
data from class der we will have to mention the class name. non-function members of a class.
For example, d1::data or d2::data.
for ( i = 0 ; i < 3 ; i++ )
class A {
{ for ( j = 0 ; j < 3 ; j++ )
public : cout << p[i][j] ;
cout << "\n" ;
int a ; }
void print( ) }
cout << a ; 70.
} When should we use the :: ( scope resolution ) operator to
}; invoke the virtual functions?

void main( ) Ans: Generally, :: operator is used to call a virtual function

{ from constructor or destructor. This is because, if we call a
int A::*pa = &A::a ; virtual function from base class constructor or destructor the
virtual function of the base class would get called even if the
A obj ; object being constructed or destroyed would be the object of
obj.*pa = 20 ; the derived class. Thus, whenever we want to bypass the
obj.print( ) ; dynamic binding mechanism we must use the :: operator to
} call a virtual function.
Here, we have initialised the data member a using the pointer ------------------------
pa. 71.
------------------------------------------------------------------------- How do I use operators .* and ->* in a program?
Ans: The following code snippet demonstrates the use of .*
and ->* operators.
How to allocate memory for a multidimensional array #include
class sample
Ans: Many times we need to allocate memory for a {
multidimensional array dynamically. Because of complexity public :
of pointers many find this difficult. Following program int i ;
allocates memory for a 3 x 3 array dynamically, copies void fun( )
contents of a 3 x 3 array in it and prints the contents using {
the pointer. cout << "fun" << endl ;
#include };
void ( sample::*pf )( ) = &sample::fun ;
int a[ ][3] = { int sample::*pdm = &sample::i ;
1, 2, 3,
4, 5, 6, void main( )
7, 8, 9 {
}; sample s ;
sample *p = new sample ;
void main( )
int **p ; ( s .* pf )( ) ;
p = new int *[3] ; ( p ->* pf )( ) ;
for ( int i = 0 ; i < 3 ; i++ )
p[i] = new int[3] ;
s .* pdm = 1 ;
for ( i = 0 ; i < 3 ; i++ ) p ->* pdm = 2 ;
for ( int j = 0 ; j < 3 ; j++ )
p[i][j] = a[i][j] ; cout << s .* pdm << endl ;
cout << p ->* pdm << endl ; for ( int i = 0 ; i < 4 ; i++ )
} cout << r [i] << endl ;
In the above program pf is a pointer to a function fun( ) of -------------------------------------------------------------------------
class sample, and pdm is a pointer to a data member i of the ------------------------
same class sample. The object s of the class sample is 74.
created statically. Next, p is a pointer to an object created When friend function becomes indispensable...
dynamically. The using the operator .* and ->* the member
functions are called and also the public data member is Ans: Consider the following program.
------------------------------------------------------------------------- #include
------------------------ class distance
72. {
What happens when we add an int value to a user defined private :
type of object? int feet ;
public :
Ans: Whenever an int value is added to an object of user distance( )
defined type, the object would search for an overloaded {
operator int( ). This operator must be defined in such a way feet = 0 ;
that it always returns an int value. However, we need not }
specify the return type as on doing so the compiler flashes an distance ( int f )
error. {
feet = f ;
#include }
class sample distance operator + ( distance x )
{ {
int i ; int f = feet + x.feet ;
return distance ( f ) ;
public : }
sample ( ) };
{ void main( )
i = 10 ; {
} distance d1 ( 20 ), d2, d3 ;
operator int( ) d2 = d1 + 10 ;
{ d3 = 10 + d2 ;
return this -> i ; }
}; If you run this program it is bound to give errors. The error
void main( ) lies in the statement d3 = 10 + d2 ; We may think that since
{ we have overloaded + operator this statement would add 10
sample s ; to d2. But this does not happen. This is because the specified
int i ; statement will get converted as d3 = 10.operator+ ( d2 ) ;
i = s + 10 ; This means that this statement should call the operator+( )
cout << i ; function that takes an object of distance class as parameter
} written in
the float class, which is not possible. The solution is to write
In the above program on adding 10 to an object s, the value operator+( ) as a 'friend' function. Declare operator+ function
of i would become 20 in distance class as given below:
Can we have a reference to an array? friend distance operator + ( distance x1, distance x2 ) ;
Ans: Yes, we can have a reference to an array.
and define it outside the class as shown below:
int a[ ] = { 8, 2, 12, 9 } ;
int ( &r ) [ 4 ] = a ; // reference to an array distance operator + ( distance x1, distance x2 )
Here, r is a reference to an array of four elements. We can int f = x1.feet + x2.feet ;
even print the elements of array with the help of reference. return distance ( f ) ;
This is shown in the following code segment: }
When compiler would see that the 'friend' operator+( ) We can't initialize a reference to a data member at the time
function is available it would convert the statement d3 = 10 of declaration. It should be initialized using 'member wise
+ d2 as operator+ (10, d2 ). Now since 10 is passed as a initialization as shown below.
parameter not as a calling object there would be no error.
Thus in such cases 'friend' function becomes indispensable. #include
------------------------------------------------------------------------- class A
------------------------ {
75. public :
How to use a memory as a stream? char *p ;
char *&rp ;
Ans: Suppose, details of an employee such as name, A( ) : rp ( p )
designation, age, etc. are stored in different types of {
variables. Now, if we wish to concatenate these details in a p = "" ;
character array we will have to use various string }
manipulation functions like strcpy( ) and strcat( ). Instead of
using these functions we can use more easy and clean way to A ( char *s ) : rp ( p )
gather the details in the char array in the form of streams. {
We can declare the memory allocated for the array as stream p=s;
and use the << operator to store variables having different }
types in this memory. Following program shows how to };
achieve this.
#include void main( )
void main( ) {
{ A a ( "abcd" ) ;
char buff [50] ; cout << a.rp ;
char str[ ] = "Sanjay" ; }
char desig[ ] = "Manager" ;
char jd[ ] = "27/12/1995" ; 77.
int age = 35 ; iostream library has made it easy to read data from various
ostrstream o ( buff, sizeof ( buff ) ) ; input devices and write data to the output devices. The
o << str << endl << desig << endl << jd << endl << age following program shows how to print a disk file 'data.dat'
<< ends ; on the printer using stream classes. Every hardware device
cout << buff ; has a familiar name given by the operating system. The
} printer is generally connected to the first parallel port. So,
As shown in the program we can also use the the file name for the printer should be PRN or lpt1.
manipulators and formatting flags. The output of this #include
program will be: void main( )
Sanjay {
Manager ifstream i ( "data.dat" ) ;
27/12/1995 ofstream o ;
35 ( "PRN" ) ;
------------------------------------------------------------------------- char ch ;
------------------------ while ( 1 )
76. i.get ( ch ) ;
How would you declare and initialize reference to a data if ( i.eof( ) )
member? break ;
Ans: Sometimes we may need to declare a data member, o.put ( ch ) ;
which is a reference to another data member of the class as }
shown below: o.put ( '\x0C' ) ;
class A -------------------------------------------------------------------------
{ ------------------------
public : 78.
char *p ;
char *&rp ; We know that a destructor is automatically called when an
}; object of a class goes out of scope. There is another case
where destructor is called automatically. If an object is
created in a try block and an exception is thrown after the {
object is created, then the destructor is called automatically. }
------------------------------------------------------------------------- };
79. void main( )
Can a function call be at the left hand side of the assignment {
operator? vir v, v1 ;
int *p1 = ( int* ) &v ;
Ans: Yes. Following program shows how it is possible. int *p2 = ( int* ) &v1 ;
class ref cout << endl << *p1 << " " << *p2 ;
{ }
private : 81.
struct data Exception Handling in C++
int a ; char *p ; In C++ we can handle run-time errors generated by c++
} d1, d2 ; classes by using three new keywords: throw, catch, and try.
public : We also have to create an exception class. If during the
data &set ( ) course of execution of a member function of
{ this class a run-time error occurs, then this member function
return d1 ; informs the application that an error has occurred. This
} process of informing is called 'throwing' an exception. The
data &get ( ) following code shows how to deal with exception handling.
{ class sample
cin >> d2.a >> d2.p ; {
return d2 ; public :
}; class errorclass
void main( ) {
{ };
ref r ; void fun( )
r.set( ) = r.get( ) ; {
r.print( ) ; if ( some error occurs )
} throw errorclass( ) // throws exception
In the above program the functions get( ) and set( ) both }
return a reference to the object of the structure data. We have };
assigned the reference returned by get( ) to the reference //application
returned by set( ) function. That is, we are assigning d2 to void main( )
d1. So, the values of d2 would get assigned to d1. You can {
check this out by printing the values of d1. try
------------------------------------------------------------------------- {
------------------------ sample s ; ) ;
80. }
catch ( sample::errorclass )
If a class contains a virtual function a pointer called VPTR is {
created. This VPTR becomes a part of every object of that // do something about the error
class. The first two bytes (in DOS) are occupied by VPTR. }
We can prove this by displaying the first two bytes of }
memory allocated for the objects. Following program shows -------------------------------------------------------------------------
how this can be achieved. ------------------------
Accessing a private data member from a different
class vir Object...
public : Different objects of the same class can access each other's
virtual void f( ) members, even if these members are private. For example:
#include < iostream.h > Ans: The array name always refers or points to the zeroeth
class sample element. If array is of references then the array name would
{ point to the zeroeth element which happens to be a reference.
float f ; Creating pointer to a reference is not valid. So, creating array
public : of references too is not possible.
sample ( float ff )
{ 85.
f = ff ; How do I call a virtual function of a class using a pointer to a
} function ?
void fun ( sample* objptr ) Ans :
{ #include
objptr -> n = 0 ; class Cvirtual
cout << "Value of this objects f is : " << f << endl ; {
cout << "Value of other objects f" << objptr -> n << public :
endl ; virtual float vfun( )
} // another object's private member! {
}; cout << "from vfun" << endl ;
void main( ) return 7.03f ;
{ }
sample s1 ( 6.5f ) , s2 ( 2.5f ) ; };
s1.f ( &s2 ) ; // s1 changes s2's n void main( )
} {
Typically, this coding style should be avoided. However, Cvirtual obj ;
you should be aware that private members of an object can int **p = ( int ** ) &obj ;
be changed by another object of the same type. Therefore, in float ( *pf1 ) ( ) ;
certain special conditions, this coding style may be useful. pf1 = ( float ( * ) ( ) ) **p ;
------------------------------------------------------------------------- float f = ( *pf1 ) ( ) ;
------------------------ cout << "return val = " << f << endl ;
83. }
Can you access private data members of a class from out
side the class? In the above program class Cvirtual consists of a virtual
Ans: Yes. This program shows how. function vfun(). In variable p we have stored the address of
#include an object of class Cvirtual. While doing so, we have type
class emp casted the address of obj to int **, because obj holds a
private : hidden data member called vptr, which in turn holds the
int i ; address of virtual function vfun( ). In pf1, a pointer to a
public : function, we are collecting the address of the virtual function
emp( ) vfun( ). Thus the value returned by vfun( ) would then get
{ collected in f.
i = 10 ; -------------------------------------------------------------------------
} ------------------------
void main( )
emp *p = new emp ; 86.
int *pi = (int*) p ; Why an overloaded new operator defined in a class is static?
cout << *pi ;
*pi = 20 ; Ans: An overloaded new function is by default static even if
cout << *pi ; it is not declared so. This is because non-static member
} functions can be called through an object only. But when an
overloaded new operator function gets called the object
The pointer to the class is typecasted in an integer pointer. doesn't stand created. Since new operator function itself is
With the help of this pointer private data member 'i' is responsible for creating the object. Hence to be able to call a
accessed in main( ). function without an object, the function must be static.
------------------------------------------------------------------------- -------------------------------------------------------------------------
------------------------ ------------------------
84. 87.
Why creating array of references is not possible? What is a pure virtual destructor?
Ans: Like a pure virtual function we can also have a pure {
virtual destructor. If a base class contains a pure virtual
destructor it becomes necessary for the derived classes to }
implement the destructor. An ordinary pure virtual function
does not have a body but pure virtual destructor must have a void f ( float n )
body. This is because all the destructors in the hierarchy of {
inheritance are always called as a part of destruction.
------------------------------------------------------------------------- }
88. The above program results in an error (ambiguous call) since
When we are required to find offset of an element within a without the default argument the two functions have
structure? or, how do we call the function of an outer class arguments that are matching in number, order and type.
from a function in the inner class? (The inner class is nested -------------------------------------------------------------------------
in the outer class) ------------------------
Ans: 90.
#include Some programs need to exercise precise control over the
class outer memory areas where data is placed. For example, suppose
{ we wish to read the contents of the boot sector into a
int i ; structure. For this the byte arrangement of the
float f ; structure elements must match the arrangement of various
public : fields in the boot sector of the disk.
class inner
{ The #pragma pack directives offer a way to fulfill this
public : requirement. The #pragma pack directive specifies packing
infunc( ) alignment for structure and union members. The #pragma
{ takes effect at the first structure or union declaration after
outer *pout ; the #pragma is seen. Consider the following structure:
pout = (outer*) this - ( size_t ) &( ( ( outer* ) 0 ) -> in ) ; #pragma pack (1)
pout -> outfunc( ) ; struct emp
} {
}; int a ;
inner in ; float s ;
outfunc( ) char ch ;
{ };
cout << "in outer class's function" ; #pragma pack( )
} Here, #pragma pack ( 1 ) lets each structure element to begin
}; on a 1-byte boundary. Hence the size of the structure will be
void main( ) 9. (int - 4, float - 4, char - 1). If we use #pragma pack ( 2 )
{ each structure element can begin on a 2-byte boundary.
outer out ; Hence the size of the structure will be 10. (int - 4, float - 4, ) char - 2).
} -------------------------------------------------------------------------
In the above example we are calling outer::outfunc( ) from ------------------------
inner::infunc(). To call outfunc( ) we need a pointer to the 91.
outer class. To get the pointer we have subtracted offset of How to restrict a friend class's access to the private data
the inner class's object (base address of outer class's members?
object - address of inner class's object) from address of inner
class's object. Ans: If we declare a class as a friend of our class the friend
89. class can access the private data members of our class.
However, if we want we can restrict this access to some
void f ( float n, int i = 10 ) ; selective functions of the class. Following program shows
void f ( float a ) ; how to achieve this:
void main( )
{ #include
f ( 12.6 ) ; class X
} {
public :
void f ( float n, int i ) void print ( class Z &z ) ;
}; fun@test@@QAEXJJ@Z) and (?
class Z fun@test@@QAEXMM@Z). Note that different compilers
{ may use different name mangling schemes.
private : 93.
int i ; How would you call a C function from C++ code?
public : Ans: Using extern "C".
Z ( int ii ) The function prototype must be preceded by extern "C".
{ More than one C functions can be grouped inside braces as
i = ii ; shown below:
} extern "C"
friend X::print ( class Z &z ) ; {
}; void f( ) ;
void X::print ( Z &z1 ) void f1( ) ;
{ }
cout << z1.i ; // In cfunc.c
} #include
main( ) void f( )
{ {
Z z ( 10 ) ; printf ( "in f( )" ) ;
Xx; }
x.print ( 10 ) ; // In func.cpp
} #include
extern "C" void f( ) ;
In the above program only the X::print( ) function can access void main( )
the private data members of class Z. {
------------------------------------------------------------------------- f( ) ;
------------------------ }
92. Ensure that both .c and .cpp files are in the same project.

What is name mangling? -------------------------------------------------------------------------

Ans: C++ enables you to assign the same function name to
more than one functions but with different parameter types. 94.
This feature is called function overloading. But when we How to restrict the number of floating-point digits
give several functions the same name, how does the displayed ?
compiler decide which particular function is to be called? C+
+ solves this problem by applying a process called name Ans: When we display floating-point values, we can use the
mangling. Name mangling applies a decorated name to the setprecision manipulator to specify the desired number of
function. The mangled name includes tokens that identify the digits to the right of the decimal point.
functions' return type and the types of its arguments. For example,

class test cout << setprecision ( 3 ) << 12.34678 ;

public : This statement would give the output as 12.347.
void fun ( int a, char b ) ; -------------------------------------------------------------------------
void fun ( char *c, float y ) ; ------------------------
}; 95.
What is a wild pointer ?
void main( )
{ Ans: A wild pointer is the one that points to a garbage value.
test s1 ; For example, an uninitialized pointer that contains garbage ( 65, 'A' ) ; value or a pointer that refers to something that no longer ( "Anil", 5.5f ) ; exists.
} -------------------------------------------------------------------------
At the time of resolving the calls to fun( ) function the linker ------------------------
would not be able to find the definition of the overloaded
function fun( ) and it would report an error. If you look at
these errors you will see the mangled names like, (? 96.
How friend function helps to increase the versatility of s1.showdata( ) ;
overloaded operators? }

Ans: Consider the following statement, Here the operator *( ) function takes two parameters. This is
s2 = s1 * 2 ; because the operator function is no longer a member
where, s1 and s2 are objects of sample class. This statement function of the class. It is a friend of the class sample. Thus
would work if the overloaded operator * ( sample s ) or the statement s2 = s1 * 2 ; would not take the form
conversion function is provided in the class. Internally this s2.operator * ( 2 ). This example shows that using friend
statement would get converted to, permits the overloaded operators to be more versatile.
s2 = s1.operator * ( 2 ) ; 97.

The function materializes because it is called with an object What is a const_cast?

s1. The this pointer of s1 would get passed implicitly. To
collect 2 in s, first the compiler would call the one-argument Ans: The const_cast is used to convert a const to a non-
constructor, then it would build a const. This is shown in the following program.
nameless object, which then would get collected in s. #include
However, if we write the above statement as,
s2 = 2 * s1 ; void main( )
then it won't compile. This is because the call now would get {
treated as, const int a = 0 ;
s2 = 2.operator * ( s1 ) ;
and 2 is not an object. The friend function helps to get rid of int *ptr = ( int * ) &a ; // one way
such a situation. This is shown in the following program. ptr = const_cast ( &a ) ; // better way
#include }

class sample Here, the address of the const variable a is assigned to the
{ pointer to a non-const variable. The const_cast is also used
private : when we want to change the data members of a class inside
int i ; the const member functions. The following code snippet
public : shows how to do this.
sample ( int ii = 0 ) class sample
{ {
i = ii ; private :
} int data ;
public :
void showdata( ) void fun( ) const
{ {
cout << i << endl ; ( const_cast ( this ) ) -> data = 70 ;
} }
friend sample operator * ( sample, sample ) ; -------------------------------------------------------------------------
}; ------------------------
sample operator * ( sample s1, sample s2 ) Using a smart pointer we can make an object appear like a
{ pointer.
sample temp ;
temp.i = s1.i * s2.i ; If a class overloads the operator -> then any object of that
return ( temp ) ; class can appear like a pointer when the operator -> ( ) is
} called. The following program illustrates this.
void main( )
{ class test
sample s1 ( 10 ), s2 ; {
public :
s2 = s1 * 2 ; void fun( )
s2.showdata( ) ; {
cout << "fun of smart pointer" ;
s1 = 2 * s2 ; }
}; Why can't data members of a class be initialized at the time
of declaration as given in the following code?
class smartpointer class emp
{ {
test t ; private :
public : int j = 10 ;
test* operator ->( ) };
{ Ans: Memory for data members of a class is allocated only
return &t ; when object of that class is created. One cannot store data in
} a memory location, which does not exist at all. Therefore
}; initialization at the time of declaration
is not possible.
void main( ) -------------------------------------------------------------------------
{ ------------------------
smartpointer sp ; 101.
sp -> fun( ) ;
} Why in a copy constructor an object is collected in a
The beauty of overloading operator -> is that even though sp reference to object as shown below?
is an object we can make it work like a pointer. The operator #include
-> ( ) returns the address of the object of the type test. Using class emp
this address of the test object the function fun( ) of the class {
test gets called. Thus even though fun( ) is not a member of public :
smartpointer class we can still call it using sp. emp( )
------------------------------------------------------------------------- }
------------------------ emp ( emp& )
99. {
Can we apply delete on this pointer inside a member cout << "copy" ;
function? }
Ans : Yes! If the member function of a class is called using a void main( )
pointer to an object, which is allocated dynamically, the {
object would get deleted. But if the member function is emp e ;
called using the object, which is allocated statically, then a emp e1 = e ;
runtime error would occur. This is because we cannot call }
delete on statically allocated objects. This is illustrated in the Ans: A copy constructor is called when an object is created
following example. and initialised at the same time. It is also called when object
class sample is passed to a function. So, If we pass the object to copy
{ constructor copy constructor would get called recursively.
private : Thus it will stuck up in an infinite loop.
int i ; -------------------------------------------------------------------------
public : ------------------------
void fun( ) 102.
delete this ; What is Early Binding and Dynamic Binding?
} Ans: The term binding refers to the connection between a
}; function call and the actual code executed as a result of the
call. Early Binding: If which function is to be called is
void main( ) known at the compile-time it is known as static or early
{ binding. Dynamic Binding: If which function is to be called
sample *s = new sample ; is decided at run time it is called as late or dynamic binding.
s -> fun( ) ; // no error Dynamic binding is so called because the actual function
called at run-time depends on the contents of the pointer. For
sample s1 ; example, call to virtual functions, call to functions to be ) ; // would throw a runtime error linked from dlls use late binding.
} -------------------------------------------------------------------------
100. ------------------------
When can we use the function ostrstream::freeze( )?
4. How are Observer and Observable used?
Ans: While outputting data to memory in the in-memory Objects that subclass the Observable class maintain a list of
formatting we need to create an object of the class observers. When an Observable object is updated it invokes
ostrstream. The constructor of ostrstream receives the the update() method of each of its observers to notify the
address of the buffer but if we want that the ostrstream observers that it has changed state. The Observer interface is
object should do its own memory management then we need implemented by objects that observe Observable objects.
to create an ostrstream object with no constructor arguments
as: 5. What is synchronization and why is it important?
ostrstream s ; With respect to multithreading, synchronization is the
Now s will do its own memory management. We can stuff as capability to control the access of multiple threads to shared
many bytes into it as we want. If it falls short of memory, it resources. Without synchronization, it is possible for one
will allocate more memory. If it cannot, it may even move thread to modify a shared object while another thread is in
the block of memory. When the object goes out of scope, the the process of using or updating that object's value. This
heap storage is automatically released. This is a more often leads to significant errors.
flexible approach if we do not know how much space we are
going to need. If we want the physical address of the 6. Can a lock be acquired on a class?
memory used by s we can obtain it by calling the str( ) Yes, a lock can be acquired on a class. This lock is acquired
member function: on the class's Class object..
char* p = s.str( ) ;
Once str( ) has been called then the block of memory 7. What's new with the stop(), suspend() and resume()
allocated by ostrstream cannot be moved. This is logical. It methods in JDK 1.2?
can't move the block since we are now expecting it to be at a The stop(), suspend() and resume() methods have been
particular location. In such a case we deprecated in JDK 1.2.
say that ostrstream has freezed itself. Once frozen we can't
add any more characters to it. Adding characters to a frozen 8. Is null a keyword?
ostrstream results in undefined behavior. In addition, the The null value is not a keyword.
ostrstream is no longer responsible for cleaning up the
storage. You took over that responsibility when you asked 9. What is the preferred size of a component?
for the char * with str( ). We can clean the storage in two The preferred size of a component is the minimum
ways: Using the delete operator as shown below: component size that will allow the component to display
ostrstream s ; normally.
char *p ;
p = s.str( ) ; 10. What method is used to specify a container's layout?
delete p ; The setLayout() method is used to specify a container's
By unfreezing the ostrstream. You do this by calling layout.
freeze( ), with an argument 1. During freezing it is called
with the default argument of 0. 11. Which containers use a FlowLayout as their default
The Panel and Applet classes use the FlowLayout as their
default layout.

java 12. What state does a thread enter when it terminates its
#############3 processing?
FAQ In Core Java When a thread terminates its processing, it enters the dead
1.what is a transient variable? state.
A transient variable is a variable that may not be serialized. 13. What is the Collections API?
The Collections API is a set of classes and interfaces that
2.which containers use a border Layout as their default support operations on collections of objects.
The window, Frame and Dialog classes use a border layout 14. Which characters may be used as the second character of
as their default layout. an identifier,
but not as the first character of an identifier?
3.Why do threads block on I/O? The digits 0 through 9 may not be used as the first character
Threads block on i/o (that is enters the waiting state) so that of an identifier but they may be used after the first character
other threads may execute while the i/o Operation is of an identifier.
15. What is the List interface?
The List interface provides support for ordered collections of Garbage collection does not guarantee that a program will
objects. not run out of memory. It is possible for programs to use up
memory resources faster than they are garbage collected. It
16. How does Java handle integer overflows and is also possible for programs to create objects that are not
underflows? subject to garbage collection
It uses those low order bytes of the result that can fit into the
size of the type allowed by the operation. 28. What restrictions are placed on the location of a package
17. What is the Vector class? within a source code file?
The Vector class provides the capability to implement a A package statement must appear as the first line in a source
growable array of objects code file (excluding blank lines and comments).

18. What modifiers may be used with an inner class that is a 29. Can an object's finalize() method be invoked while it is
member of an outer class? reachable?
A (non-local) inner class may be declared as public, An object's finalize() method cannot be invoked by the
protected, private, static, final, or abstract. garbage collector while the object is still reachable.
However, an object's finalize() method may be invoked by
19. What is an Iterator interface? other objects.
The Iterator interface is used to step through the elements of
a Collection. 30. What is the immediate superclass of the Applet class?
20. What is the difference between the >> and >>>
operators? 31. What is the difference between preemptive scheduling
The >> operator carries the sign bit when shifting right. The and time slicing?
>>> zero-fills bits that have been shifted out. Under preemptive scheduling, the highest priority task
executes until it enters the waiting or dead states or a higher
21. Which method of the Component class is used to set the priority task comes into existence. Under time slicing, a task
position and executes for a predefined slice of time and then reenters the
size of a component? pool of ready tasks. The scheduler then determines which
setBounds() task should execute next, based on priority and
other factors.
22. How many bits are used to represent Unicode, ASCII,
UTF-16, and UTF-8 characters? 32. Name three Component subclasses that support painting.
Unicode requires 16 bits and ASCII require 7 bits. Although The Canvas, Frame, Panel, and Applet classes support
the ASCII character set uses only 7 bits, it is usually painting.
represented as 8 bits. UTF-8 represents characters using 8,
16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit 33. What value does readLine() return when it has reached
patterns. the end of a file?
The readLine() method returns null when it has reached the
23What is the difference between yielding and sleeping? end of a file.
When a task invokes its yield() method, it returns to the
ready state. When a task invokes its sleep() method, it 34. What is the immediate superclass of the Dialog class?
returns to the waiting state. Window
24. Which java.util classes and interfaces support event
handling? 35. What is clipping?
The EventObject class and the EventListener interface Clipping is the process of confining paint operations to a
support event processing. limited area or shape.

25. Is sizeof a keyword? 36. What is a native method?

The sizeof operator is not a keyword. A native method is a method that is implemented in a
language other than Java.
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be 37. Can a for statement loop indefinitely?
accessed as objects. Yes, a for statement can loop indefinitely. For example,
consider the following:
27. Does garbage collection guarantee that a program will for(;;) ;
not run out of memory?
38. What are order of precedence and associativity, and how MenuItem
are they used?
Order of precedence determines the order in which operators 51. What is the purpose of finalization?
are evaluated in expressions. Associatity determines whether The purpose of finalization is to give an unreachable object
an expression is evaluated left-to-right or right-to-left the opportunity to perform any cleanup processing before the
object is garbage collected.
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O. 52. Which class is the immediate superclass of the
MenuComponent class.
40. To what value is a variable of the String type Object
automatically initialized?
The default value of an String type is null. 53. What invokes a thread's run() method?
After a thread is started, via its start() method or that of the
41. What is the catch or declare rule for method Thread class, the JVM invokes the thread's run() method
declarations? when the thread is initially executed.
If a checked exception may be thrown within the body of a
method, the method must either catch the exception or 54. What is the difference between the Boolean & operator
declare it in its throws clause. and the && operator?
If an expression involving the Boolean & operator is
42. What is the difference between a MenuItem and a evaluated, both operands are evaluated. Then the & operator
CheckboxMenuItem? is applied to the operand. When an expression involving the
The CheckboxMenuItem class extends the MenuItem class && operator is evaluated, the first operand is evaluated. If
to support a menu item that may be checked or unchecked. the first operand returns a value of true then the second
operand is evaluated. The && operator is then applied to the
43. What is a task's priority and how is it used in scheduling? first and second operands. If the first operand evaluates to
A task's priority is an integer value that identifies the relative false, the evaluation of the second operand is skipped.
order in which it should be executed with respect to other
tasks. The scheduler attempts to schedule higher priority 55. Name three subclasses of the Component class.
tasks before lower priority tasks. Box.Filler, Button, Canvas, Checkbox, Choice, Container,
Label, List, Scrollbar, or TextComponent
44. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in 56. What is the GregorianCalendar class?
the AWT event-class hierarchy. The GregorianCalendar provides support for traditional
Western calendars.
45. When a thread is created and started, what is its initial
state? 57. Which Container method is used to cause a container to
A thread is in the ready state after it has been created and be laid out and redisplayed?
started. validate()

46. Can an anonymous class be declared as implementing an 58. What is the purpose of the Runtime class?
interface and extending a class? The purpose of the Runtime class is to provide access to the
An anonymous class may implement an interface or extend a Java runtime system.
superclass, but may not be declared to do both.
59. How many times may an object's finalize() method be
47. What is the range of the short type? invoked by the
The range of the short type is -(2^15) to 2^15 - 1. garbage collector?
An object's finalize() method may only be invoked once by
48. What is the range of the char type? the garbage collector.
The range of the char type is 0 to 2^16 - 1.
60. What is the purpose of the finally clause of a try-catch-
49. In which package are most of the AWT events that finally statement?
support the event-delegation The finally clause is used to provide the capability to execute
model defined? code no matter whether or not an exception is thrown or
Most of the AWT-related events of the event-delegation caught.
model are defined in the java.awt.event package. The
AWTEvent class is defined in the java.awt package. 61. What is the argument type of a program's main()
50. What is the immediate superclass of Menu?
A program's main() method takes an argument of the String[] resource. When a thread executes an object's wait() method,
type. it enters the waiting state. It only enters the ready state after
another thread invokes the object's notify() or notifyAll()
62. Which Java operator is right associative? methods..
The = operator is right associative.
73. What is an abstract method?
63. What is the Locale class? An abstract method is a method whose implementation is
The Locale class is used to tailor program output to the deferred to a subclass.
conventions of a particular geographic, political, or cultural
region. 74. How are Java source code files named?
A Java source code file takes the name of a public class or
64. Can a double value be cast to a byte? interface that is defined within the file. A source code file
Yes, a double value can be cast to a byte. may contain at most one public class or interface. If a public
class or interface is defined within a source code file, then
65. What is the difference between a break statement and a the source code file must take the name of the public class or
continue statement? interface. If no public class or interface is defined within a
A break statement results in the termination of the statement source code file, then the file must take on a name that is
to which it applies (switch, for, do, or while). A continue different than its classes and interfaces. Source code files use
statement is used to end the current loop iteration and return the .java extension.
control to the loop statement.
75. What is the relationship between the Canvas class and
66. What must a class do to implement an interface? the Graphics class?
It must provide all of the methods in the interface and A Canvas object provides access to a Graphics object via its
identify the interface in its implements clause. paint() method.

67. What method is invoked to cause an object to begin 76. What are the high-level thread states?
executing as a separate thread? The high-level thread states are ready, running, waiting, and
The start() method of the Thread class is invoked to cause an dead.
object to begin executing as a separate thread.
77. What value does read() return when it has reached the
68. Name two subclasses of the TextComponent class. end of a file?
TextField and TextArea The read() method returns -1 when it has reached the end of
a file.
69. What is the advantage of the event-delegation model
over the earlier event-inheritance model? 78. Can a Byte object be cast to a double value?
The event-delegation model has two advantages over the No, an object cannot be cast to a primitive value.
event-inheritance model. First, it enables event handling to
be handled by objects other than the ones that generate the 79. What is the difference between a static and a non-static
events (or their containers). This allows a clean separation inner class?
between a component's design and its use. The other A non-static inner class may have object instances that are
advantage of the event-delegation model is that it performs associated with instances of the class's outer class. A static
much better in applications where many events are inner class does not have any object instances.
generated. This performance improvement is due to the fact 80. What is the difference between the String and
that the event-delegation model does not have to repeatedly StringBuffer classes?
process unhandled events, as is the case of the event- String objects are constants. StringBuffer objects are not.
inheritance model.
70. Which containers may have a MenuBar? 81. If a variable is declared as private, where may the
Frame variable be accessed?
A private variable may only be accessed within the class in
71. How are commas used in the intialization and iteration which it is declared.
parts of a for statement?
Commas are used to separate multiple statements within the 82. What is an object's lock and which object's have locks?
initialization and iteration parts of a for statement. An object's lock is a mechanism that is used by multiple
threads to obtain synchronized access to the object. A thread
72. What is the purpose of the wait(), notify(), and may execute a synchronized method of an object only after it
notifyAll() methods? has acquired the object's lock. All objects and classes have
The wait(),notify(), and notifyAll() methods are used to locks. A class's lock is acquired on the class's Class object.
provide an efficient way for threads to wait for a shared
83. What is the Dictionary class? 95. What classes of exceptions may be caught by a catch
The Dictionary class provides the capability to store key- clause?
value pairs. A catch clause can catch any exception that may be assigned
to the Throwable type. This includes the Error and Exception
84. How are the elements of a BorderLayout organized? types.
The elements of a BorderLayout are organized at the borders
(North, South, East, and West) and the center of a container. 96. If a class is declared without any access modifiers, where
may the class be accessed?
85. What is the % operator? A class that is declared without any access modifiers is said
It is referred to as the modulo or remainder operator. It to have package access. This means that the class can only
returns the remainder of dividing the first operand by the be accessed by other classes and interfaces that are defined
second operand. within the same package.

86. When can an object reference be cast to an interface 97. What is the SimpleTimeZone class?
reference? The SimpleTimeZone class provides support for a Gregorian
An object reference be cast to an interface reference when calendar.
the object implements the referenced interface.
98. What is the Map interface?
87. What is the difference between a Window and a Frame? The Map interface replaces the JDK 1.1 Dictionary class and
The Frame class extends Window to define a main is used associate keys with values.
application window that can have a menu bar.
99. Does a class inherit the constructors of its superclass?
88. Which class is extended by all other classes? A class does not inherit constructors from any of its
The Object class is extended by all other classes. superclasses.

89. Can an object be garbage collected while it is still 100. For which statements does it make sense to use a label?
reachable? The only statements for which it makes sense to use a label
A reachable object cannot be garbage collected. Only are those statements that can enclose a break or continue
unreachable objects may be garbage collected.. statement.

90. Is the ternary operator written x : y ? z or x ? y : z ? 101. What is the purpose of the System class?
It is written x ? y : z. The purpose of the System class is to provide access to
system resources.
91. What is the difference between the Font and FontMetrics
classes? 102. Which TextComponent method is used to set a
The FontMetrics class is used to define implementation- TextComponent to the read-only state?
specific properties, such as ascent and descent, of a Font setEditable()
103. How are the elements of a CardLayout organized?
92. How is rounding performed under integer division? The elements of a CardLayout are stacked, one on top of the
The fractional part of the result is truncated. This is known other, like a deck of cards.
as rounding toward zero.
104. Is &&= a valid Java operator?
93. What happens when a thread cannot acquire a lock on an No, it is not.
If a thread attempts to execute a synchronized method or 105. Name the eight primitive Java types.
synchronized statement and is unable to acquire an object's The eight primitive types are byte, char, short, int, long,
lock, it enters the waiting state until the lock becomes float, double, and boolean.
106. Which class should you use to obtain design
94. What is the difference between the Reader/Writer class information about an object?
hierarchy and the The Class class is used to obtain information about an
InputStream/OutputStream class hierarchy? object's design.
The Reader/Writer class hierarchy is character-oriented, and
the InputStream/OutputStream class hierarchy is byte- 107. What is the relationship between clipping and
oriented. repainting?
When a window is repainted by the AWT painting thread, it Java uses layout managers to lay out components in a
sets the clipping regions to the area of the window that consistent manner across all windowing platforms. Since
requires repainting. Java's layout managers aren't tied to absolute sizing and
positioning, they are able to accomodate platform-specific
108. Is "abc" a primitive value? differences among windowing systems.
The String literal "abc" is not a primitive value. It is a String
object. 119. What is the Collection interface?
The Collection interface provides support for the
109. What is the relationship between an event-listener implementation of a mathematical bag - an unordered
interface and an collection of objects that may contain duplicates.
event-adapter class?
An event-listener interface defines the methods that must be 120. What modifiers can be used with a local inner class?
implemented by an event handler for a particular kind of A local inner class may be final or abstract.
event. An event adapter provides a default implementation of
an event-listener interface. 121. What is the difference between static and non-static
110. What restrictions are placed on the values of each case A static variable is associated with the class as a whole
of a switch statement? rather than with specific instances of a class. Non-static
During compilation, the values of each case of a switch variables take on unique values with each object instance.
statement must evaluate to a value that can be promoted to
an int value. 122. What is the difference between the paint() and repaint()
111. What modifiers may be used with an interface The paint() method supports painting via a Graphics object.
declaration? The repaint() method is used to cause paint() to be invoked
An interface may be declared as public or abstract. by the AWT painting thread.

112. Is a class a subclass of itself? 123. What is the purpose of the File class?
A class is a subclass of itself. The File class is used to create objects that provide access to
the files and directories of a local file system.
113. What is the highest-level event class of the event-
delegation model? 124. Can an exception be rethrown?
The java.util.EventObject class is the highest-level class in Yes, an exception can be rethrown.
the event-delegation class hierarchy. 125. Which Math method is used to calculate the absolute
value of a number?
114. What event results from the clicking of a button? The abs() method is used to calculate absolute values.
The ActionEvent event is generated as the result of the
clicking of a button. 126. How does multithreading take place on a computer with
a single CPU?
115. How can a GUI component handle its own events? The operating system's task scheduler allocates execution
A component can handle its own events by implementing the time to multiple tasks. By quickly switching between
required event-listener interface and adding itself as its own executing tasks, it creates the impression that tasks execute
event listener. sequentially.
116. What is the difference between a while statement and a
do statement? 127. When does the compiler supply a default constructor
A while statement checks at the beginning of a loop to see for a class?
whether the next loop iteration should occur. A do statement The compiler supplies a default constructor for a class if no
checks at the end of a loop to see whether the next iteration other constructors are provided.
of a loop should occur. The do statement will always execute
the body of a loop at least once. 128. When is the finally clause of a try-catch-finally
statement executed?
117. How are the elements of a GridBagLayout organized? The finally clause of the try-catch-finally statement is always
The elements of a GridBagLayout are organized according executed unless the thread of execution terminates or an
to a grid. However, the elements are of different sizes and exception occurs within the execution of the finally clause.
may occupy more than one row or column of the grid. In
addition, the rows and columns may have different sizes. 129. Which class is the immediate superclass of the
Container class?
118. What advantage do Java's layout managers provide over Component
traditional windowing systems?
130. If a method is declared as protected, where may the The ObjectInputStream class supports the reading of objects
method be accessed? from input streams.
A protected method may only be accessed by classes or
interfaces of the same package or by subclasses of the class 141. What is the difference between a field variable and a
in which it is declared. local variable?
A field variable is a variable that is declared as a member of
131. How can the Checkbox class be used to create a radio a class. A local variable is a variable that is declared local to
button? a method.
By associating Checkbox objects with a CheckboxGroup.
142. Under what conditions is an object's finalize() method
132. Which non-Unicode letter characters may be used as invoked by the garbage collector?
the first character The garbage collector invokes an object's finalize() method
of an identifier? when it detects that the object has become unreachable.
The non-Unicode letter characters $ and _ may appear as the
first character of an identifier 143. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class.
133. What restrictions are placed on method overloading? super() is used to invoke a superclass constructor.
Two methods may not have the same name and argument list
but different return types. 144. What is the relationship between a method's throws
clause and the exceptions
134. What happens when you invoke a thread's interrupt that can be thrown during the method's execution?
method while it is A method's throws clause must declare any checked
sleeping or waiting? exceptions that are not caught within the body of the method.
When a task's interrupt() method is executed, the task enters
the ready state. The next time the task enters the running 145. What is the difference between the JDK 1.02 event
state, an InterruptedException is thrown. model and the event-delegation
model introduced with JDK 1.1?
135. What is casting? The JDK 1.02 event model uses an event inheritance or
There are two types of casting, casting between primitive bubbling approach. In this model, components are required
numeric types and casting between object references. to handle their own events. If they do not handle a particular
Casting between numeric types is used to convert larger event, the event is inherited by (or bubbled up to) the
values, such as double values, to smaller values, such as byte component's container. The container then either handles the
values. Casting between object references is used to refer to event or it is bubbled up to its container and so on, until the
an object by a compatible class, interface, or array type highest-level container has been tried..
reference. In the event-delegation model, specific objects are
designated as event handlers for GUI components. These
136. What is the return type of a program's main() method? objects implement event-listener interfaces. The event-
A program's main() method has a void return type. delegation model is more efficient than the event-inheritance
model because it eliminates the processing required to
137. Name four Container classes. support the bubbling of unhandled events.
Window, Frame, Dialog, FileDialog, Panel, Applet, or 146. How is it possible for two String objects with identical
ScrollPane values not to be equal
under the == operator?
138. What is the difference between a Choice and a List? The == operator compares two objects to determine if they
A Choice is displayed in a compact form that requires you to are the same object in memory. It is possible for two String
pull it down to see the list of available choices. Only one objects to have the same value, but located indifferent areas
item may be selected from a Choice. A List may be of memory.
displayed in such a way that several List items are visible. A
List supports the selection of one or more List items. 147. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code
139. What class of exceptions are generated by the Java run- library.
time system?
The Java runtime system generates RuntimeException and 148. What Checkbox method allows you to tell if a
Error exceptions. Checkbox is checked?
140. What class allows you to read objects directly from a
stream? 149. What state is a thread in when it is executing?
An executing thread is in the running state.
If you are running Java on English Windows platforms, it is
150. What are the legal operands of the instanceof operator? probably Cp1252. If you are running Java on English Solaris
The left operand is an object reference or null value and the platforms, it is most likely 8859_1..
right operand is a class, interface, or array type.
163. Which package is always imported by default?
151. How are the elements of a GridLayout organized? The java.lang package is always imported by default.
The elements of a GridBad layout are of equal size and are
laid out using the squares of a grid. 164. What interface must an object implement before it can
be written to a
152. What an I/O filter? stream as an object?
An I/O filter is an object that reads from one stream and An object must implement the Serializable or Externalizable
writes to another, usually altering the data in some way as it interface before it can be written to a stream as an object.
is passed from one stream to another.
165. How are this and super used?
153. If an object is garbage collected, can it become this is used to refer to the current object instance. super is
reachable again? used to refer to the variables and methods of the superclass
Once an object is garbage collected, it ceases to exist. It can of the current object instance.
no longer become reachable again.
166. What is the purpose of garbage collection?
154. What is the Set interface? The purpose of garbage collection is to identify and discard
The Set interface provides methods for accessing the objects that are no longer needed by a program so that their
elements of a finite mathematical set. Sets do not allow resources may be reclaimed and reused.
duplicate elements. 167. What is a compilation unit?
A compilation unit is a Java source code file.
155. What classes of exceptions may be thrown by a throw
statement? 168. What interface is extended by AWT event listeners?
A throw statement may throw any expression that may be All AWT event listeners extend the java.util.EventListener
assigned to the Throwable type. interface.
156. What are E and PI?
E is the base of the natural logarithm and PI is mathematical 169. What restrictions are placed on method overriding?
value pi. Overridden methods must have the same name, argument
list, and return type.
157. Are true and false keywords? The overriding method may not limit the access of the
The values true and false are not keywords. method it overrides.
The overriding method may not throw any exceptions that
158. What is a void return type? may not be thrown
A void return type indicates that a method does not return a by the overridden method.
170. How can a dead thread be restarted?
159. What is the purpose of the enableEvents() method? A dead thread cannot be restarted.
The enableEvents() method is used to enable an event for a
particular object. Normally, an event is enabled when a 171. What happens if an exception is not caught?
listener is added to an object for a particular event. The An uncaught exception results in the uncaughtException()
enableEvents() method is used by objects that handle events method of the thread's ThreadGroup being invoked, which
by overriding their event-dispatch methods. eventually results in the termination of the program in which
it is thrown.
160. What is the difference between the File and
RandomAccessFile classes? 172. What is a layout manager?
The File class encapsulates the files and directories of the A layout manager is an object that is used to organize
local file system. The RandomAccessFile class provides the components in a container.
methods needed to directly access data contained in any part
of a file. 173. Which arithmetic operations can result in the throwing
of an ArithmeticException?
161. What happens when you add a double value to a String? Integer / and % can result in the throwing of an
The result is a String object. ArithmeticException.

162. What is your platform's default character encoding? 174. What are three ways in which a thread can enter the
waiting state?
A thread can enter the waiting state by invoking its sleep() A statement block is used to organize a sequence of
method, by blocking on I/O, by unsuccessfully attempting to statements as a single statement group.
acquire an object's lock, or by invoking an object's wait()
method. It can also enter the waiting state by invoking its 185. What is a Java package and how is it used?
(deprecated) suspend() method. A Java package is a naming context for classes and
interfaces. A package is used to create a separate name space
175. Can an abstract class be final? for groups of classes and interfaces. Packages are also used
An abstract class may not be declared as final. to organize related classes and interfaces into a single API
unit and to control accessibility to these classes and
176. What is the ResourceBundle class? interfaces.
The ResourceBundle class is used to store locale-specific
resources that can be loaded by a program to tailor the 186. What modifiers may be used with a top-level class?
program's appearance to the particular locale in which it is A top-level class may be public, abstract, or final.
being run.
187. What are the Object and Class classes used for?
177. What happens if a try-catch-finally statement does not The Object class is the highest-level class in the Java class
have a catch clause to handle an exception that is thrown hierarchy. The Class class is used to represent the classes
within the body of the try statement? and interfaces that are loaded by a Java program..
The exception propagates up to the next higher level try- 188. How does a try statement determine which catch clause
catch statement (if any) or results in the program's should be used to handle an exception?
termination. When an exception is thrown within the body of a try
statement, the catch clauses of the try statement are
178. What is numeric promotion? examined in the order in which they appear. The first catch
Numeric promotion is the conversion of a smaller numeric clause that is capable of handling the exception is executed.
type to a larger numeric type, so that integer and floating- The remaining catch clauses are ignored.
point operations may take place. In numerical promotion,
byte, char, and short values are converted to int values. The 189. Can an unreachable object become reachable again?
int values are also converted to long values, if necessary. An unreachable object may become reachable again. This
The long and float values are converted to double values, as can happen when the object's finalize() method is invoked
required. and the object performs an operation which causes it to
become accessible to reachable objects.
179. What is the difference between a Scrollbar and a
ScrollPane? 190. When is an object subject to garbage collection?
A Scrollbar is a Component, but not a Container. A An object is subject to garbage collection when it becomes
ScrollPane is a Container. A ScrollPane handles its own unreachable to the program in which it is used.
events and performs its own scrolling.
191. What method must be implemented by all threads?
180. What is the difference between a public and a non- All tasks must implement the run() method, whether they are
public class? a subclass of Thread or implement the Runnable interface.
A public class may be accessed outside of its package. A
non-public class may not be accessed outside of its package. 192. What methods are used to get and set the text label
displayed by a Button object?
181. To what value is a variable of the boolean type getLabel() and setLabel()
automatically initialized?
The default value of the boolean type is false. 193. Which Component subclass is used for drawing and
182. Can try statements be nested? Canvas
Try statements may be tested.
194. What are synchronized methods and synchronized
183. What is the difference between the prefix and postfix statements?
forms of the ++ operator? Synchronized methods are methods that are used to control
The prefix form performs the increment operation and access to an object. A thread only executes a synchronized
returns the value of the increment operation. The postfix method after it has acquired the lock for the method's object
form returns the current value all of the expression and then or class. Synchronized statements are similar to
performs the increment operation on that value. synchronized methods. A synchronized statement can only
be executed after a thread has acquired the lock for the
184. What is the purpose of a statement block? object or class referenced in the synchronized statement.
195. What are the two basic ways in which classes that can · What is the difference between "overloading" and
be run as threads may be defined? "overridding"?
A thread class may be declared as a subclass of Thread, or it · Explain the need for "Virtual Destructor".
may implement the Runnable interface. · Can we have "Virtual Constructors"?
· What are the different types of polymorphism?
196. What are the problems faced by Java programmers who · What are Virtual Functions? How to implement virtual
don't use layout managers? functions in "C"
Without layout managers, Java programmers are faced with · What are the different types of Storage classes?
determining how their GUI will be displayed across multiple · What is Namespace?
windowing systems and finding a common sizing and · What are the types of STL containers?.
positioning that will work within the constraints imposed by · Difference between "vector" and "array"?
each windowing system. · How to write a program such that it will delete itself after
197. What is the difference between an if statement and a · Can we generate a C++ source code from the binary file?
switch statement? · What are inline functions?
The if statement is used to select among two alternatives. It · Talk sometiming about profiling?
uses a boolean expression to decide which alternative should · How many lines of code you have written for a single
be executed. The switch statement is used to select among program?
multiple alternatives. It uses an int expression to determine · What is "strstream" ?
which alternative should be executed. · How to write Multithreaded applications using C++?
· Explain "passing by value", "passing by pointer" and
198. What happens when you add a double value to a String? "passing by reference"
The result is a String object. · Write any small program that will compile in "C" but not in
199. What is the List interface? · Have you heard of "mutable" keyword?
The List interface provides support for ordered collections of · What is a "RTTI"?
· Is there something that I can do in C and not in C++?
· Why preincrement operator is faster than postincrement?
· What is the difference between "calloc" and "malloc"?
************************************ · What will happen if I allocate memory using "new" and
FAQ In Object Oriented Concepts free it using "free" or allocate sing "calloc" and free it using
********************************* "delete"?
· How do you write a program which produces its own · What is Memory Alignment?
source code as its output? · Explain working of printf.
· How can I find the day of the week given the date? · Difference between "printf" and "sprintf".
· Why doesn't C have nested functions? · What is "map" in STL?
· What is the most efficient way to count the number of bits · When shall I use Multiple Inheritance?
which are set in a value? · What are the techniques you use for debugging?
· How can I convert integers to binary or hexadecimal? · How to reduce a final size of executable?
· How can I call a function, given its name as a string? · Give 2 examples of a code optimization.
· How do I access command-line arguments? · What is inheritance?
· How can I return multiple values from a function? · Difference between Composition and Aggregation.
· How can I invoke another program from within a C · Difference: Sequence Diagrams, Collaboration Diagrams.
program? · Difference: 'uses', 'extends', 'includes'
· How can I access memory located at a certain address? · What shall I go for Package Diagram?
· How can I allocate arrays or structures bigger than 64K? · What is Polymorphism?
· How can I find out how much memory is available? · Is class an Object? Is object a class?
· How can I read a directory in a C program? · Comment: C++ "includes" behavior and java "imports"
· How can I increase the allowable number of simultaneously · What do you mean by "Realization"?
open files? · What is a Presistent, Transient Object?
· What's wrong with the call "fopen("c:\newdir\file.dat", · What is the use of Operator Overloading?
"r")"? · Does UML guarantee project success?
· What is the output of printf("%d") · Difference: Activity Diagram and Sequence Diagram.
· What will happen if I say delete this · What is association?
· Difference between "C structure" and "C++ structure". · How to resolve many to many relationship?
· Diffrence between a "assignment operator" and a "copy · How do you represent static members and abstract classes
constructor" in Class Diagram?
· What does static variable mean? · How can we check whether the contents of two structure
· What is a pointer? variables are same or not?
· What is a structure? · How are Structure passing and returning implemented by
· What are the differences between structures and arrays? the complier?
· In header files whether functions are declared or defined? · How can we read/write Structures from/to data files?
· What are the differences between malloc() and calloc()? · What is the difference between an enumeration and a set of
· What are macros? what are its advantages and pre-processor # defines?
disadvantages? · what do the 'c' and 'v' in argc and argv stand for?
· Difference between pass by reference and pass by value? · Are the variables argc and argv are local to main?
· What is static identifier? What is the maximum combined length of command line
· Where are the auto variables stored? arguments including the space between adjacent arguments?
· Where does global, static, local, register variables, free · If we want that any wildcard characters in the command
memory and C Program instructions get stored? line arguments should be appropriately expanded, are we
· Difference between arrays and linked list? required to make any special provision? If yes, which?
· What are enumerations? · Does there exist any way to make the command line
· Describe about storage allocation and scope of global, arguments available to other functions without passing them
extern, static, local and register variables? as arguments to the function?
· What are register variables? What are the advantage of · What are bit fields? What is the use of bit fields in a
using register variables? Structure declaration?
· What is the use of typedef? · To which numbering system can the binary number
· Can we specify variable field width in a scanf() format 1101100100111100 be easily converted to?
string? If possible how? · Which bit wise operator is suitable for checking whether a
· Out of fgets() and gets() which function is safe to use and particular bit is on or off?
why? · Which bit wise operator is suitable for turning off a
· Difference between strdup and strcpy? particular bit in a number?
· What is recursion? · Which bit wise operator is suitable for putting on a
· Differentiate between a for loop and a while loop? What particular bit in a number?
are it uses? · Which bit wise operator is suitable for checking whether a
· What are the different storage classes in C? particular bit is on or off?
· Write down the equivalent pointer expression for referring · which one is equivalent to multiplying by 2:Left shifting a
the same element a[i][j][k][l]? number by 1 or Left shifting an unsigned int or char by 1?
· What is difference between Structure and Unions? · Write a program to compare two strings without using the
· What the advantages of using Unions? strcmp() function.
· What are the advantages of using pointers in a program? · Write a program to concatenate two strings.
· What is the difference between Strings and Arrays? · Write a program to interchange 2 variables without using
· In a header file whether functions are declared or defined? the third one.
· What is a far pointer? where we use it? · Write programs for String Reversal & Palindrome check
· How will you declare an array of three function pointers · Write a program to find the Factorial of a number
where each function receives two ints and returns a float? · Write a program to generate the Fibinocci Series
· what is a NULL Pointer? Whether it is same as an · Write a program which employs Recursion
uninitialized pointer? · Write a program which uses Command Line Arguments
· What is a NULL Macro? What is the difference between a · Write a program which uses functions like strcmp(),
NULL Pointer and a NULL Macro? strcpy()? etc
· What does the error 'Null Pointer Assignment' mean and · What are the advantages of using typedef in a program?
what causes this error? · How would you dynamically allocate a one-dimensional
· What is near, far and huge pointers? How many bytes are and two-dimensional array of integers?
occupied by them? · How can you increase the size of a dynamically allocated
· How would you obtain segment and offset addresses from a array?
far address of a memory location? · How can you increase the size of a statically allocated
· Are the expressions arr and &arr same for an array of array?
integers? · When reallocating memory if any other pointers point into
· Does mentioning the array name gives the base address in the same piece of memory do you have to readjust these
all the contexts? other pointers or do they get readjusted automatically?
· Explain one method to process an entire string as one unit? · Which function should be used to free the memory
· What is the similarity between a Structure, Union and allocated by calloc()?
enumeration? · How much maximum can you allocate in a single call to
· Can a Structure contain a Pointer to itself? malloc()?
· Can you dynamically allocate arrays in expanded memory?
· What is object file? How can you access object file? · What do you mean by public, private, protected and
Which header file should you include if you are to develop a friendly?
function which can accept variable number of arguments? · When is an object created and what is its lifetime?
· Can you write a function similar to printf()? · What do you mean by multiple inheritance and multilevel
· How can a called function determine the number of inheritance? Differentiate between them.
arguments that have been passed to it? · Difference between realloc() and free?
· Can there be at least some solution to determine the number · What is a template?
of arguments passed to a variable argument list function? · What are the main differences between procedure oriented
· How do you declare the following: languages and object oriented languages?
· An array of three pointers to chars · What is R T T I ?
· An array of three char pointers · What are generic functions and generic classes?
· A pointer to array of three chars · What is namespace?
· A pointer to function which receives an int pointer and · What is the difference between pass by reference and pass
returns a float pointer by value?
· A pointer to a function which receives nothing and returns · Why do we use virtual functions?
nothing · What do you mean by pure virtual functions?
· What do the functions atoi(), itoa() and gcvt() do? · What are virtual classes?
· Does there exist any other function which can be used to · Does c++ support multilevel and multiple inheritance?
convert an integer or a float to a string? · What are the advantages of inheritance?
· How would you use qsort() function to sort an array of · When is a memory allocated to a class?
structures? · What is the difference between declaration and definition?
· How would you use qsort() function to sort the name stored · What is virtual constructors/destructors?
in an array of pointers to string? · In c++ there is only virtual destructors, no constructors.
· How would you use bsearch() function to search a name Why?
stored in array of pointers to string? · What is late bound function call and early bound function
· How would you use the functions sin(), pow(), sqrt()? call? Differentiate.
· How would you use the functions memcpy(), memset(), · How is exception handling carried out in c++?
memmove()? · When will a constructor executed?
· How would you use the functions fseek(), freed(), fwrite() · What is Dynamic Polymorphism?
and ftell()? · Write a macro for swapping integers.
· How would you obtain the current time and difference *************************************************
between two times? *************************************************
· How would you use the functions randomize() and *
· How would you implement a substr() function that extracts FAQ In Testing Tools
a sub string from a given string?
· What is the difference between the functions rand(), ************************
random(), srand() and randomize()? Click here for Winrunner Interview Questions.
· What is the difference between the functions memmove()
and memcpy()? Software QA and Testing Frequently-Asked-Questions
· How do you print a string on the printer?
· Can you use the function fprintf() to display the output on 1.What is 'Software Quality Assurance'?
the screen?
· What is an object? Software QA involves the entire software development
· What is the difference between an object and a class? PROCESS - monitoring and improving the process, making
· What is the difference between class and structure? sure that any agreed- upon standards and procedures are
· What is public, protected, private? followed, and ensuring that problems are found and dealt
· What are virtual functions? with. It is oriented to 'prevention'.
· What is friend function?
· What is a scope resolution operator? 2.What is 'Software Testing'?
· What do you mean by inheritance?
· What is abstraction? Testing involves operation of a system or application under
· What is polymorphism? Explain with an example. controlled conditions and evaluating the results (eg, 'if the
· What is encapsulation? user is in interface A of the application while using hardware
· What do you mean by binding of data and functions? B, and does C, then D should happen'). The controlled
· What is function overloading and operator overloading? conditions should include both normal and abnormal
· What is virtual class and friend class? conditions. Testing should intentionally attempt to make
· What do you mean by inline function? things go wrong to determine if things happen when they
shouldn't or things don't happen when they should. It is school district decided to reinstate it's original 25-year old
oriented to 'detection'. system for at least a year until the bugs were worked out of
the new system by the software vendors.
3.What are some recent major computer system failures
caused by software bugs? In October of 1999 the $125 million NASA Mars Climate
Orbiter spacecraft was believed to be lost in space due to a
In April of 2003 it was announced that the largest student simple data conversion error. It was determined that
loan company in the U.S. made a software error in spacecraft software used certain data in English units that
calculating the monthly payments on 800,000 loans. should have been in metric units. Among other tasks, the
Although borrowers were to be notified of an increase in orbiter was to serve as a communications relay for the Mars
their required payments, the company will still reportedly Polar Lander mission, which failed for unknown reasons in
lose $8 million in interest. The error was uncovered when December 1999. Several investigating panels were convened
borrowers began reporting inconsistencies in their bills. to determine the process failures that allowed the error to go
News reports in February of 2003 revealed that the U.S.
Treasury Department mailed 50,000 Social Security checks Bugs in software supporting a large commercial high-speed
without any beneficiary names. A spokesperson indicated data network affected 70,000 business customers over a
that the missing names were due to an error in a software period of 8 days in August of 1999. Among those affected
change. Replacement checks were subsequently mailed out was the electronic trading system of the largest U.S. futures
with the problem corrected, and recipients were then able to exchange, which was shut down for most of a week as a
cash their Social Security checks. result of the outages.

In March of 2002 it was reported that software bugs in In April of 1999 a software bug caused the failure of a $1.2
Britain's national tax system resulted in more than 100,000 billion military satellite launch, the costliest unmanned
erroneous tax overcharges. The problem was partly attibuted accident in the history of Cape Canaveral launches. The
to the difficulty of testing the integration of multiple failure was the latest in a string of launch failures, triggering
systems. a complete military and industry review of U.S. space launch
programs, including software integration and testing
A newspaper columnist reported in July 2001 that a serious processes. Congressional oversight hearings were requested.
flaw was found in off-the-shelf software that had long been
used in systems for tracking certain U.S. nuclear materials. A small town in Illinois received an unusually large monthly
The same software had been recently donated to another electric bill of $7 million in March of 1999. This was about
country to be used in tracking their own nuclear materials, 700 times larger than its normal bill. It turned out to be due
and it was not until scientists in that country discovered the to bugs in new software that had been purchased by the local
problem, and shared the information, that U.S. officials power company to deal with Y2K software issues.
became aware of the problems. According to newspaper
stories in mid-2001, a major systems development contractor
was fired and sued over problems with a large retirement
plan management system. According to the reports, the
client claimed that system deliveries were late, the software
had excessive defects, and it caused other systems to crash.

In January of 2001 newspapers reported that a major

European railroad was hit by the aftereffects of the Y2K bug.
The company found that many of their newer trains would
not run due to their inability to recognize the date
'31/12/2000'; the trains were started by altering the control
system's date settings.News reports in September of 2000
told of a software vendor settling a lawsuit with a large
mortgage lender; the vendor had reportedly delivered an
online mortgage processing system that did not meet
specifications, was delivered late, and didn't work.

In early 2000, major problems were reported with a new

computer system in a large suburban U.S. public school
district with 100,000+ students; problems included 10,000
erroneous report cards and students left stranded by failed
class registration systems; the district's CIO was fired. The