c language interview questions

38
C 1. What does static variable mean? Static variable : A static local variable exists for the duration of the program, but is only visible in the function body. Static automatic variables continue to exist even after the block in which they are defined terminates. Thus, the value of a static variable in a function is retained between repeated function calls to the same function. 2. What is a pointer? Pointer : A pointer is a variable used to store address of another variable or any memory location. A pointer provides a way of accessing a variable without referring to the variable directly. Syntax: datatype *pvar1,*pvar2… ; 3. What is a structure? Structure : Structures are data structures whose individual elements can differ in type. A single data structure may contain integers, floating points, pointers, arrays as well as other structures. The individual structure elements are referred to as members. Syntax: struct structure _name { data_type member1; data_type member2; ------------ --------------; ------------ --------------; } ; //Semicolon is must & Before semicolon you can declare structure 4. What are the differences between structures and arrays? Differences between structures and arrays : 1. Array elements are homogeneous. Structure elements are of different data type. 2. Array allocates static memory and uses index / subscript for accessing elements of the array. Structures allocate dynamic memory and uses (.) operator for accessing the member of a structure. 3. Array is a pointer to the first element of it. Structure is not a pointer 4. Array element access takes less time in comparison with structures.

Upload: md-suhas

Post on 22-Jul-2016

55 views

Category:

Documents


0 download

DESCRIPTION

C language interview questions

TRANSCRIPT

Page 1: C language  interview questions

“ C ”

1. What does static variable mean?

Static variable :

A static local variable exists for the duration of the program, but is only visible

in the function body. Static automatic variables continue to exist even after the block in

which they are defined terminates. Thus, the value of a static variable in a function is

retained between repeated function calls to the same function.

2. What is a pointer?

Pointer :

A pointer is a variable used to store address of another variable or any memory

location. A pointer provides a way of accessing a variable without referring to the

variable directly.

Syntax: datatype *pvar1,*pvar2… ;

3. What is a structure?

Structure:

Structures are data structures whose individual elements can differ in type. A

single data structure may contain integers, floating points, pointers, arrays as well as

other structures. The individual structure elements are referred to as members.

Syntax: struct structure _name

{

data_type member1;

data_type member2;

------------ --------------;

------------ --------------;

} ; //Semicolon is must & Before semicolon you can declare structure

4. What are the differences between structures and arrays?

Differences between structures and arrays :

1. Array elements are homogeneous. Structure elements are of

different data type.

2. Array allocates static memory and uses index / subscript for

accessing elements of the array. Structures allocate dynamic

memory and uses (.) operator for accessing the member of a

structure.

3. Array is a pointer to the first element of it. Structure is not a pointer

4. Array element access takes less time in comparison with structures.

Page 2: C language  interview questions

5. In header files whether functions are declared or defined?

Whether functions are declared or defined in header files :

Functions and macros are declared in header files. Header files

would be included in source files by the compiler at the time of compilation. Header files

are included in source code using #include directive.#include<some.h> includes all the

declarations present in the header file „some.h‟. A header file may contain declarations of

sub-routines, functions, macros and also variables which we may want to use in our

program. Header files help in reduction of repetitive code.

6. What are the differences between malloc() and calloc()?

Differences between malloc( ) and calloc( ) :

There are two differences. First, is in the number of arguments. Malloc()

takes a single argument (memory required in bytes), while calloc() needs two arguments

(number of variables to allocate memory, size in bytes of a single variable). Secondly,

malloc() does not initialize the memory allocated, while calloc() initializes the allocated

memory to ZERO.

7. What are macros? What are its advantages and disadvantages?

Macros :

Macros are the identifiers that represent statements or expressions. To

associate meaningful identifiers with constants, keywords, and statements or

expressions, #define directive is used.

The advantage of using macro is the execution speed of the program fragment.

When the actual code snippet is to be used, it can be substituted by the name of the

macro. The same block of statements, on the other hand, need to be repeatedly hard

coded as and when required.

The disadvantage of the macro is the size of the program. The reason is, the

pre-processor will replace all the macros in the program by its real definition prior to the

compilation process of the program.

8. Difference between pass by reference and pass by value?

Pass by references and pass by value:

Pass By Reference :

- In Pass by reference address of the variable is passed to a function. Whatever changes

made to the formal parameter will affect to the actual parameters

- Same memory location is used for both variables.(Formal and Actual)-

- it is useful when you required to return more than 1 values

Page 3: C language  interview questions

Pass By Value:

- In this method value of the variable is passed. Changes made to formal will not affect

the actual parameters.

- Different memory locations will be created for both variables.

9. What is static identifier?

Static Identifier :

The static identifier is used for initializing only once, and the value retains during the life

time of the program / application. A separate memory is allocated for „static‟ variables. This

value can be used between function calls. The default value of an uninitialized static variable is

zero. A function can also be defined as a static function, which has the same scope of the static

variable.

10. Where are the auto variables stored?

Auto variable storage :

Main memory and CPU registers are the two memory locations where auto variables are

stored. Auto variables are defined under automatic storage class. They are stored in main

memory. Memory is allocated to an automatic variable when the block which contains it is called

and it is de-allocated at the completion of its block execution.

Auto variables:

Storage : main memory.

Default value : garbage value.

Scope : local to the block in which the variable is defined.

Lifetime : till the control remains within the block in which the variable is defined.

11. Where does global, static, local, register variables, free memory and C Program instructions get stored?

Local/auto variables, which is declared in stack area of memory. A variable prefixed with

register will be stored in registers. Global variables stored in uninitialized data segment

static variables stored in initialized data segment. Free memory (dynamic memory allocations)

will be stored in heap memory (i.e. in data segments). Const variables also stores in text

segments

12. Difference between arrays and linked list?

Differences between arrays and linked list :

Arrays and Linked list both are list data structures used for maintaining a

list of values. Arrays use sequential allocation while Linked list uses linked allocation.

> Linked list uses some extra memory i.e. link pointer.

> Indexing an element, e.g. accessing kth element is cheaper in arrays and costly in Linked list.

Page 4: C language  interview questions

> Insertion and Deletion of elements is a cheaper operation in Linked lists.

> Since nodes in Linked list are dynamically allocated, it has no limitations on growth (apart

from memory constraints).

