Sunday 5 December 2010

C Interview Questions Part 16

C interview question: What is C language?
Answer: The C programming language is a standardized programming language developed in the early 1970s by Ken Thompson and Dennis Ritchie for use on the UNIX operating system. It has since spread to many other operating systems, and is one of the most widely used programming languages. C is prized for its efficiency, and is the most popular programming language for writing system software, though it is also used for writing applications.

C interview question: Inprintf() Function What is the output of printf("%d")?
Answer:1. When we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after �%d� so compiler will show in output window garbage value.
2. When we use %d the compiler internally uses it to access the argument in the stack (argument stack). Ideally compiler determines the offset of the data variable depending on the format specification string. Now when we write printf("%d",a) then compiler first accesses the top most element in the argument stack of the printf which is %d and depending on the format string it calculated to offset to the actual data variable in the memory which is to be printed. Now when only %d will be present in the printf then compiler will calculate the correct offset (which will be the offset to access the integer variable) but as the actual data object is to be printed is not present at that memory location so it will print what ever will be the contents of that memory location.
3. Some compilers check the format string and will generate an error without the proper number and type of arguments for things like printf(...) and scanf(...).


C interview question:Why doesn't the following code give the desired result?
Answer: int x = 3000, y = 2000 ;
long int z = x * y ;
Ans: Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:
long int z = ( long int ) x * y ;
Note that ( long int )( x * y ) would not give the desired effect.


C interview question: Why doesn't the following statement work?
char str[ ] = "Hello" ;
strcat ( str, '!' ) ;
Answer: The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, 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:
strcat ( str, "!" ) ;


C interview question:malloc() Function- What is the difference between "calloc(...)" and "malloc(...)"?
Answer:1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).
malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).
2.malloc(...) allocates memory blocks and returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
           calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.

Read more...

C Interview Questions Part 15

C interview question:How do I write code to get the current drive as well as set the current drive?
Answer: 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
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 ) ;
}

C interview question: How do I compare character data stored at two different memory locations?
Answer: Sometimes in a program we require to compare memory ranges containing strings. In such a situation we can use functions like memcmp( ) or memicmp( ). The basic difference between two functions is that memcmp( ) does a case-sensitive comparison whereas memicmp( ) ignores case of characters. Following program illustrates the use of both the functions.

#include
main( )
{
char *arr1 = "Kicit" ;
char *arr2 = "kicitNagpur" ;
int c ;
c = memcmp ( arr1, arr2, sizeof ( arr1 ) ) ;
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") ;
c = memicmp ( arr1, arr2, sizeof ( arr1 ) ) ;
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" ) ;
}

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,

char *num[10] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

Instead of using the above, use
char num[10][6] = { "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten" } ;

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.

Read more...

C Interview Questions Part 14

C interview question:When we open a file, how does functions like fread( )/fwrite( ), etc. get to know from where to read or to write the data?
Answer: 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

C interview question: Explain the use of array indices ?
Answer:If we wish to store a character in a char variable ch and the character to be stored depends on the value of another variable say color (of type int), then the code would be as shown below:

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.
char *str = "RGB' ;
char ch ;
int color ;
// code
ch = str[ color ] ;

 
C interview question:How do I write code that would get error number and display error message if any standard error occurs?
Answer: Following code demonstrates this.
#include
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.

Read more...

C Interview Questions Part 13

C interview question:How do I determine amount of memory currently available for allocating?
Answer: 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.

C interview question:How does a C program come to know about command line arguments?
Answer: 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 tables,environment segment, and command line information. When we compile the C program the compiler inserts additional code that parses the command, assigning it to the argv array, making the arguments easily accessible within our C program.

C interview question:What is environment and how do I get environment for a specific entry?
Answer: While working in DOS, it stores information in a memory region called environment. In this region we can place configuration settings such as command path, system prompt, etc. Sometimes in a program we need to access the information contained in environment. The function getenv( ) can be used when we want to access environment for a specific entry. Following program demonstrates the use of this function.

#include
main( )
{
char *path = NULL ;
path = getenv ( "PATH" ) ;
if ( *path != NULL )
printf ( "\nPath: %s", path ) ;
else
printf ( "\nPath is not set" ) ;
}

C interview question:How do I display current date in the format given below?
Saturday October 12, 2002
Answer: Following program illustrates how we can display date in above given format.

#include
main( )
{
struct tm *curtime ;
time_t dtime ;
char str[30] ;
time ( &dtime ) ;
curtime = localtime ( &dtime ) ;
strftime ( str, 30, "%A %B %d, %Y", curtime ) ;
printf ( "\n%s", str ) ;
}

Here we have called time( ) function which returns current 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 localtime( ). Then we have called strftime( ) function to format the time and store it in a string str.

Read more...

C Interview Questions Part 12

C interview question:Can we get the mantissa and exponent form of a given number?
Answer: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
void main( )
{
double mantissa, number ;
int exponent ;
number = 8.0 ;
mantissa = frexp ( number, &exponent ) ;
printf ( "The number %lf is ", number ) ;
printf ( "%lf times two to the ", mantissa ) ;
printf ( "power of %d\n", exponent ) ;
return 0 ;
}

C interview quesion:What is access( ) function...
Answer:The access( ) function checks for the existence of a file and also determines whether it can be read,written to or executed. This function takes two arguments the filename and an integer indicating the access mode. The values 6, 4, 2, and 1 checks for read/write, read, write and execute permission of a given file, whereas value 0 checks whether the file exists or not. Following program demonstrates how we can use access( ) function to check if a given file exists.

#include
main( )
{
char fname[67] ;
printf ( "\nEnter name of file to open" ) ;
gets ( fname ) ;
if ( access ( fname, 0 ) != 0 )
{
printf ( "\nFile does not exist." ) ;
return ;
}
}

C interview question:How do I convert a floating-point number to a string?
Answer: Use function gcvt( ) to convert a floating-point number to a string. Following program demonstrates the use of this function.
#include
main( )
{
char str[25] ;
float no ;
int dg = 5 ; /* significant digits */
no = 14.3216 ;
gcvt ( no, dg, str ) ;
printf ( "String: %s\n", str ) ;
}

Read more...

C Interview Questions Part 11

C interview question:How can I find the day of the week of a given date?
Answer: The following code snippet shows how to get the day of week from the given date.
dayofweek ( int yy, int mm, int dd )
{
/*Monday = 1 and Sunday = 0 */
/* month number >= 1 and <= 12, yy > 1752 or so */
static int arr[ ] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 } ;
yy = yy - mm < 3 ;
return ( yy + yy / 4 - yy / 100 + yy / 400 + arr[ mm - 1] + dd ) % 7 ;
}
void main( )
{
printf ( "\n\n\nDay of week : %d ", dayofweek ( 2002, 5, 18 ) ) ;
}

C interview question:What's the difference between these two declarations?
struct str1 { ... } ;
typedef struct { ... } str2 ;
Answer : The first form declares a structure tag whereas the second declares a typedef. The main difference is that the second declaration is of a slightly more abstract type -- its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it.

C interview question: How do I print the contents of environment variables?
Answer: The following program shows how to achieve this:
main( int argc, char *argv[ ], char *env[ ] )
{
int i = 0 ;
clrscr( ) ;
while ( env[ i ] )
printf ( "\n%s", env[ i++ ] ) ;
}
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.

C interview question:How do I use the function ldexp( ) in a program?
Answer: 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
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

Read more...

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP