Sunday, April 10, 2011

Most frequently asked 30 essential C questions along with the best available answers for interviews

Hello buddies!!
One question which  most of my juniors and friends ask me nowadays is about preparing for placements.. so i thought of making use of my blog for it, being in the process of placements as a co-ordinator, a student preparing for placements and being selected for  2 most reputed companies such as IBM and E&Y, I feel i ve gained ample amount of knowledge about placements which i can share it here, hence , thinking of sharing my preparation process, knowledge , know-how ,pro's& con's here in my blog through posts.
so frenz.. lets start the Placement carnival with the fundamentals and essentials. What the company professionals,  first and foremost expect from students is  THE MINIMUM BASIC  KNOWLEDGE  about C.. so i am presenting below the 30 most essential questions and most excellent answers on C which i have found by googling hours together on NET.. Most of the times ,Though u know the concept , u may find it difficult to express it more precisely.. but after reading it ,i hope u feel more confident to answer questions on C




1. What is the difference between declaring a variable and defining a variable?
Declaration of a variable in C hints the compiler about the type and size of the variable in compile time. Similarly, declaration of a function hints about type and size of function parameters. No space is reserved in memory for any variable in case of declaration.
Example: int a;
Here variable 'a' is declared of data type 'int'
Defining a variable means declaring it and also allocating space to hold it.
We can say "Definition = Declaration + Space reservation".
Example: int  a = 10;
Here variable "a" is described as an int to the compiler and memory is allocated to hold value 10.

2. What is a static variable?
A static variable is a special variable that is stored in the data segment unlike the default automatic variable that is stored in stack. A static variable can be initialized by using keyword static before variable name.
Example:
static int a = 5;
A static variable behaves in a different manner depending upon whether it is a global variable or a local variable.
A static global variable is same as an ordinary global variable except that it cannot be accessed by other files in the same program / project even with the use of keyword extern. A static local variable is different from local variable. It is initialized only once no matter how many times that function in which it resides is called. It may be used as a count variable.
Example:
#include
//program in file f1.c
void count(void) {
 static int count1 = 0;
 int count2 = 0;
 count1++;
 count2++;
 printf("\nValue of count1 is %d, Value of count2 is %d", count1, count2);
}
/*Main function*/
int main(){
 count();
 count();
 count();
 return 0;
}
Output:
Value of count1 is 1, Value of count2 is 1
Value of count1 is 2, Value of count2 is 1
Value of count1 is 3, Value of count2 is 1

3. What is a register variable?
Register variables are stored in the CPU registers. Its default value is a garbage value. Scope of a register variable is local to the block in which it is defined. Lifetime is till when control remains within the block in which the register variable is defined. Variable stored in a CPU register can always be accessed faster than the one that is stored in memory. Therefore, if a variable is used at many places in a program, it is better to declare its storage class as register
Example: register int x=5;
Variables for loop counters can be declared as register. Note that register keyword may be ignored by some compilers.

4. Where is an auto variables stored?
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.