> Merging Lists is easier in case of Linked lists.

> Breaking a List into two or more lists is easier in case of Linked lists.so Linked list is a better

data structure in most cases. Arrays are goes mostly for static data structures.

13. What are enumerations?

Enumerations :

An enumeration consists of a set of named integer constants. An

enumeration type declaration gives the name of the (optional) enumeration tag and defines the

set of named integer identifiers (called the "enumeration set," "enumerator constants,"

"enumerators," or "members"). A variable with enumeration type stores one of the values of the

enumeration set defined by that type.

Syntax:

enum identifier opt { enumerator-list }

enum identifier

14. Describe about storage allocation and scope of global, extern, static, local and register variables?

Storage allocation and scope of global ,extern ,static ,local and register variables :

The storage allocation / class determine the memory part where the storage space

is allocated for variables, functions and how long the allocation of storage continues to exist.

The scope of a variable is specified by its storage allocation. This is specified by

the keywords – auto, extern, static and register.

- „auto‟ variables stores in the memory storage. Majority of the variables in a program

/ application are of type „auto‟. Their scope might be local or global.

- „extern‟ variables are of global variables and can be declared in another source file

which could be external / outside the current program scope,

- „register‟ variables are allocated in the CPU registers. These variables storage and

accessibility is much faster than other variables, being they are stored in CPU itself. The

variables of repeated usage or access time is critical, can be declared as register variables.

- „static‟ variables provide a lifetime over the program, and provide a way for

limiting the scope of such variables. These variables are automatically initialized to zero and

could be specified for „auto‟ and „extern‟ variables. The values are retained, even though they are

declared in local scope, between the repeated function calls to the same function.

Page 5: C language  interview questions

15. What are register variables? What are the advantage of using register variables?

register variables :

The variables of „register‟ type modifier will inform the compiler for storing the

variables in a register of CPU.

The advantage of this type modifier is the access optimization and speed of program

execution. The operations of these variables are faster by orders of magnitude

16. What is the use of typedef?

typedef :

A typedef declaration is a declaration with typedef as the storage class. The declarator

becomes a new type. You can use typedef declarations to construct shorter or more meaningful

names for types already defined by C or for types that you have declared. Typedef names allow

you to encapsulate implementation details that may change.

typedef is used to define new data type names to make a program more readable to the

programmer.

17. Can we specify variable field width in a scanf() format string? If possible how?

It is possible to specify variable field width in a scanf() format string. By using %s control string.

This character reads a string of variable field width up to the first white space character.

Ex: scanf(“%s”, name); // where name is a character array

18. Out of fgets() and gets() which function is safe to use and why?

The function fgets() function is safer to use. It checks the bounds, i.e., the size of the buffer and

does not cause overflow on the stack to occur. gets() does not check the bounds.

19. Difference between strdup and strcpy?

Differences between strdup and strcpy :

The function strcpy() will not allocate the memory space to copy. A pointer to the string

to copy and a pointer to place to copy it to should be given.

The function strdup() will occupy / grab itself the memory space for copying the string to.

This memory space needs to be freed up later when it is of no use anymore.

20. What is recursion?

Page 6: C language  interview questions

Recursion :

Recursive function is a function which contains a call to itself. Recursive function

allows you to divide your complex problem into identical single simple cases which can handle

easily. This is also a well-known computer programming technique: divide and conquer.

21. Differentiate between a for loop and a while loop? What are it uses?

Differences between a for loop and a while loop :

22 . What are the different storage classes in C?

Storage classes in C :

Storage class defined for a variable determines the accessibility and longevity of the

variable. The accessibility of the variable relates to the portion of the program that has

access to the variable. The longevity of the variable refers to the length of time the

variable exists within the program.

Auto Automatic variable, also called as local variable and it has scope only within the function

block where it is defined.

External

External variable are defined outside any function and memory is set aside for this type of

Page 7: C language  interview questions

variable once it is declared and remained until the end of the program. These variables are

also called global variables.

Static The static automatic variables, as with local variables, are accessible only within the

function in which it is defined. Static automatic variables exist until the program ends in the

same manner as external variables. In order to maintain value between function calls, the

static variable takes its presence.

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

equivalent pointer expression for referring the same element aijkl :

it is a[i][j][k][l]; so in pointer reference:

(*(*(*(*(a+i)+j))+k)+l)

24. What is difference between Structure and Unions?

Differences between Structures and Unions :

1. union allocates the memory equal to the maximum memory required by the

member of the union but structure allocates the memory equal to the total memory required by

the members.

2. In union, one block is used by all the member of the union but in case of structure,

each member have their own memory space.

3. union is best in the environment where memory is less as it shares the memory

allocated.But structure can not implemented in shared memory.

4. As memory is shared,ambiguity are more in union,but less in structure.

5. self referencial union can not be implemented in any datastructure ,but self

referencial structure can be implemented.

25. What the advantages of using Unions?

Advantages of using Unions :

In case of structure each variables have their own storage location whereas for

unions all the variables share a common memory location. In structure all the variables can be

handled at a time but for union only a member can be handled at a time.

26. What are the advantages of using pointers in a program?

Advantages of using Pointers in a program :

1) Function cannot return more than one value. But when the same function can modify

many pointer variables and function as if it is returning more than one variable.

2) In the case of arrays we can decide the size of th array at runtime by allocating the

necessary space.

Page 8: C language  interview questions

27. What is the difference between Strings and Arrays?

Difference between Strings and Arrays :

1. String can hold only char data. Where as an array can hold any data type.

An array size cannot be changed. Where as a string size can be changed if it is a char

pointer

2. The last element of an array is an element of the specific type. The last character of a

string is a null – „\0‟ character.

3. The length of an array is to specified in [] at the time of declaration (except char []).

The length of the string is the number of characters + one (null character).

28. In a header file whether functions are declared or defined?

Refer to Question 5.

29. What is a far pointer? where we use it?

Far pointer:

A far pointer is a 32 bit pointer to an object anywhere in memory. In

order to use it, the compiler must allocate a segment register, load it with the segment portion of

the pointer, and then reference memory using the offset portion of the pointer relative to the

newly loaded segment register. This takes extra instructions and extra time, so it is the slowest

and largest method of accessing memory, but it can access memory that is larger than 64kb,

