Professional Documents
Culture Documents
C, C
C, C
The first 16 chapters, and the chapter on GUI programming (chapter 27 of Big C++
= chapter 18 of C++ Essentials) are identical.
Big C++ has expanded C++ coverage on operator overloading, memory
management, exception handling, name scope management, polymorphism, multiple
inheritance, templates, and STL (8 chapters). C++ Essentials has a one-chapter
summary that briefly discusses operator overloading, exception handling, name
scope management, and templates.
Big C++ has chapters on UML, design patterns, database programming, and XML.
(The XML chapter is available on the web.)
Question: What are the differences between the second and third edition of
Computing Concepts with C++ Essentials?
Answer:
The coverage of the third edition is more object-oriented, with class design appearing
earlier and a chapter on OO design
Recursion is now covered in a separate chapter
The chapter on data structures has expanded coverage of STL
There are new chapters on advanced C++ topics and GUI programming
There is expanded coverage of pointers and C-style arrays
Answer: Answers to the odd-numbered exercises are available for all readers. If you
are an instructor, please visit http://www.wiley.com/college/horstmann and select
"Instructor Resources". You will need to fill out a form and obtain a password to see
the solutions to all exercises.
Question: Why do I get an error message: "std does not exist or is not a
namespace"?
Answer: Your compiler (Microsoft Visual C++ 6) does not conform to the C++
standard. A remedy is to add a line
namespace std {}
Answer: Your compiler (Microsoft Visual C++ 6) does not conform to the C++
standard. A remedy is to rename the index variable in the second loop.
Answer: Your compiler (Microsoft Visual C++ 6 or g++ 2.9x) does not conform to
the C++ standard. A remedy is to add the line
double max(double x, double y) { if (x > y) return x; else return y; }
with
Answer: Your compiler (g++ 2.9x) does not conform to the C++ standard. A remedy
is to change
#include <sstream>
...
istringstream instr(s);
...
ostringstream outstr;
...
s = outstr.str();
to
#include <strstream>
...
istrstream instr(s.c_str())
...
ostrstream outstr;
...
s = string(outstr.str());
Question: Why do I get an error message: "fixed undefined" even though I
include the <iomanip> header?
Answer: Your compiler (g++ 2.9x) does not conform to the C++ standard. A remedy
is to replace fixed with setiosflags(ios::fixed)
Answer: (1) STL uses doubly-linked lists. (2) It is actually easier to implement
insertion and deletion in a doubly-linked list.
Question: Why doesn't the book teach more about char* strings? Doesn't
every C++ programmer need to know them?
Answer: This is a book about computing concepts, not about C++. Strings are a
concept. ANSI C++ supports two implementations of strings: the string class and
char* pointers. There is no doubt that many C++ programmers will need to learn
both implementations, but I do not believe they should learn all details of both of
them in their first programming course. The string class is safe and convenient.
Students master it quickly and can move on to learning more computing concepts.
Answer: The <iostream> header and the std namespace were introduced in 1996
and approved in the international standard in 1998. If your compiler does not
support these constructs, you will need to upgrade your compiler. g++, Borland C++
5.5 and Microsoft Visual C++ 6 are reasonably standard compliant.
Answer: The CCC graphics library has been purposefully kept simple so that students
don't fritter away endless time with color and fancy fonts. Use wxWidgets if you want
fancier graphics
Answer: There are many different schemes to name accessors, mutators and data
fields. The C++ library uses overloaded pairsseconds() and seconds(int) for
accessors and mutators, which I think is a bit too confusing. I felt the get/set
terminology makes it really clear that the accessor is a function call. And, of course,
that is the convention used in Java.
Question: Why do you use all those underscores in function names? What is wrong
with mixed case?
Answer: The standard C++ library uses no uppercase letters at all, and it uses
underscores to make names more readable (bad_cast, push_back). There is nothing
wrong with mixed case (getSeconds, readInt); I just wanted to be consistent.
void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d",a[i]) ;
}
Ans: The output for the above code would be a garbage value. In the statement a[i]
= i++; the value of the variable i 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 been
initialized, a[i] will have a garbage value.
-----------------------------------------------------------------------------------------------
--
2. Why doesn't the following code give the desired result?
-----------------------------------------------------------------------------------------------
--
3. Why doesn't the following statement work?
-----------------------------------------------------------------------------------------------
--
4. How do I know how many elements an array can hold?
Ans: The amount of memory an array can consume depends on the data type of an
array. In DOS environment, the amount of memory an array can consume depends
on the current memory model (i.e. Tiny, Small, Large, Huge, etc.). In general an
array cannot consume more than 64 kb. Consider following program, which shows
the maximum number of elements an array of type int, float and char can have in
case of Small memory model.
main( )
{
int i[32767] ;
float f[16383] ;
char s[65535] ;
}
-----------------------------------------------------------------------------------------------
--
Ans: Use peekb( ) function. This function returns byte(s) read from specific segment
and offset locations in memory. The following program illustrates use of this function.
In this program from VDU memory we have read characters and its attributes of the
first row. The information stored in file is then further read and displayed using peek(
) function.
#include <stdio.h>
#include <dos.h>
main( )
{
fclose ( fp ) ;
6.
How do I compare character data stored at two different memory locations?
#include <mem.h>
main( )
{
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ;
int c ;
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memcmp are identical" ) ;
else
printf ( "\nStrings arr1 and arr2 compared using memcmp are not identical"
);
if ( c == 0 )
printf ( "\nStrings arr1 and arr2 compared using memicmp are identical" )
;
else
printf ( "\nStrings arr1 and arr2 compared using memicmp are not
identical" ) ;
}
-----------------------------------------------------------------------------------------------
--
7.
Fixed-size objects are more appropriate as compared to variable size data objects.
Using variable-size data objects saves very little space. Variable size data objects
usually have some overhead. Manipulation of fixed-size data objects is usually faster
and easier. Use fixed size when maximum size is clearly bounded and close to
average. And use variable-size data objects when a few of the data items are bigger
than the average size. For example,
The first form uses variable-size data objects. It allocates 10 pointers, which are
pointing to 10 string constants of variable size. Assuming each pointer is of 4 bytes,
it requires 90 bytes. On the other hand, the second form uses fixed size data
objects. It allocates 10 arrays of 6 characters each. It requires only 60 bytes of
space. So, the variable-size in this case does not offer any advantage over fixed size.
-----------------------------------------------------------------------------------------------
--
8.
DOS is a single tasking operating system, thus only one 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 parent process
and the second program that gets called from within the first program is called a
child process. Once the second program starts execution, the first is put on hold until
the second program completes execution. The first program is then restarted. The
following program demonstrates use of spawnl( ) function.
/* Mult.c */
/* Spawn.c */
#include <process.h>
#include <stdio.h>
main( )
{
int val ;
val = spawnl ( P_WAIT, "C:\\Mult.exe", "3", "10",
"20", NULL ) ;
printf ( "\nReturned value is: %d", val ) ;
}
Here, there are two programs. The program 'Mult.exe' works as a child process
whereas 'Spawn.exe' works as a parent process. On execution of 'Spawn.exe' it
invokes 'Mult.exe' and passes the command-line arguments to it. 'Mult.exe' in turn
on execution, calculates the product of 10 and 20 and returns the value to val in
'Spawn.exe'. In our call to spawnl( ) function, we have passed 6 parameters, P_WAIT
as the mode of execution, path of '.exe' file to run as child process, total number of
arguments to be passed to the child process, list of command line arguments and
NULL. P_WAIT will cause our application to freeze execution until the child process
has completed its execution. This parameter needs to be passed as the default
parameter if you are working under DOS. under other operating systems that
support multitasking, this parameter can be P_NOWAIT or P_OVERLAY. P_NOWAIT
will cause the parent process to execute along with the child process, P_OVERLAY will
load the child process on top of the parent process in the memory.
-----------------------------------------------------------------------------------------------
--
9.
11.
How do I write code to retrieve current date and time from the system and display it
as a string?
Ans: Use time( ) function to get current date and time and then ctime( ) function to
display it as a string. This is shown in following code snippet.
#include <sys\types.h>
void main( )
{
time_t curtime ;
char ctm[50] ;
-----------------------------------------------------------------------------------------------
--
12.
Ans: We can change the cursor type by using function _setcursortype( ). This
function can change the cursor type to solid cursor and can even hide a cursor.
Following code shows how to change the cursor type and hide cursor.
#include <conio.h>
main( )
{
/* Hide cursor */
_setcursortype ( _NOCURSOR ) ;
How do I write code that would get error number and display error message
if any standard error occurs?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
main( )
{
char *errmsg ;
FILE *fp ;
fp = fopen ( "C:\file.txt", "r" ) ;
if ( fp == NULL )
{
errmsg = strerror ( errno ) ;
printf ( "\n%s", errmsg ) ;
}
}
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 value (in this case 2) related to the error
generated would get set in errno. errno is an external int variable declared in
'stdlib.h' and also in 'errno.h'. Next, we have called sterror( ) function which takes an
error number and returns a pointer to standard error message related to the given
error number.
-----------------------------------------------------------------------------------------------
--
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 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 integer
indicating the drive to be set. Following program demonstrates use of both the
functions.
#include <dir.h>
main( )
{
int dno, maxdr ;
dno = getdisk( ) ;
printf ( "\nThe current drive is: %c\n", 65 + dno
);
maxdr = setdisk ( 3 ) ;
dno = getdisk( ) ;
printf ( "\nNow the current drive is: %c\n", 65 +
dno ) ;
}
-----------------------------------------------------------------------------------------------
--
15.
The functions memcmp( ) and memicmp( ) compares first n bytes of given two
blocks of memory or strings. However, memcmp( ) performs comparison as unsigned
chars whereas memicmp( ) performs comparison as chars but ignores case (i.e.
upper or lower case). Both the functions return an integer value where 0 indicates
that two memory buffers compared are identical. If the value returned is greater
than 0 then it indicates that the first buffer is bigger than the second one. The value
less than 0 indicate that the first buffer is less than the second buffer. The following
code snippet demonstrates use of both
#include <stdio.h>
#include <mem.h>
main( )
{
char str1[] = "This string contains some
characters" ;
char str2[] = "this string contains" ;
int result ;
show ( int r )
{
if ( r == 0 )
printf ( "\nThe buffer str1 and str2 hold
identical data" ) ;
if ( r > 0 )
printf ( "\nThe buffer str1 is bigger than buffer
str2" ) ;
if ( r < 0 )
printf ( "\nThe buffer str1 is less than buffer
str2" ) ;
}
-----------------------------------------------------------------------------------------------
--
16.
#include <stdio.h>
#include <stdlib.h>
#include <dir.h>
#include <dos.h>
main( )
{
int dr ; struct dfree disk ;
long freesp ;
dr = getdisk( ) ;
getdfree ( dr + 1 , &disk ) ;
if ( disk.df_sclus == 0xFFFF )
{
printf ( "\ngetdfree( ) function failed\n");
exit ( 1 ) ;
}
17.
switch ( color )
{
case 0 :
ch = 'R' ;
break ;
case 1 :
ch = 'G' ;
break ;
case 2 :
ch = 'B' ;
break ;
}
In place of switch-case we can make use of the value in color as an index for a
character array. How to do this is shown in following code snippet.
#include <stdio.h>
#include <stdlib.h>
void fun1( )
{
printf("Inside fun1\n");
}
void fun2( )
{
printf("Inside fun2\n");
}
main( )
{
atexit ( fun1 ) ;
/* some code */
atexit ( fun2 ) ;
printf ( "This is the last statement of
program?\n" );
}
-----------------------------------------------------------------------------------------------
--
19.
20.
Ans: The malloc( ) / free( ) implementation remembers the size of each block
allocated and returned, so it is not necessary to remind it of the size when freeing.
-----------------------------------------------------------------------------------------------
--
21.
-----------------------------------------------------------------------------------------------
--
22.
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 of unused
memory between the top of the heap and stack. If we are using a larger model, this
function returns the amount of memory between the highest allocated memory and
the end of conventional memory. The function returns amount of memory in terms of
bytes.
-----------------------------------------------------------------------------------------------
--
23.
24.
When we open a file, how does functions like fread( )/fwrite( ), etc. get to
know from where to read or to write the data?
Ans: When we open a file for read/write operation using function like fopen( ), it
returns a pointer to the structure of type FILE. This structure stores the file pointer
called position pointer, which keeps track of current location within the file. On
opening file for read/write operation, the file pointer is set to the start of the file.
Each time we read/write a character, the position pointer advances one character. If
we read one line of text at a step from the file, then file pointer advances to the start
of the next line. If the file is opened in append mode, the file pointer is placed at the
very end of the file. Using fseek( ) function we can set the file pointer to some other
place within the file.
-----------------------------------------------------------------------------------------------
--
25.
The sizeof( ) function doesn’t return the size of the block of memory pointed
to by a pointer. Why?
Ans: The sizeof( ) operator does not know that malloc( ) has 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( ).
27.
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 when we use DOS and BIOS services in a program we need to
know the segment register's value. In such a situation we can use segread( )
function. The following program illustrates the use of this function.
#include <dos.h>
main( )
{
struct SREGS s ;
segread ( &s ) ;
printf ( "\nCS: %X DS: %X SS: %X ES: %X",s.cs,
s.ds, s.ss, s.es ) ;
}
-----------------------------------------------------------------------------------------------
--
29.
main( )
{
char *path = NULL ;
path = getenv ( "PATH" ) ;
if ( *path != NULL )
printf ( "\nPath: %s", path ) ;
else
printf ( "\nPath is not set" ) ;
}
-----------------------------------------------------------------------------------------------
--
30.
#include <stdio.h>
#include <time.h>
main( )
{
struct tm *curtime ;
time_t dtime ;
char str[30] ;
time ( &dtime ) ;
curtime = localtime ( &dtime ) ;
strftime ( str, 30, "%A %B %d, %Y", curtime ) ;
36.
What is a stack ?
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 completes, C removes the
items from the stack. Similarly, when a function declares local variables, C stores the
variable's values on the stack during the function's execution. Depending on the
program's use of functions and parameters, the amount of stack space that a
program requires will differ.
-----------------------------------------------------------------------------------------------
--
37.
Allocating memory for a 3-D array
#include "alloc.h"
#define MAXX 3
#define MAXY 4
#define MAXZ 5
main( )
{
int ***p, i, j, k ;
p = ( int *** ) malloc ( MAXX * sizeof ( int ** ) ) ;
for ( i = 0 ; i < MAXX ; i++ )
{
p[i] = ( int ** ) malloc ( MAXY * sizeof ( int * ) ) ;
for ( j = 0 ; j < MAXY ; j++ )
p[i][j] = ( int * ) malloc ( MAXZ * sizeof ( int ) ) ;
}
for ( k = 0 ; k < MAXZ ; k++ )
{
for ( i = 0 ; i < MAXX ; i++ )
{
for ( j = 0 ; j < MAXY ; j++ )
{
p[i][j][k] = i + j + k ;
printf ( "%d ", p[i][j][k] ) ;
}
printf ( "\n" ) ;
}
printf ( "\n\n" ) ;
}
}
Data Structures
How to distinguish between a binary tree and a tree?
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 have at most two branches. For binary trees we
distinguish between the subtree on the left and subtree on the right, whereas for
trees the order of the subtrees is irrelevant.
Consider the following figure...
This above figure shows two binary trees, but these binary trees are different. The
first has an empty right subtree while the second has an empty left subtree. If the
above are regarded as trees (not the binary trees), then they are same despite the
fact that they are drawn differently. Also, an empty binary tree can exist, but there is
no tree having zero nodes.
-----------------------------------------------------------------------------------------------
--
38.
How do I use the function ldexp( ) in a program?
Ans: The math function ldexp( ) is used while solving the 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 ( 2, exp ) )
where n is the double value and exp is the integer. The following program
demonstrates the use of this function.
#include <stdio.h>
#include <math.h>
void main( )
{
double ans ;
double n = 4 ;
ans = ldexp ( n, 2 ) ;
printf ( "\nThe ldexp value is : %lf\n", ans ) ;
}
Here, ldexp( ) function would get expanded as ( 4 * 2 * 2 ), and the output would be
the ldexp value is : 16.000000
-----------------------------------------------------------------------------------------------
--
39.
Can we get the mantissa and exponent form of a given number?
Ans: The function frexp( ) splits the given number into a mantissa and exponent
form. The function takes two arguments, the number to be converted as a double
value and an int to store the exponent form. The function returns the mantissa part
as a double value. Following example demonstrates the use of this function.
#include <math.h>
#include <stdio.h>
void main( )
{
double mantissa, number ;
int exponent ;
number = 8.0 ;
mantissa = frexp ( number, &exponent ) ;
return 0 ;
}
-----------------------------------------------------------------------------------------------
--
40.
#include <stdlib.h>
main( )
{
int ch ;
void fun ( void ) ;
atexit ( fun ) ;
// code
}
void fun( void )
{
printf ( "\nTerminate program......" ) ;
getch( ) ;
}
-----------------------------------------------------------------------------------------------
--
41.
What are memory models?
Ans: The compiler uses a memory model to determine how much memory is
allocated to the program. The PC divides memory into blocks called segments of size
64 KB. Usually, program uses one segment for code and a second segment for data.
A memory model defines the number of segments the compiler can use for each. It
is important to know which memory model can be used for a program. If we use
wrong memory model, the program might not have enough memory to execute. The
problem can be solved using larger memory model. However, larger the memory
model, slower is your program execution. So we must choose the smallest memory
model that satisfies our program needs. Most of the compilers support memory
models like tiny, small, medium, compact, large and huge.
42.
How does C compiler store elements in a multi-dimensional array?
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]
-----------------------------------------------------------------------------------------------
--
43.
( ( i < 10 ) ? j : k ) = l * 2 + p ;
Ans: No! The above statement is invalid. We cannot use the conditional operators in
this fashion. The conditional operators like most operators, yields a value, and we
cannot assign the value of an _expression to a value. However, we can use
conditional operators as shown in following code snippet.
main( )
{
int i, j, k, l ;
i = 5 ; j = 10 ; k = 12, l = 1 ;
* ( ( i < 10 ) ? &j : &k ) = l * 2 + 14 ;
printf ( "i = %d j = %d k = %d l = %d", i, j, k, l ) ;
}
Ans: The following code snippet shows how to get the day of week from the given
date.
void main( )
{
printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 ) ) ;
}
-----------------------------------------------------------------------------------------------
--
45.
main( ) has the third command line argument env, which is an array of pointers to
the strings. Each pointer points to an environment variable from the list of
environment variables.
-----------------------------------------------------------------------------------------------
--
47.
div( )...
The function div( ) divides two integers and returns the quotient and remainder. This
function takes two integer values as arguments; divides first integer with the second
one and returns the answer of division of type div_t. The data type div_t is a
structure that contains two long ints, namely quot and rem, which store quotient and
remainder of division respectively. The following example shows the use of div( )
function.
#include <stdlib.h>
void main( )
{
div_t res ;
48.
What would the second and the third printf( ) output the following program?
main( )
{
char *str[ ] = {
"Good Morning"
"Good Evening"
"Good Afternoon"
};
printf ( "\nFirst string = %s", str[0] ) ;
printf ( "\nSecond string = %s", str[1] ) ;
printf ( "\nThird string = %s", str[2] ) ;
}
Ans: For the above given program, we expect the output as Good Evening and Good
Afternoon, for the second and third printf( ). However, the output would be as shown
below.
The suppression character * suppresses the input read from the standard input
buffer for the assigned control character.
-----------------------------------------------------------------------------------------------
--
50.
Ans: This can be achieved through the use of suppression char '*' in the format
string of printf( ) as shown in the following program.
main( )
{
int i = 2 ;
float f = 23.34568734 ;
printf ( "%.*f", i, f ) ;
}
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 pointed by it, whereas
++*ptr increments the value being pointed to by ptr.
-----------------------------------------------------------------------------------------------
--
52.
strpbrk( )
The function strpbrk( ) takes two strings as parameters. It scans the first string, to
find, the first occurrence of any character appearing in the second string. The
function returns a pointer to the first occurrence of the character it found in the first
string. The following program demonstrates the use of string function strpbrk( ).
#include <string.h>
main( )
{
char *str1 = "Hello!" ;
char *str2 = "Better" ;
char *p ;
p = strpbrk ( str1, str2 ) ;
if ( p )
printf ( "The first character found in str1 is %c", *p ) ;
else
printf ( "The character not found" ) ;
}
The output of the above program would be the first character found in str1 is e
53.
Ans: The function ultoa( ) can be used to convert an unsigned long integer value to a
string. This function takes three arguments, first the value that is to be converted,
second the base address of the buffer in which the converted number has to be
stored (with a string terminating null character '\0') and the last argument specifies
the base to be used in converting the value. Following example demonstrates the use
of this function.
#include <stdlib.h>
void main( )
{
unsigned long ul = 3234567231L ;
char str[25] ;
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 and
returns the largest possible integer to which the given double value can be rounded
down. The following program demonstrates the use of both the functions.
#include <math.h>
void main( )
{
double no = 1437.23167 ;
double down, up ;
down = floor ( no ) ;
up = ceil ( no ) ;
Ans: The function ecvt( ) converts a floating-point value to a null terminated string.
This function takes four arguments, such as, the value to be converted to string, the
number of digits to be converted to string, and two integer pointers. The two-integer
pointer stores the position of the decimal point (relative to the string) and the sign of
the number, respectively. If the value in a variable, used to store sign is 0, then the
number is positive and, if it is non-zero, then the number is negative. The function
returns a pointer to the string containing digits. Following program demonstrates the
use of this function.
#include <stdlib.h>
main( )
{
char *str ;
double val ;
int dec, sign ;
int ndig = 4 ;
val = 22 ;
str = ecvt ( val, ndig, &dec, &sign ) ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;
val = -345.67 ;
ndig = 8 ;
str = ecvt ( val, ndig, &dec, &sign ) ;
printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ;
-----------------------------------------------------------------------------------------------
--
56.
Ans: We can use the system( ) function to execute the DIR command along with its
options. Following program shows how this can be achieved:
// mydir.c
if ( argc < 2 )
exit ( 0 ) ;
If we run the executable file of this program at command prompt passing the
command line arguments as follows:
Suppose I have a structure having fields name, age, salary and have passed
address of age to a function fun( ). How I can access the other member of
the structure using the address of age?
Ans:
struct emp
{
58.
How to restrict the program's output to a specific screen region?
Ans: A C function window( ) can be used to restrict the screen output to a specific
region. The window( ) function defines a text-mode window. The parameters passed
to this function defines the upper-left and lower-right corner of the 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 which
prints directly on the text-mode window.
#include <conio.h>
main( )
{
int i, j ;
Sometimes you need to prompt the user for a password. When the user
types in the password, the characters the user 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.
main( )
{
char *pwd ;
Ans: We can use the function _getdrive( ) to obtain the current drive. The _getdrive(
) function uses DOS function 0X19 to get the current drive number
#include <direct.h>
main( )
{
int disk ;
disk = _getdrive( ) + 'A' - 1 ;
printf ( "The current drive is: %c\n", disk ) ;
}
-----------------------------------------------------------------------------------------------
--
61.
How come the output for both the programs is different when the logic is
same?
main( )
{
int i, j ;
main( )
{
int i, j ;
Output -> 5 5
Even if logic of both the programs is same the output of the first program comes out
to be 100, 100, but of the second program it is 5, 5. The comma operator plays a
vital role inside the for loop. It always considers the value of the latest variable. So,
at the time of testing the condition in for loop, the value of j will be considered in the
first program and value of i in the second.
-----------------------------------------------------------------------------------------------
--
62.
Can we get the x and y coordinate of the current cursor position ?
Ans : The function wherex( ) and wherey( ) returns the x-coordinate and y-
coordinate of the current cursor position respectively. Both the functions return an
integer value. The value returned by wherex( ) is the horizontal position of cursor
and the value returned by wherey( ) is the vertical position of the cursor. Following
program shows how to use the wherex( ) and wherey( ) functions.
#include <conio.h>
main( )
{
printf ( "Just\n To\n Test\n Where\n the cursor\n goes" ) ;
printf ( "Current location is X: %d Y: %d\n", wherex( ), wherey( ) ) ;
}
63.
How do I programmatically delete lines in the text window?
Ans: While writing programs that perform screen-based I/O, you may want to-delete
the current line's contents, moving one line up, all of the output that follows. In such
cases a function called delline( ) can be used. Following code snippet illustrates the
use of function delline( ).
#include <conio.h>
main( )
{
int i ;
clrscr( ) ;
gotoxy ( 2, 6 ) ;
getch( ) ;
}
-----------------------------------------------------------------------------------------------
--
64.
Ans: The function difftime( ) finds the difference between two times. It calculates the
elapsed time in seconds and returns the difference between two times as a double
value.
#include <time.h>
#include <stdio.h>
#include <dos.h>
main( )
{
int a[] = { 2, -34, 56, 78, 112, 33, -7, 11, 45, 29, 6 } ;
int s ;
time_t t1, t2 ; // time_t defines the value used for time function
s = sizeof ( a ) / 2 ;
t1 = time ( NULL ) ;
sel_sort ( a, s ) ; // sort array by selection sort
bub_sort ( a, s ) ; // sort array by bubble sort method
t2 = time ( NULL ) ;
printf ( "\nThe difference between two function calls is %f", difftime (
t2, t1 ) ) ;
}
In the above program we have called difftime( ) function that returns the time
elapsed from t1 to t2.
-----------------------------------------------------------------------------------------------
--
65.
Ans: The function swab( ) swaps the adjacent bytes of memory. It copies the bytes
from source string to the target string, provided that the number of characters in the
source string is even. While copying, it swaps the bytes which are then assigned to
the target string.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
main ( )
{
char *str1 = "hS eesll snsiasl not eh es as oher " ;
char *str2 ;
clrscr( ) ;
swab ( str1, str2, strlen ( str1 ) ) ;
printf ( "The target string is : %s\n", str2 ) ; // output -- She sells
snails on the sea shore
getch( ) ;
}
-----------------------------------------------------------------------------------------------
--
66.
Turbo C provides various command line compiler options which we can use through
TCC. The compiler options include : displaying specific warning messages, generating
8087 hardware instructions, using a filename for generating assembly code, etc.
Instead of compiler options being executed at command line we can use these
compiler options in our program. This can be achieved using #pragma options. We
can use various flags with #pragma options to use the compiler options. All these
flags are available in turbo C's online help.
-----------------------------------------------------------------------------------------------
--
67.
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 array that is defined in another file. You have three ways to resolve this
problem:
1. In file 'F1.C' define as,
int a[ ] = { 1, 2, 3, 4, 5, 6 } ;
int size_a = sizeof ( a ) ;
and in file F2.C declare as,
extern int a[ ] ;
extern int size_a ;
#define ARR_SIZ 6
In file F1.C declare as,
#include "F1.H"
int a[ ARR_SIZ ] ;
and in file F2.C declare as,
#include "F1.H"
extern int a[ ARR_SIZ ] ;
3. In file 'F1.C' define as,
int a[ ] = { 1, 2, 3, 4, 5, 6, -1 } ;
extern int a[ ] ;
Here the element -1 is used as a sentinel value, so the code can
understand the end without any explicit size.
char name[20] ;
int age ;
float salary ;
};
main( )
{
struct emp e ;
printf ( "\nEnter name: " ) ;
scanf ( "%s", e.name ) ;
printf ( "\nEnter age: " ) ;
scanf ( "%d", &e.age ) ;
printf ( "\nEnter salary: " ) ;
scanf ( "%f", &e.salary ) ;
fun ( &e.age ) ;
}
fun ( int *p )
{
struct emp *q ;
int offset ;
offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char * ) ( (
struct emp* ) 0 ) ;
q = ( struct emp * ) ( ( char * ) p - offset ) ;
printf ( "\nname: %s", q -> name ) ;
printf ( "\nage: %d", q -> age ) ;
printf ( "\nsalary: %f", q -> salary ) ;
}
68.
Ans: Sometimes, specially when we are creating a text editor like program we may
wish to allow user to delete a line. We can do so by using two functions namely
clreol( ) and delline( ). The clreol( ) function deletes the line from the current cursor
position to the end of line. The delline() function deletes the entire line at the current
cursor position and
moves up the following line. Following program shows how to use these functions.
#include <conio.h>
main( )
{
int i ;
getch( ) ;
gotoxy ( 1, 7 ) ;
clreol( ) ;
getch( ) ;
gotoxy ( 1, 12 ) ;
delline( ) ;
getch( ) ;
}
-----------------------------------------------------------------------------------------------
--
69.
How do I programmatically insert lines in the text window?
Ans: We can insert a blank line in the text window using the insline( ) function. This
function inserts line at current cursor position. While doing so, it shifts down the lines
that are below the newly inserted line.
#include <conio.h>
void main( )
{
printf ( "The little snail was slowly moving up. She wanted\r\n" ) ;
printf ( "to reach the top of the tree. It was chilly\r\n" ) ;
printf ( "winter season. Most of the animals were resting in\r\n" ) ;
printf ( "their nests as there was a heavy snow fall.\r\n" ) ;
printf ( "\r\nPress any key to continue:" ) ;
gotoxy ( 10, 2 ) ;
getch( ) ;
insline( ) ;
getch( ) ;
}
-----------------------------------------------------------------------------------------------
--
70.
main( )
{
unsigned int num ;
int i ;
Ans: The output of this program is the binary equivalent of the given number. We
have used bitwise operators to get the binary number.
What is Polymorphism
C++ Templates allow u to generate families of functions or classes that can operate
on a variety of different data types, freeing you from the need to create a separate
function or class for each type. Using templates, u have the convenience of writing a
single generic function or class definition, which the compiler automatically translates
into a specific version of the function or class, for each of the different data types
that your program actually uses. Many data structures and algorithms can be defined
independently of the type of data they work with. You can increase the amount of
shared code by separating data-dependent portions from data-independent portions,
and templates were introduced to help you do that.
What is the difference between run time binding and compile time binding?
Dynamic Binding :
The address of the functions are determined at runtime rather than @ compile time.
This is also known as "Late Binding".
Static Binding :
The address of the functions are determined at compile time rather than @ run time.
This is also known as "Early Binding"
void main ()
{ int i = 0 , a[3] ;
a[i] = i++;
printf (“%d",a[i]) ;
The output for the above code would be a garbage value. In the statement a[i] =
i++; the value of the variable i 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 been initialized,
a[i] will have a garbage value.
Ans: No. The virtual function mechanism is used on the specific object that
determines which virtual function to call. Since the static functions are not any way
related to objects, they cannot be declared as virtual.
-----------------------------------------------------------------------------------------------
--
2.
#include
class test
{
int i ;
public :
test ( int ii = 0 )
{
i = ii ;
}
};
class sample
{
static test s ;
};
test sample::s ( 26 ) ;
-----------------------------------------------------------------------------------------------
--
3.
class sample
{
public :
friend void fun ( sample, test ) ;
};
void main( )
{
sample s ;
test t ;
fun ( s, t ) ;
}
This program would not compile. It gives an error that sample is undeclared identifier
in the statement friend void fun ( sample, test ) ; of the class test. This is so because
the class sample is defined below the class test and we are using it
before its definition. To overcome this error we need to give forward reference of
the class sample before the definition of class test. The following
statement is the forward reference of class sample. Forward
referencing is generally required when we make a class or a function as a friend.
-----------------------------------------------------------------------------------------------
--
4.
The istream_withassign class has been derived from the istream class and
overloaded assignment operator has been added to it. The
_withassign classes are much like their base classes except that
they include overloaded assignment operators. Using these operators the objects of
the _withassign classes can be copied. The istream, ostream,
and iostream classes are made uncopyable by making their
overloaded copy constructor and assignment operators private.
-----------------------------------------------------------------------------------------------
--
5.
How do I write my own zero-argument manipulator that should work same as hex?
#include
o.setf ( ios::hex) ;
return o ;
void main( )
{
}
-----------------------------------------------------------------------------------------------
--
6.
We all know that a const variable needs to be initialized at the time of declaration.
Then how come the program given below runs properly even when we have not
initialized p?
#include
void main( )
{
const char *p ;
p = "A const pointer" ;
cout << p ;
}
Ans: The output of the above program is 'A const pointer'. 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
-----------------------------------------------------------------------------------------------
--
7.
Ans: There are two ways in which we can refer to a name of class or function that is
defined within a namespace: Using scope resolution operator
through the using keyword. This is shown in following example:
namespace name1
{
class sample1
{
// code
};
}
namespace name2
{
class sample2
{
// code
};
}
using namespace name2 ;
void main( )
{
name1::sample1 s1 ;
sample2 s2 ;
}
Here, class sample1 is referred using the scope resolution operator. On the other
hand we can 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.
-----------------------------------------------------------------------------------------------
--
8.
void main( )
{
sample s1, s2, s3 ;
s3 = s1 + ; // error
}
-----------------------------------------------------------------------------------------------
--
9.
How do I carry out conversion of one object of user-defined type to another?
#include
class sample
{
static sample *ptr ;
private:
sample( )
{
}
public:
static sample* create( )
{
if ( ptr == NULL )
ptr = new sample ;
return ptr ;
}
};
sample *sample::ptr = NULL ;
void main( )
{
sample *a = sample::create( ) ;
sample *b = sample::create( ) ;
}
Here, the class sample contains a static data member ptr, which is a pointer to the
object of same class. The constructor is private which avoids us
from creating objects outside the class. A static 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 address is returned.
Thus, in main( ) on execution of the first statement one object of sample gets
created whereas on execution of second statement, b holds the
address of the first object. Thus, whatever number of times you call create( )
function, only one object of sample class will be available.
11.
How do I write code to add functions, which would work as get and put properties of
a class?
class sample
{
int data ;
public:
__declspec ( property ( put = fun1, get = fun2 ) )
int x ;
void fun1 ( int i )
{
if ( i < 0 )
data = 0 ;
else
data = i ;
}
int fun2( )
{
return data ;
}
};
void main( )
{
sample a ;
a.x = -99 ;
cout << a.x ;
}
Here, the function fun1( ) of class sample is used to set the given integer value into
data, whereas fun2( ) returns the current value of data. To set these functions as
properties of a class we have given the statement as shown below:
__declspec ( property ( put = fun1, get = fun2 )) int x ;
As a result, the statement a.x = -99 ; would cause fun1( ) to get called to set the
value in data. On the other hand, the last statement would cause fun2( ) to get
called to return the value of data.
-----------------------------------------------------------------------------------------------
--
12.
#include
class emp
{
public :
int a[3][3] ;
emp( )
{
int c = 1 ;
for ( int i = 0 ; i <= 2 ; i++ )
{
for ( int j = 0 ; j <= 2 ; j++ )
{
a[i][j] = c ;
c++ ;
}
}
}
void main( )
{
emp e ;
cout << e[0][1] ;
}
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] ; would get converted into a call to the overloaded [ ] function as
e.operator[ ] ( 0 ). 0 would get collected in i. The function would return a[i] that
represents the base address of the zeroeth row. Next the statement would get
expanded as base address of zeroeth row[1] that can be further expanded as *(
base address + 1 ). This gives us a value in zeroth row
13.
What are formatting flags in ios class?
Ans: The ios class contains formatting flags that help users to format the stream
data. Formatting flags are a set of enum definitions. There are two types of
formatting flags:
On/Off flags
Flags that work in-group
The On/Off flags are turned on using the setf( ) function and are turned off using the
unsetf( ) function. To set the On/Off flags, the one argument setf( ) function is used.
The flags working in groups are set through the two-argument setf( ) function. For
example, to left justify a string we can set the flag as,
cout.setf ( ios::left ) ;
cout << "KICIT Nagpur" ;
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, showpoint, uppercase,
showpos, unitbuf and stdio. The flags that work in a group can have only one of
these flags set at a time.
-----------------------------------------------------------------------------------------------
--
14.
What is the purpose of ios::basefield in the following statement?
Ans: Yes! The ios::flags( ) member function gives the value format flags. This
function takes no arguments and returns a long ( typedefed to fmtflags) that
contains the current format flags.
-----------------------------------------------------------------------------------------------
--
16.
Is there any function that can skip certain number of characters present in the input
stream?
Ans: Yes! This can be done using cin::ignore( ) function. The prototype of this
function is as shown below:
istream& ignore ( int n = 1, int d =EOF ) ;
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
passed to the next input and may pose problem.
To get rid of such extra characters the cin::ignore( ) function is used. This is
equivalent to fflush ( stdin ) used in C language. This function ignores the first n
characters (if present) in the input stream, stops if delimiter d is encountered.
-----------------------------------------------------------------------------------------------
--
17.
Write a program that implements a date class containing day, month and year as
data members. Implement assignment operator and copy constructor in this class.
// copy constructor
date ( date &d )
{
day = d.day ;
month = d.month ;
year = d.year ;
}
void main( )
{
date d1 ( 25, 9, 1979 ) ;
date d2 = d1 ;
date d3 ;
d3 = d2 ;
d3.display( ) ;
}