5. What is scope & storage allocation of extern and global variables?
Extern variables: belong to the External storage class and are stored in the main memory. extern is used when we have to refer a function or variable that is implemented in other file in the same project. The scope of the extern variables is Global.
Example:
***************/
Index: f1.c
/****************
#include
extern int x;
int main() {
 printf("value of x %d", x);
 return 0;
{
Index: f2.c
/****************
int x = 3;
Here, the program written in file f1.c has the main function and reference to variable x. The file f2.c has the  declaration of variable x. The compiler should know the datatype of x and this is done by extern definition.
Global variables: are variables which are declared above the main( ) function. These variables are accessible throughout the program. They can be accessed by all the functions in the program. Their default value is zero.
Example:
#include
int x = 0;
/* Variable x is a global variable.
It can be accessed throughout the program */
void increment(void) {
 x = x + 1;
 printf("\n value of x: %d", x);
{
int main(){
 printf("\n value of x: %d", x);
 increment();
 return 0;
}

6. What is scope & storage allocation of register, static and local variables?
Register variables: belong to the register storage class and are stored in the CPU registers. The scope of the register variables is local to the block in which the variables are defined. The variables which are used for more  number of times in a program are declared as register variables for faster access.



Example: loop counter variables.
register int y=6;
Static variables: Memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates. The scope of the static variables is local to the block in which the variables are defined.
Example:
#include
void decrement(){
  static int a=5;
  a--;
  printf("Value of a:%d\n", a);
}
int main(){
 decrement();
 return 0;
}
Here 'a' is initialized only once. Every time this function is called, 'a' does not get initialized. so output would be 4 3 2 etc.,
Local variables: are variables which are declared within any function or a block. They can be accessed only by function or block in which they are declared. Their default value is a garbage value
.
7. What are storage memory, default value, scope and life of Automatic and Register storage class?
   1.  Automatic storage class:
Storage  : main memory.
Default value : garbage value.
Scope  :  local to the block in which the variable is defined.
Lifetime  :  till control remains within the block.
   2. Register storage class:
Storage  : CPU registers.
Default value : garbage value.
Scope  :  local to the block in which the variable is defined.
Lifetime  :  till control remains within the block.

8. What are storage memory, default value, scope and life of Static and External storage class?
   1.  Static storage class:
Storage  : main memory.
Default value : zero
Scope  :  local to the block in which the variable is defined.
Lifetime  :  till the value of the variable persists between different function calls.
   2. External storage class:
Storage  : main memory
Default value : zero
Scope  :  global
Lifetime  :  as long as the program execution doesn't come to an end.

9. What is the difference between 'break' and 'continue' statements?
Differences between 'break' and 'continue' statements
break  continue
1. break is a keyword used to terminate the loop or exit from the block. The control jumps to next
statement after the loop or block.
1. continue is a keyword used for skipping the current iteration and go to next iteration of the loop
2.Syntax:
{
 Statement 1;
 Statement 2;
 Statement n;
 break;
}
2.Syntax:
{
 Statement 1;
 continue;
 Statement 2;
}
3. break can be used with for, while, do- while, and switch statements. When break is used in nested loops i.e. within the inner most loop then only the innermost loop is terminated.
3. This statement when occurs in a loop does not terminate it but skips the statements after thiscontinue statement. The control goes to the next iteration. Continue can be used with for, while and do-while.
4. Example:  int i = 1, j = 0; while(i<=5)
{
 i=i+1;
 if(i== 2)
break;
 j=j+1;
}
4. Example:  Int i = 1, j = 0; while(i<=5)
{
 i=i+1;
 if(i== 2)
continue;
 j=j+1;
}

10. What is the difference between 'for' and 'while' loops?
for loop: When it is desired to do initialization, condition check and increment/decrement in a single statement of an iterative loop, it is recommended to use 'for' loop.
Syntax:
for(initialization;condition;increment/decrement)
{
}
while loop: When it is not necessary to do initialization, condition check and increment/decrement in a single statement of an iterative loop, while loop could be used. In while loop statement, only condition statement is present.


11. What is equivalent of multiplying an unsigned int by 2? left shift of number by 1 or right shift of number by 1?

Left shifting of an unsigned integer is equivalent to multiplying an unsigned int by 2.

12. What is an Enumeration Constant?
Enumeration is a data type. We can create our own data type and define values that the variable can take. This can help in making program more readable. enum definition is similar to that of a structure.
Example: consider light_status as a data type. It can have two possible values - on or off.
enum light_status
{
  on, off
};
enum light_status bulb1, bulb2;
/* bulb1, bulb2 are the variables */
Declaration of enum has two parts:
a) First part declares the data type and specifies the possible values, called 'enumerators'.
b) Second part declares the variables of this data type.
We can give values to these variables:
bulb1 = on;
bulb2 = off;