sometimes, such as when dealing with video memory, a needful thing.

A far pointer contains a 16 bit segment part and a 16 bit offset part. Still,

at any one instant of time, without "touching" segment registers, the program only has access to

four 64kb chunks, or segments of memory. If there is a 100kb object involved, code will need to

be written to consider its segmentation, even with far pointers.

30 . How will you declare an array of three function pointers where each function receives two ints and returns a float?

Declaration for an array of three function pointers where each function receives two ints

and returns a float :

float (*fn[3])(int,int)

31. what is a NULL Pointer? Whether it is same as an uninitialized pointer?

Null Pointer :

An uninitialized pointer is a pointer that has not been assigned a value; it's uninitialized.

The value of an uninitialized pointer is undefined (it could be anything).

A null pointer is simply a pointer that has a value of NULL.

A word of advice: initialize your pointers to NULL.

This allows you to see that the pointer is invalid; to check if an uninitialized pointer is

valid is quite impossible.

32. What is a NULL Macro? What is the difference between a NULL Pointer and a NULL Macro?

Null Macro:

NULL Macro is simply what is defined as 0 in a macro provided by the library

Page 9: C language  interview questions

Difference between Null Pointer and a Null Macro

Both are very different.

NULL macro is

#define NULL 0

it means the macro NULL will be replaced by 0 while preprocessing

But the NULL pointer means it points to nowhere i.e. contains 0.

It contains 0 means it may be dangerous to use such pointer without assigning proper

address to it otherwise NULL pointer may try to access reset address may cause the

program to crash.

33. What does the error 'Null Pointer Assignment' mean and what causes this error?

Null Pointer Assignment Error :

A NULL pointer assignment is a runtime error It occurs due to various reasons one is that ur

program has tried to access an illegal memory location. Illegal location means either the location

is in the operating systems address space or in the other processes memory space. In stdio.h

NULL is defined as 0

So whenever your program tries to access 0th location the operating system kills your

program with runtime assignment error because the 0th location is in the operating systems

address space and operating system doesn‟t allow access to its address space by user program .

34. What is near, far and huge pointers? How many bytes are occupied by them?

Near ,Far and huge Pointers :

Near pointer: Near pointer is 16 bit wide and holds only offset address. This can

point up to 64kb or 0xFFFF offset in a given segment.

int i = 0;

int * i_pointer = &i;

Far pointer: Far pointers are 32 bit wide. It holds both 16bit segment and 16bit

offset address. Thus a far pointer can point any segment and any offset inside that segment.

MK_FP is a compiler macro which takes segment and offset value and constructs a far pointer.

int far * i_pointer = (int far * )MK_FP(0xA000, 0);

i_pointer can have offset from 0 to 0xFFFF.

Thus it can access address range 0xA0000 to 0xAFFFF

Huge pointer: Huge pointers are also far pointers i.e. 32 bit pointer. The difference

is compiler rounds of the offset to zero of a far pointer when offset reaches to 0xFFFF but for

huge pointer it increments the segment thus huge pointer can be increased or decreased

uniformly between any segments and thus can have any value from 0 to 1MB.

char huge * i_pointer = (char huge * )MK_FP(0xA000, 0xFFFF);

In case of far pointer increment of i_pointer will make it round off to 0xA0000

again. But for huge pointer the value will point to next segment i.e. 0xAFFFF + 1 = 0xB0000.

Page 10: C language  interview questions

35. How would you obtain segment and offset addresses from a far address of a memory location?

Pointers to far objects are stored using four bytes (32 bits). The bytes are stored little

endian or low to high order. The first word contains the 14-bit memory offset (bits 14 and 15 are

always 0). The second word contains the page number (or segment number for function

pointers). The memory address is calculated as follows:

Variable Address = (Page * 0x4000L) + Offset

Function Address = (Segment * 0x10000L) + Offset

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

No arr refers to address of array &arr refers address of address of array but compiler treats arr

and & arr, so even you place arr and & arr no error only warnings will be displayed.

37. Does mentioning the array name gives the base address in all the contexts?

yes by mentioning the name of array we get the base address of the array

38. Explain one method to process an entire string as one unit?

Using gets() we can process an entire string as one unit.

39. What is the similarity between a Structure, Union and enumeration?

Similarity between a Structure,Union and enumeration :

Both structures and unions are used to group a number of variables together. But while a

structure enables us to treat as a unite a number of different variables stored at different places in

memory , a union enables us to treat the same space in memory as a number of different

variables . That is , a union is a way for a section of memory to be treated as a variable of one

type on one occasion, and as a different variable, of a different type on other occasion.

An enumerated type (also called enumeration or enum) is a data type consisting of a set of

named values called elements, members or enumerators of the type. The enumerator names are

usually identifiersthat behave as constants in the language. A variable that has been declared as

having an enumerated type can be assigned any of the enumerators as a value.

For example, the four suits in a deck of playing cards may be four enumerators

named CLUB, DIAMOND, HEART, SPADE, belonging to an enumerated type named suit. If a

variable V is declared having suit as its data type, one can assign any of those four values to it.

Page 11: C language  interview questions

You may need to use the code below to declare the structure:

Code:

struct testing

{

public int y,z;

}

testing test = new testing();

You may need to use the code below to declare the class:

Code:

class test

{

int num = 10;

...

}

You may need to use the code below to declare the emum:

Code:

enum colors {red, green, blue, yellow};

40. Can a Structure contain a Pointer to itself?

yes, a structure contain a pointer to itself... thats y its called self referential's strutures....

struct name { int. .... struct name * ptr; };

41. How can we check whether the contents of two structure variables are same or not?

There is no way you can compare the two structure variables.

for Ex:

stucture test a b;

if (a == b) // is wrong we can't compair structure as whole.

The two structure variables need to be of same type.

we can check the equality of two structure variables by comparing them individually.

example::

#include<stdio.h>

#include<conio.h>

struct student

{

Page 12: C language  interview questions

int rno;

char name[20];

float tot;

}a,b;

void main()

{

clrscr();

printf("enter rno,total of student 1");

scanf("%d%f",a.rno,a.total);

printf("

enter the name of student1");

scanf("%s",a.name);

printf("

enter the rno and total of student2");

scanf("%d%f",b.rno,b.total);

printf("

enter the name of student2");

scanf("%s",b.name);

if((a.rno==b.rno)&&(a.name==b.name)&&(a.total==b.total))

printf("

two structure variables are equal");

else

printf("

two structure variables are not equal");

getch();

}

42. How are Structure passing and returning implemented by the complier?

Structure passing and return implementation by the compiler :

Here is the program that illustrates the solution to the above question.

i)accept input through GetEmployeeDetails()

ii)Print the same details through PrintEmployeeDetails()

iii)Modify / Change the details through ModifyEmployeeDetails()

iv)Print the modified values using PrintEmployeeDetails()

#include<stdio.h>

struct Employee

{

int ID;

char *name;

Page 13: C language  interview questions

};

void GetEmployeeDetails(struct Employee *Emp)

{

printf("Enter the ID");

scanf(" d" &Emp->ID);

Emp->name = (char*)malloc(20 * sizeof(char));

fflush(stdin);

printf("nEnter the Name");

gets(Emp->name);

}

void PrintEmployeeDetails(struct Employee Emp)

{

printf("nEmployee ID :: d" Emp.ID);

printf("nEmployee Name :: snn" Emp.name);

}

struct Employee* ModifyEmployeeDetails(struct Employee Emp)

{

printf("Enter the ID");

scanf(" d" &Emp.ID);

Emp.name = (char*)malloc(20 * sizeof(char));

fflush(stdin);

printf("nEnter the Name");

gets(Emp.name);

return &Emp;

}

int main()

{

struct Employee Emp1 *Emp2;

GetEmployeeDetails(&Emp1);

PrintEmployeeDetails(Emp1);

Emp2 = ModifyEmployeeDetails(Emp1);

PrintEmployeeDetails(*Emp2);

system("pause");

}

43. How can we read/write Structures from/to data files?

Read/Write Structures from/to data files :

There 2 function given in C++. They are fread() & fwrite(). Using them we can read & write

structures

from/to data files respectively.

Page 14: C language  interview questions

Basic representation:

fread(&structure, sizeof structure,1,fp);

fread function recieves a pointer to structure and reads the image(memory) of the

structure as a stream of bytes. Sizeof gives the bytes which was occupied by structure.

fwrite(&structure, sizeof structure,1,fp);

fwrite function recieves a pointer to structure and writes the image(memory) of the

structure as a stream of bytes. Sizeof gives the bytes which was occupied by structure.

44. What is the difference between an enumeration and a set of pre-processor # defines? Difference between an enumeration and a set of pre-processor # defines :

It is always better to use enums over #define for this kind of cases. One thing is type safety.

Another one is that when you have a sequence of values you only have to give the beginning of

the sequence in the enum, the other values get consecutive values.

enum {

ONE = 1,

TWO,

THREE,

FOUR

};

instead of

#define ONE 1

#define TWO 2

#define THREE 3

#define FOUR 4

As a side-note, there is still some cases where you may have to use #define (typically for some

kind of macros, if you need to be able to construct an identifier that contains the constant), but

that's kind of macro black magic, and very very rare to be the way to go. If you go to these