13. What is a structure?
A structure is a collection of pre-defined data types to create a user-defined data type. Let us say we need to create records of students. Each student has three fields:
int roll_number;
char name[30];
int total_marks;
This concept would be particularly useful in grouping data types. You could declare a structure student as:
struct student {
 int roll_number;
 char name[30];
 int total_marks;
} student1, student2;
The above snippet of code would declare a structure by name student and it initializes two objects student1,
student2. Now these objects and their fields could be accessed by saying student1.roll_number for accesing roll
number field of student1 object, similarly student2.name for accesing name field of student2 object.

14. What are the differences between a structure and a union?
Structures and Unions are used to store members of different data types.
STRUCTURE v/s UNION
a)Declaration:
struct
{ 
   data type member1;
   data type member2;
};
a)Declaration:
union       { 
   data type member1;
   data type member2;
};

b)Every structure member is allocated memory when a structure variable is defined.
Example:
struct emp {
 char name[5];
 int age;
 float sal;
};
struct emp e1;
Memory allocated for structure is 1+2+4=7 bytes. 1 byte for name, 2 bytes for age and 4 bytes for sal.
b)The memory equivalent to the largest item is allocated commonly for all members.
Example:
union emp1 {
 char name[5];
 int age;
 float sal;
}; union emp1 ;
Memory allocated to a union is equal to size of the largest member. In this case, float is the largest-sized
data type. Hence memory allocated to this union is 4  bytes.

c)All structure variables can be initialized at a time
struct st {
 int a;
 float b;
};
struct st s = { .a=4, .b=10.5 };
Structure is used when all members are to be independently used in a program.
c)Only one union member can be initialized at a time
union un {
 int a;
 float b;
};
union un un1 = { .a=10 };
Union is used when members of it are not required to be accessed at the same time.

15. What are the advantages of unions?
Union is a collection of data items of different data types. It can hold data of only one member at a time though it has members of different data types. If a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.
Example:
union pen {
 char name;
 float point;
};
Here name and point are union members. Out of these two variables, 'point' is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type. Union is efficient when members of it are not required to be accessed at the same time.

16. How can typedef be used  to define a type of structure?
typedef declaration helps to make source code of a C program more readable. Its purpose is to redefine the name of an existing variable type. It provides a short and meaningful way to call a data type. typedef is useful when the name of the data type is long. Use of typedef can reduce length and complexity of data types.
Note: Usually uppercase letters are used to make it clear that we are dealing with our own data type.
Example:
struct employee {
 char name[20];
 int age;
};
struct employee e;
//The above declaration of the structure would be easy to use when renamed using typedef as:
struct employee {
 char name[20];
 int age;
};
typedef struct employee EMP;
EMP e1, e2;



17. What is the purpose of main() function?
In C, program execution starts from the main() function. Every C program must contain a main() function. The main function may contain any number of statements. These statements are executed sequentially in the order in which they are written. The main function can in-turn call other functions. When main calls a function, it passes the execution control to that function. The function returns control to main when a return statement is executed or when end of function is reached.
In C, the function prototype of the 'main' is one of the following:
int main(); //main with no arguments
int main(int argc, char *argv[]); //main with arguments
The parameters argc and argv respectively give the number and value of the program's command-line arguments.