extremities you probably should use a C++ template (but if you're stuck with C...).

45. What do the 'c' and 'v' in argc and argv stand for?

In argc c for argument count and in argv v for argument vector .

In C, we can supply arguments to ‟main‟ function. The arguments that we pass to main ( ) at

command prompt are called command line arguments. These arguments are supplied at the

time of invoking the program.The main ( ) function can take arguments as:

Page 15: C language  interview questions

main(int argc, char *argv[]) { }

The first argument argc is known as ‟argument counter‟. It represents the number of

arguments in the command line. The second argument argv is known as ‟argument vector‟. It is

an array of char type pointers that points to the command line arguments. Size of this array will

be equal to the value of argc.

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

The variables argc and argv are local to main

Reason :

Yes why because these variables written in main function only not outside main. These

belong to main block but not to other. So according to my knowledge these command line

arguments are local to main.

47. What is the maximum combined length of command line arguments including the space between adjacent arguments?

The maximum combined length of command line arguments including the space between

adjacent arguments :

Presumably this would be (INT_MAX-1) * SIZE_MAX. That is each argument can presumably

be up to SIZE_MAX chars and there can be INT_MAX - 1 arguments (one being needed for

argv[0] the program name).

Since the actual values of INT_MAX and SIZE_MAX are implementation defined no maximum

can be definitively given ahead of time.

That said one might suspect the hosting OS and/or startup code would provide somewhat more

stringent limits.

48. If we want that any wildcard characters in the command line arguments should be appropriately expanded, are we required to make any special provision? If yes, which?

Yes you have to compile a program like

tcc myprog wildargs.obj

49. Does there exist any way to make the command line arguments available to other functions without passing them as arguments to the function?

You can copy them into global variables in the main() function, then have your other functions

access those global variables. Global variables should generally be avoided, however.

(Or)

Trap the arguments in variables which can be passed to other function.

Page 16: C language  interview questions

50. What are bit fields? What is the use of bit fields in a Structure declaration?

Bit fields and its usuage in structure declaration :

When the storage is at premium it may be necessary to pack several objects into single machine

word one common use is a set of single bit flags in application like compiler symbol tables. A bit

field or field for short is a set of adjacent bits with a single implementation - defined storage unit.

struct {

unsugned int is_keyword : 1;

unsigned is_extern :1;

unsigned is_static : 1 ;

} flags ;

flags.is_extern = flags.is_static = 1 ; to tun this bit on.

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

1101100100111100 conversion

Since this is a 16 bit number,

we can group these bits into 4bits a group each as

(1101)(1001)(0011)(1100)

Hence the given set of bits can be converted to HEXA DECIMAL SYSTEM

As (D93C)

16

52. Which bit wise operator is suitable for checking whether a particular bit is on or off?

Checking whether a particulat bit is on or off :

Its Bitwise AND (&)

for Ex

I need to check if 3rd bit from right(Starting from 0th) is ON in a variable x or OFF.

then see this code:

int x=24;

int tester=1;

tester = tester << 3; \Makes tester as 00001000

if((x&tester)!=1)

printf("3rd bit from left in x is ON");

else

printf("3rd bit from left in x is OFF");

Explaination:

x = 24 i.e. 0001 1000

Page 17: C language  interview questions

tester = 1 i.e. 0000 0001

tester = tester << 3 does:

tester = 8 i.e. 0000 1000

now x&tester i.e.

0001 1000

&&&&&&&&

0000 1000

-------------

0000 1000

which is NON ZERO hence decides that 3rd bit is SET / ON.

if x = 5 (0000 0101)

then x&tester i.e.

00000101 &

00001000

------------

00000000

which is ZERO hence decides that 3rd bit is UNSET / OFF.

In Brief: Bitwise AND is used to CHECK / TEST a particular bit.

Bitwise OR is used to SET (Make it 1) a particular bit.

Bitwise XOR is used to TOGGLE (1to0 or 0to1) a particular bit.

Bitwise AND is also used to RESET a particular bit (if ANDed with 11110111 say I have to

reset 4th bit).

53. Which bit wise operator is suitable for turning off a particular bit in a number?

the bit wise AND operator.

In the following code snippet, the bit number 24 is reset to zero.

some_int = some_int & ~KBit24;

54. Which bit wise operator is suitable for putting on a particular bit in a number?

Shift to the position first and use XOR (^) to switch the bit on/off. AND (&) to check if it's on

or off. In both cases the 2nd operand will be 1. (Ex. int switch = x ^ 1; int check = x & 1; This

is only if you are checking for the least significant bit, the furthest one to the right.)

55. Which bit wise operator is suitable for checking whether a particular bit is on or off?

Kindly refer to Q.52

56. which one is equivalent to multiplying by 2:Left shifting a number by 1 or Left shifting an

Page 18: C language  interview questions

unsigned int or char by 1?

left shifting by 1 it is multiplying by 2

right shifting by 1 it is dividing by 2

57. Write a program to compare two strings without using the strcmp() function.

program to compare two strings without using the strcmp() function :

#include <stdio.h>

#include <conio.h>

main()

{

//please read two strings int str1 and str2//

while(str1[i]!='/0' &&str2[i]!='/0')

if(str1[i]!=str2[i])

flag=1;

if(flag==1)

printf("equal");

}

#include

main()

{

//please read two strings int str1 and str2//

while(str1[i]!='/0' &&str2[i]!='/0')

if(str1[i]!=str2[i])

flag=1;

if(flag==1)

printf("equal");

}

58. Write a program to concatenate two strings. program to concatenate two strings :

#include<stdio.h>

#include<conio.h>

Page 19: C language  interview questions

main()

{

char s1[20],s2[20];

printf("enter first string");

scanf("%s",s1);

printf("enter second string");

scanf("%s",s2);

string_concatenate(&s1,&s2);

}

count_characters(char *x)

{

int i=0, count=0;

for(i=0;*(x+i)!='\0';i++)

count++;

return count;

}

string_concatenate(char *s1,char *s2)

{

int i,j;

char s3[50];

for(i=0;i

s3[i]=s1[i];

for(j=0;j

s3[i+j]=s2[j];

s3[i+j]=s2[j];

printf("%s",s3);

getch();

}

59. Write a program to interchange 2 variables without using the third one.

Interchanging 2 variables without using the third one :

#include<stdio.h>

#include<conio.h>

void main

{

int a,b;

printf("enter the two no");

scanf("%d%d",&a,&b);

a=a+b;

b=a-b;

a=a-b;

Page 20: C language  interview questions

printf("a=%d,b=%d",a,b);

getch();

}

60. Write programs for String Reversal & Palindrome check

program for string reversal & palindrome check :

REVERSE A STRING

#include<stdio.h>

#include<string.h>

main()

{

char str[50] revstr[50];

int i=0 j=0;

printf("Enter the string to be reversed : ");

scanf(" s" str);

for(i=strlen(str)-1;i>=0;i--)

{

revstr[j]=str[i];

j++;

}

revstr[j]=' ';

printf("Input String : s" str);

printf("nOutput String : s" revstr);

getch();

}

PALINDROME CHECK

#include < stdio.h >

#include < string.h >

#include < stdlib.h >

#include < ctype.h >

int isPalindrome(char string[]);

int main()

{

isPalindrome("avon sees nova");

Page 21: C language  interview questions

isPalindrome("a");

isPalindrome("avon sies nova");

isPalindrome("aa");

isPalindrome("abc");

isPalindrome("aba");

isPalindrome("3a2");

return(0);

}

int isPalindrome(char string[])

{

int count, countback, end, N;

N = strlen(string);

end = N-1;

for((count=0, countback = end); count <= (end/2); ++count,--countback)

{

if(string[count]!=string[countback])

{

return(1);

}

}

printf("\n[%s] is a palidrome!\n", string);

return(0);

}

61. Write a program to find the Factorial of a number

Program to find the factorial of a number :

#include<iostream>

using namespace std;

/* factorial function --recursive*/

int fact(int n){

if (n == 0)

return 1;

n=n*fact(n-1);

return n;

}

Page 22: C language  interview questions

int main() {

int n=5;

cout << "Factorial of number " << n << " is : " << fact(n) << endl;

return 0;

}

62 . Write a program to generate the Fibinocci Series

Fibonacci series :

#include<stdio.h>

#include<conio.h>

int fib(int a);

main()

{

int a;

clrscr();

scanf("%d",&a);

for(int i=0;i<a;i++)

printf("%d\n",fib(i));

}

int fib(int a)

{

if(a==0)

return 0;

if(a==1)

return 1;

else

return (fib(a-1)+fib(a-2));

}

63. Write a program which employs Recursion

Recursion :

#include<stdio.h>

#include<conio.h>

void main()

{

int factorial(int);

int n;

clrscr();

printf("Enter a number: ");

scanf("%d",&n);

printf("Factorial of %d is: %d",n,factorial(n));

Page 23: C language  interview questions

getch();

}

int factorial(int f)

{

int fact;

if(f==1)

return(1);

else

fact=f*factorial(f-1);

return(fact);

}

64. Write a program which uses Command Line Arguments

Command Line Arguments :

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

int main(int argc, char *argv[]) {

double *a;

int x, y, z, i, j;

if ((argc < 4) ||

(sscanf(argv[1],"%d",&x) != 1) ||

(sscanf(argv[2],"%d",&y) != 1) ||

(sscanf(argv[3],"%d",&z) != 1) ||

(x <= 0) || (y <= 0) || (z <= 0) ||

(z < y) || ((z - y) > 10)) {

printf("usage: %s <x> <y> <z>\n",argv[0]);

printf(" where: x, y, and z are integers > 0\n");

printf(" z >= y, and z - y <= 10\n");

return -1;

}

a = malloc((z-y+1)*sizeof(double));

for (i = 0, j = y; i < z-y+1; i++, j++) {

a[i] = pow(x,j);

printf("%g ",a[i]);

}

puts("");

free(a);

return 0;

}

Page 24: C language  interview questions

65. Write a program which uses functions like strcmp(), strcpy()? etc

Program which uses functions like strcmp(),strcpy() :

#include <stdio.h>

#include <string.h>

int main()

{

char name1[12], name2[12], mixed[25];

char title[20];

strcpy(name1, "Rosalinda");

strcpy(name2, "Zeke");

strcpy(title, "This is the title.");

printf(" %s\n\n", title);

printf("Name 1 is %s\n", name1);

printf("Name 2 is %s\n", name2);

if(strcmp(name1, name2) > 0) /* returns 1 if name1 > name2 */

strcpy(mixed, name1);

else

strcpy(mixed, name2);

printf("The biggest name alphabetically is %s\n", mixed);

strcpy(mixed, name1);

strcat(mixed, " ");

strcat(mixed, name2);

printf("Both names are %s\n", mixed);

return 0;

}

/* Output of Program.

This is the title.

Name1 is Rosalinda

Name2 is Zeke

The biggest name alphabetically is Zeke

Both names are Rosalinda Zeke

*/

66. What are the advantages of using typedef in a program?

advantages of using typedef in a program :

1. Readability. Just like naming your variables properly can show how you intend to use the

variable, renaming the type can help show how you intend to use all variables of this type. It

eliminates the possible bug of incorrect argument ordering (e.g. if a method signature has

multiple boolean flags).

Page 25: C language  interview questions

2. Portability. On different systems you might want to have the same variable name (because

you're using it the same way) to be of a different type. So you keep the typedef in a header file

controlled by conditional compilation (for example) for maximal portability.

3. decreases complexity for declaring complex and repeated declarations like

typedef unsigned long int UINT64;

67. How would you dynamically allocate a one-dimensional and two-dimensional array of

integers?

Dynamically allocating a 1-D and 2-D array of integers :

To dynamically allocate an array, use 'void *realloc(void *array, size_t size)', where array is the

pointer you plan on reallocating and size is the new length of the array in bytes.

One-dimensional array:

{

int len = 10;

int *array = NULL;

array = (int*)realloc(array, len * sizeof(int));

}

Two-dimensional array:

{

int xlen = 10;

int ylen = 10;

int **array2d = NULL;

array2d = (int**)realloc(array2d, xlen * sizeof(int*));

/* After reallocating array2d, do the same to its contents. */

int index;

for (index = 0; index < xlen; index++) {

Page 26: C language  interview questions

array2d[index] = (int*)realloc(array2d[index], ylen * sizeof(int));

}

array2d[5][5] = 24;

/* Clean up. */

for (index = 0; index < xlen; index++) {

free(array2d[index]);

}

free(array2d);

return 0;

}

68. How can you increase the size of a dynamically allocated array?

Increase the size of a dynamically allocated array :

int *ptr = malloc(10 * sizeof (int));

if (ptr == NULL) { /* Memory could not be allocated, the program should handle the error here

as appropriate. */

realloc

It is often useful to be able to grow or shrink a block of memory. This can be done

using realloc which returns a pointer to a memory region of the specified size, which contains the

same data as the old region pointed to by ptr (truncated to the minimum of the old and new

sizes). If realloc is unable to resize the memory region in-place, it allocates new storage, copies

the required data, and frees the old pointer. If this allocation fails, realloc maintains the original

pointer unaltered, and returns the null pointer value. The newly allocated region of memory is

uninitialized (its contents are not predictable). The function prototype is

void *realloc(void *pointer, size_t size);

69. How can you increase the size of a statically allocated array?

Increase the size of a statically allocated array :

int arr[10];

When an array is declared as above, memory is allocated for the elements of the array when the

program starts, and this memory remains allocated during the lifetime of the program. This is

known as static array allocation. Hence we cannot increase size of statically allocated array.

Page 27: C language  interview questions

70. When reallocating memory if any other pointers point into the same piece of memory do

you have to readjust these other pointers or do they get readjusted automatically?

They get readjusted directly or we can simply them .

71. Which function should be used to free the memory allocated by calloc()?

free() is a function used to free the memory allocated dynamically by both malloc and calloc

functions.

free(ptr): ptr is a pointer to a memory block which has already been creeated by malloc or calloc.

72. How much maximum can you allocate in a single call to malloc()?

Maximum can you allocate in a single call to malloc( )

The largest possible memory block malloc can allocate depends on the host system particularly

the size of physical memory and the operating system implementation. Theoretically the largest

number should be the maximum value that can be held in a size_t type which is an

implementation-dependent unsigned integer representing the size of an area of memory. The

maximum value is (size_t) 1 or the constant SIZE_MAX in the C99 standard.

73. Can you dynamically allocate arrays in expanded memory?

yes, In C its possible to allocate array in expanded memory at run time.

74. What is object file? How can you access object file?

Object file :

An object file is binary representation of source(text) file. On Linux, object and executable

files have ELF format. It's a collection of various sections segragating type of data in:

- text section

- data section

- stack

- heap

Also addresses in an object file are relative and hence object files can't be run unless it's

linked. for ex, if you make a call to printf(), object file will have an entry as

("call printf ___") where the blank is the address of printf function. Since printf is part of

libc.so, you have no knowledge of its address. Linking with libc pads the correct address and

enable you to call it successfully.

Page 28: C language  interview questions

When we compile a C program using cc program.c, the compiler places the object code in

program.o and loads the executable in a.out(called as assembler output).When we write

./a.out, the loader loads it in the memory and executes it .

75. Which header file should you include if you are to develop a function which can accept variable number of arguments?

The header file should you include if you are to develop a function which can accept

variable number of arguments is stdarg.h

76. Can you write a function similar to printf()?

Function similar to printf() :

we can use va_start, va_end, va_list

Here, we write a program similar to printf().

#include <stdarg.h>

int printf(const char * restrict fmt, ...)

{

va_list list; int i; va_start(list, fmt);

i = vfprintf(stdout, fmt, list);

va_end(list);

return i;

}

77. How can a called function determine the number of arguments that have been passed to it?

use the variable length argument - va_arg va_list ca_start and va_end macros

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

In general, you cannot. Ideally, you should provide a version of that other function which

accepts a va_list pointer.

Suppose you want to write a faterror function which will print a fatal error message, then

exit. You might like to write it in terms of the error function of question 15.5:

void faterror(const char *fmt, ...)

{

error(fmt, what goes here? );

exit(EXIT_FAILURE);

}

but it's not obvious how to hand faterror's arguments off to error.

Proceed as follows. First split up the existing error function to create a new verror which

Page 29: C language  interview questions

accepts not a variable argument list but a single va_list pointer. (Note that doing so is little

extra work, because verror contains much of the code that used to be inerror, and the

new error becomes a simple wrapper around verror.)

#include <stdio.h>

#include <stdarg.h>

void verror(const char *fmt, va_list argp)

{

fprintf(stderr, "error: ");

vfprintf(stderr, fmt, argp);

fprintf(stderr, "\n");

}

void error(const char *fmt, ...)

{

va_list argp;

va_start(argp, fmt);

verror(fmt, argp);

va_end(argp);

}

Now you can write faterror, and have it call verror, too:

#include <stdlib.h>

void faterror(const char *fmt, ...)

{

va_list argp;

va_start(argp, fmt);

verror(fmt, argp);

va_end(argp);

exit(EXIT_FAILURE);

}

Note that the relation between error and verror is exactly that which holds between

e.g. printf and vprintf. In fact, as Chris Torek has observed, whenever you find yourself

writing a varargs function, it's a good idea to write two versions of it: one (likeverror)

which accepts a va_list and does the work, and one (like the revised error) which is a

simple wrapper. The only real restriction on this technique is that a function

like verror can scan the arguments just once; there is no way for it to reinvoke va_start.

If you do not have the option of rewriting the lower-level function (error, in this example)

to accept a va_list, such that you find yourself needing to pass the variable arguments that

one function (e.g. faterror) receives on to another as actual arguments, no portable

solution is possible. (The problem could perhaps be solved by resorting to machine-

specific assembly language; see also question 15.13.)

Page 30: C language  interview questions

One approach that would not work would be something like

void faterror(const char *fmt, ...)

{

va_list argp;

va_start(argp, fmt);

error(fmt, argp); /* WRONG */

va_end(argp);

exit(EXIT_FAILURE);

}

A va_list is not itself a variable argument list; it's really sort of a pointer to one. That is, a

function which accepts a va_list is not itself varargs, nor vice versa.

Another kludge that is sometimes used, and which sometimes works even though it is

grossly nonportable, is to use a lot of int arguments, hoping that there are enough of them

and that they can somehow pass through pointer, floating-point, and other arguments as

well:

void faterror(fmt, a1, a2, a3, a4, a5, a6)

char *fmt;

int a1, a2, a3, a4, a5, a6;

{

error(fmt, a1, a2, a3, a4, a5, a6); /* VERY WRONG */

exit(EXIT_FAILURE);

}

This example is presented only for the purpose of urging you not to use it; please don't

try it just because you saw it here.

79. How do you declare the following:

o An array of three pointers to chars

o An array of three char pointers

o A pointer to array of three chars

o A pointer to function which receives an int pointer and returns a float pointer

o A pointer to a function which receives nothing and returns nothing

An array of three pointers to chars : char* a[3];

An array of three char pointers : char* b[3];

A pointer to array of three chars : char[3] *c;

A pointer to function which receives an int pointer and returns a float pointer : float*

(*func)(int *); A pointer to a function which receives nothing and returns nothing

Note that these are definitions. To make these declarations only, use the keyword

Page 31: C language  interview questions

'extern'.

80. What do the functions atoi(), itoa() and gcvt() do?

atoi() converts string to integer

itoa() converts integer to string

atof() converts string to float

gcvt() this func converts double to ascii string.

81. Does there exist any other function which can be used to convert an integer or a float to a string?

Some implementations provide a nonstandard function called itoa(), which converts an

integer to string.

#include

char *itoa(int value, char *string, int radix);

DESCRIPTION

The itoa() function constructs a string representation of an integer.

PARAMETERS

value:

Is the integer to be converted to string representation.

string:

Points to the buffer that is to hold resulting string.

The resulting string may be as long as seventeen bytes.

radix:

Is the base of the number; must be in the range 2 - 36.

A portable solution exists. One can use sprintf():

char s[SOME_CONST];

int i = 10;

float f = 10.20;

sprintf ( s, “%d %f\n”, i, f );

82. How would you use qsort() function to sort an array of structures?

qsort() function to sort an array of structures :

#include <stdio.h>

#include <stdlib.h>

typedef int (*compfn)(const void*, const void*);

Page 32: C language  interview questions

struct animal { int number;

char name[15];

};

struct animal array[10] = { { 1, "Anaconda" },

{ 5, "Elephant" },

{ 8, "Hummingbird" },

{ 4, "Dalmatian" },

{ 3, "Canary" },

{ 9, "Llama" },

{ 2, "Buffalo" },

{ 6, "Flatfish" },

{ 10, "Zebra" },

{ 7, "Giraffe" } };

void printarray(void);

int compare(struct animal *, struct animal *);

void main(void)

{

printf("List before sorting:\n");

printarray();

qsort((void *) &array, // Beginning address of array

10, // Number of elements in array

sizeof(struct animal), // Size of each element

(compfn)compare ); // Pointer to compare function

printf("\nList after sorting:\n");

printarray();

}

int compare(struct animal *elem1, struct animal *elem2)

{

if ( elem1->number < elem2->number)

return -1;

else if (elem1->number > elem2->number)

return 1;

else

return 0;

}

Page 33: C language  interview questions

void printarray(void)

{

int i;

for (i = 0; i < 10; i++)

printf("%d: Number %d is a %s\n",

i+1, array[i].number, array[i].name);

}

83. How would you use qsort() function to sort the name stored in an array of pointers to string?

It is same as you would sort an array of integers using qsort. Only difference is that you

would have to do string comparison.

84. How would you use bsearch() function to search a name stored in array of pointers to string?

bsearch() function to sort to search a name stored in array of pointers to string :

bsearch, It is a library function.Using this we done data entry in array. Ther is

mandatry in binary search your must sorted in ascending order.And do compare

two datas.For using this function we have to include stdlib.h library function.

Syntax:

void *bsearch(void *key, void *base, size num, size width,

int (*cmp)(void *emt1, void *emt2));

where;

emt->Element.

Some steps that we have to follow when we using

bsearch.

1. It is passed pointers to two data items

2. It returns a type int as follows:

2.1) <0 Element 1 is less than element 2.

2.2) 0 Element 1 is equal to element 2.

2.3) > 0 Element 1 is greater than element 2.

example:

#include <stdio.h>

Page 34: C language  interview questions

#include <stdlib.h>

#include <string.h>

#define TABSIZE 1000

struct node { /* These are stored in the table. */

char *string;

int length;

};

struct node table[TABSIZE];/*Table to be search*/

.

.

.

{

struct node *node_ptr, node;

/* Routine to compare 2 nodes. */

int node_compare(const void *, const void *);

char str_space[20]; /* Space to read string into. */

.

.

.

node.string = str_space;

while (scanf("%s", node.string) != EOF) {

node_ptr = (struct node *)bsearch((void *)(&node),(void *)table,

TABSIZE,sizeof(struct node), node_compare);

if (node_ptr != NULL)

{

(void)printf("string = %20s, length = %d\n",

node_ptr->string, node_ptr->length);

}

else

{

(void)printf("not found: %s\n", node.string);

}

}

}

/*

This routine compare two nodes based on an

alphabetical ordering of the string field.

*/

int node_compare(const void *node1, const void *node2)

{

Page 35: C language  interview questions

return strcoll(((const struct node *)node1)->string,((const struct node *)node2)-

>string);

}

85. How would you use the functions sin(), pow(), sqrt()?

First of all you have to insert the following line in your code:

#include <math.h>

sin is defined function which takes argument fo double type and returns double type:

sin(x)

If you write something like:

double x, y;

cout << "Enter value for argument for sin/n";

cin >> x;

cout << "/nResult is: " << y;

The same for sqrt which is square root of x (sqrt(x));

The function pow has two arguments (pow(x, y)) of double type and in returns the

value of double type. For instance,

pow(2, 3) in mathematical language can be written as 23.

86. How would you use the functions memcpy(), memset(), memmove()?

memcpy() function copies n bytes from the object pointed to by s2 into the object

pointed to by s1. If copying takes place between objects that overlap, the behavior is

undefined.

memmove() function shall copy n bytes from the object pointed to by s2 into the

object pointed to by s1. Copying takes place as if the n bytes from the object pointed

to by s2 are first copied into a temporary array of n bytes that does not overlap the

objects pointed to by s1 and s2, and then the n bytes from the temporary array are

copied into the object pointed to by s1.

memset() function copies c (converted to an unsigned char) into each of the first n

bytes of the object pointed to by s. SYNTAX:

void *memcpy(void *s1, const void *s2, size_t n);

void *memmove(void *s1, const void *s2, size_t n);

void *memset(void *s, int c, size_t n);

Page 36: C language  interview questions

87. How would you use the functions fseek(), freed(), fwrite() and ftell()?

fread(s,i1,i2,f) Enter i2 dataitems,each of size i1 bytes,from file f to string s.

fseek(f,1,i) Move the pointer for file f a distance 1 byte from location i.

ftell(f) Return the current pointer position within file f.

fwrite(s,i1,i2,f) send i2 data items,each of size i1 bytes from string s to file f.

The data type returned for functions fread,fseek and fwrite is int and ftell is long int.

88. How would you obtain the current time and difference between two times?

we have Date class in java.util.

Ex:

java.util.Date d1 new java.util.Date();

System.out.println(d1.getTime());

statement 1;

statement 2;

statement 3;

java.util.Date d2 new java.util.Date();

System.out.println(d2.getTime());

89. How would you use the functions randomize() and random()?

Random() returns a random number between 0 and (num-1).random(num) is a

macro defined in stdlib.h

Randomize() initializes the random number generator with a random value.Because

randomize is implemented as a macro that calls the time function protyped in

time.h,you should include time.h when you use this routine.

#include<conio.h>

main()

{int i;

i=random(50);

printf9'%d",i);

}

Page 37: C language  interview questions

90. How would you implement a substr() function that extracts a sub string from a given string?

substr(string position [ count])

It extract substring starting from start and going for count characters. If count is

not specified the string is clipped from the start till the end

91. What is the difference between the functions rand(), random(), srand() and randomize()?

RAND: Rand uses a multiplicative congruential random number generator with

period232 to return successive pseudo-random numbers in the range 0 to

RAND_MAX.

Return Value: Rand returns the generated pseudo-random number.

RANDOM(): Random returns a random number between 0 and (num-

1).random(num) is a macro defined in STDLIB.H.

RANDOMIZE(): Randomize initializes the random number generator with a

random value. Because randomize is implemented as a macro that calls the time

function prototyped in TIME.H you should include TIME.H when you use this

routine

SRAND(): The random number generator is reinitialized by calling srand with

an argument value of 1.The generator can be set to a new starting point by

calling srand with a given seed number.

92. What is the difference between the functions memmove() and memcpy()?

void *memmove(void *DST, const void *SRC, size_t LENGTH);

This function moves LENGTH characters from the block of memory start-

ing at `*SRC' to the memory starting at `*DST'. `memmove' reproduces

the characters correctly at `*DST' even if two areas overlap.

void* memcpy(void *OUT, const void *IN, size_t N);

This function copies N bytes from the memory region pointed to by IN

to the memory region pointed to by OUT.

Page 38: C language  interview questions

93. How do you print a string on the printer?

By using sprintf() function.

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

yes we can

#include <stdio.h>

#include <conio.h>

void main()

{

fprintf(stdout sdfsdf );

getch();

}

fprintf() accepts the first argument which is a file pointer to a stream. the stdout

is also a file pointer to the standard output(screen)