18. Explain command line arguments of main function?
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: 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.
Example: at the command prompt if we give:
C:\> fruit.exe apple mango
Then  argc would contain value 3
argv [0] would contain base address of string " fruit.exe" which is the command name that invokes the program.
argv [1] would contain base address of string "apple"
argv [2] would contain base address of string "mango"
here apple and mango are the arguments passed to the program fruit.exe
Program:
#include
int main(int argc, char *argv[]) {Material from Interview Mantra. Subscribe to free updates via email.
 int n;
 printf("Following are the arguments entered in the command line");
 for (n = 0; n < argc; n++) {
  printf("\n %s", argv[n]);
{
 printf("\n Number of arguments entered are\n %d\n", argc);
 return 0;
}
Output:
Following are the arguments entered in the command line
C:\testproject.exe
apple
mango
Number of arguments entered are
3

19. What are header files? Are functions 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 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.
Syntax of include directive:
#include //includes the header file stdio.h, standard input output header into the source code
Functions can be declared as well as defined in header files. But it is recommended only to declare functions and not to define in the header files. When we include a header file in our program we actually are including all the functions, macros and variables declared in it.
In case of pre-defined C standard library header files ex(stdio.h), the functions calls are replaced by equivalent binary code present in the pre-compiled libraries. Code for C standard functions are linked and then the program is executed.
Header files with custom names can also be created.


20. What are the differences between formal arguments and actual arguments of a function?
Argument: An argument is an expression which is passed to a function by its caller (or macro by its invoker) in order for the function(or macro) to perform its task. It is an expression in the comma-separated list bound by the parentheses in a function call expression.
Actual arguments: The arguments that are passed in a function call are called actual arguments. These arguments are defined in the calling function.
Formal arguments: The formal arguments are the parameters/arguments in a function declaration. The scope of formal arguments is local to the function definition in which they are used. Formal arguments belong to the called function. Formal arguments are a copy of the actual arguments. A change in formal arguments would not be reflected in the actual arguments.
Example: #include
void sum(int i, int j, int k);
/* calling function */
int main() {
      int a = 5;
      // actual arguments
      sum(3, 2 * a, a);
      return 0;
}
/* called function */
/* formal arguments*/
void sum(int i, int j, int k) {
      int s;
      s = i + j + k;
      printf("sum is %d", s);
}
Here 3,2*a,a are actual arguments and i,j,k are formal arguments.

21. What is pass by value in functions?
Pass by Value: In this method, the value of each of the actual arguments in the calling function is copied into  corresponding formal arguments of the called function. In pass by value, the changes made to formal arguments in the called function have no effect on the values of actual arguments in the calling function.
Example:
#include
void swap(int x, int y) {
 int t;
 t = x;
 x = y;
 y = t;
}
int main() {
 int m = 10, n = 20;
 printf("Before executing swap m=%d n=%d\n", m, n);
 swap(m, n);
 printf("After executing swap m=%d n=%d\n", m, n);
 return 0;
Output:
Before executing swap m=10 n=20
After executing swap m=10 n=20
Explanation:
In the main function, value of variables m, n are not changed though they are passed to function 'swap'. Swap function has a copy of m, n and hence it can not manipulate the actual value of arguments passed to it.

22. What is pass by reference in functions?
Pass by Reference: In this method, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses, we would have an access to the actual arguments and hence we would be able to manipulate them. C does not support Call by reference.
But it can be simulated using pointers.
Example:
#include
/* function definition */
void swap(int *x, int *y) {
 int t;
 t = *x; /* assign the value at address x to t */
 *x = *y; /* put the value at y into x */
 *y = t; /* put the value at to y */
}
int main() {
 int m = 10, n = 20;
 printf("Before executing swap m=%d n=%d\n", m, n);
 swap(&m, &n);
 printf("After executing swap m=%d n=%d\n", m, n);
 return 0;
}
 Output:
Before executing swap m=10 n=20
After executing swap m=20 n=10

Explanation:
In the main function, address of variables m, n are sent as arguments to the function 'swap'. As swap function has the access to address of the arguments, manipulation of passed arguments inside swap function would be directly reflected in the values of m, n.

23. What are the differences between getchar() and scanf() functions for reading strings?
Differences between getchar and scanf functions for reading strings:
 1)scanf  2) getchar
1. Entering of each character should be followed by return key.
1. Need not type return key.
2. Continuous stream of characters cannot be directly supplied using scanf function.
2. Continuous stream of characters can be directly supplied using getchar function
3. Scanf function can be used to provide data at execution time irrespective of its type(int, char,
float).
Example:
#include
int  main() {
   char a[10];
   printf("Enter a: \n");
   scanf("%s",a);
   return 0;
}
3. getchar() function is used only with character type.
Example:
#include
int main() {
 char a;
 printf("Enter any character: \n");
 a = getchar();
 printf("Character entered:%c \n",a);
 return 0;
}
4. scanf() returns the number of items read successfully. A return value 0 indicates that no fields were read. EOF(end of file) is returned in case of an error or if end-of-file/end-of-string character is encountered.
4. getchar() returns the character entered as the value of the function. It returns EOF in case of an error. It is recommended to use getchar instead of scanf.


24. What is the difference between the functions strdup() and strcpy()?
strcpy function: copies a source string to a destination defined by user. In strcpy function both source and destination strings are passed as arguments. User should make sure that destination has enough space to accommodate the string to be copied.  'strcpy' sounds like short form of "string copy".
Syntax: strcpy(char *destination, const char *source);
Source string is the string to be copied and destination string is string into which source string is copied. If successful, strcpy subroutine returns the address of the copied string. Otherwise, a null pointer is returned.

strdup function: duplicates a string to a location that will be decided by the function itself. Function will copy the contents of string to certain memory location and returns the address to that location. 'strdup' sounds like short
form of "string duplicate"
Syntax:
strdup (const char *s);
strdup returns a pointer to a character or base address of an array. Function returns address of the memory
location where the string has been copied. In case free space could not be created then it returns a null pointer.
Both strcpy and strdup functions are present in header file


 25. What is a pointer in C?
A pointer is a special variable in C language meant just to store address of any other variable or function. Pointer variables unlike ordinary variables cannot be operated with all the arithmetic operations such as '*','%' 
operators.

26. What is pointer arithmetic?
A pointer is declared as:
int *ap;
int a = 5;
In the above two statements an integer a was declared and initialized to 5. A pointer to an integer with name ap was declared. Next before ap is used
ap=&a;
This operation would initialize the declared pointer to int. The pointer ap is now said to point to a.
Operations on a pointer:
• Dereferencing operator ' * ': This operator gives the value at the address pointed by the pointer . For
example after the above C statements if we give
printf("%d",*ap);
Actual value of a that is 5 would be printed. That is because ap points to a.
• Addition operator ' + ': Pointer arithmetic is different from ordinary arithmetic. ap=ap+1;
Above expression would not increment the value of ap by one, but would increment it by the number of
bytes of the data type it is pointing to. Here ap is pointing to an integer variable hence ap is incremented
by 2 or 4 bytes depending upon the compiler.

27. What are the advantages of using pointers?
Pointers are special variables which store address of some other variables.
Syntax: datatype *ptr;
Here * indicates that ptr is a pointer variable which represents value stored at a particular address.
Example: int *p;
'p' is a pointer variable pointing to address location where an integer type is stored.
Advantages:
1. Pointers allow us to pass values to functions using call by reference. This is useful when large sized
arrays are passed as arguments to functions. A function can return more than one value by using call by reference.
2. Dynamic allocation of memory is possible with the help of pointers.
3. We can resize data structures. For instance, if an array's memory is fixed, it cannot be resized. But in
case of an array whose memory is created out of malloc can be resized.
4. Pointers point to physical memory and allow quicker access to data.

27. What are the differences between malloc() and calloc()?
two main Differences between malloc() and calloc() are:
 1. Number of arguments differ.
2. By default, memory allocated by malloc() contains garbage values. Whereas memory allocated by calloc() contains all zeros

28.How to use realloc() to dynamically increase size of an already allocated array?
realloc(): This function is used to increase or decrease the size of any dynamic memory which is allocated using malloc() or calloc() functions.
Syntax: void *realloc(void *ptr, size_t newsize);
The first argument 'ptr' is a pointer to the memory previously allocated by the malloc or calloc functions. The second argument 'newsize' is the size in bytes, of a new memory region to be allocated by realloc. This value can be larger or smaller than the previously allocated memory. The realloc function adjusts the old memory region if newsize is smaller than the size of old memory.  If the newsize is larger than the existing memory size, it increases the size by copying the contents of old memory region to new memory region. The function then deallocates the old memory region. realloc function is helpful in managing a dynamic array whose size may change during execution.
Example: a program that reads input from standard input may not know the size of data in advance. In this case, dynamically allocated array can be used so that it is possible allocate the exact amount of memory using realloc function.

29.What is the equivalent pointer expression for referring an element a[i][j][k][l], in a four dimensional array?
Consider a multidimensional array a[w][x][y][z].
In this array, a[i] gives address of a[i][0][0][0] and a[i]+j gives the address of a[i][j][0][0]
Similarly, a[i][j] gives address of a[i][j][0][0] and a[i][j]+k gives the address of a[i][j][k][0]
a[i][j][k] gives address of a[i][j][k][0] and a[i][j][k]+l gives address of a[i][j][k][l]
Hence a[i][j][k][l] can be accessed using pointers as *(a[i][j][k]+l)
where * stands for value at address and a[i][j][k]+l gives the address location of a[i][j][k][l].
Program: Example program to illustrate pointer denotation of multi-dimensional arrays.
#include
#include
int main() {
 int a[3][3][3][3];
 //it gives address of a[0][0][0][0] .
 printf(" \n address of array a is %u", a);
 printf("\n address of a[2][0][0][0] is %u ,given by a[2], %u given by a+2",
 a[2], a + 2);
 printf("\n address of a[2][2][0][0] is %u ,given by a[2][2], %u given by a[2]+2",
 a[2][2], a[2] + 2);
 printf("\n address of a[2][2][1][0] is %u ,given by a[2][2][1] , %u given by a[2][2]+1",
 a[2][2][1], a[2][2] + 1);
 return 0;
}
Output:
address of array a is 65340Material from Interview Mantra. Subscribe to free updates via email.
address of a[2][0][0][0] is 65448, given by a[2] , 65448 given by a+2
address of a[2][2][0][0] is 65484, given by a[2][2] ,65484 given by a[2]+2
address of a[2][2][1][0] is 65490, given by a[2][2][1] , 65490 given by a[2][2]+1
Explanation:
This output may differ from computer to computer as the address locations are not same for every computer.



30. (i) What are the differences between the C statements below:
char *str = "Hello";
char arr[] = "Hello";
(ii) Whether following statements get complied or not? Explain each statement.
arr++;
*(arr + 1) = 's';
printf("%s",arr);
(i) char *str="Hello";
"Hello" is an anonymous string present in the memory. 'str' is a pointer variable that holds the address of this
string.
char arr[]="Hello";
This statement assigns space for six characters: 'H' 'e' 'l' 'l' 'o' '\0' . 'arr' is the variable name assigned to thisMaterial from Interview Mantra. Subscribe to free updates via email.
array of characters.
str[4] and arr[4] also have different meanings.
str[4]: adds 4 to the value of 'str' and points to the address same as value of str + 4.
arr[4]: points to the fourth element in array named 'arr'.
(ii) 'arr' is variable name of an array. A variable name can not be incremented or decremented. Hence arr++ is an invalid statement and would result in a compilation error.
*(arr+1)='s';
'arr' is the name of a character array that holds string "Hello". Usually, name of an array points to its base
address. Hence value of arr is same as &arr[0].
arr+1 is address of the next element: &arr[1]
Character 's' is assigned to the second element in array 'arr', thereby string changes from "Hello" to "Hsllo".
printf("%s",arr );
This statement prints the string stored in character array 'arr'.








No comments:

Post a Comment