Showing posts with label answers. Show all posts
Showing posts with label answers. Show all posts

Sunday, May 3, 2015

Latest subjective C questions asked in placement interviews

Comment on the output of following C code:
 #include <stdio.h>  
 int main(){  
  const int x=10;  
  int *p;  
  p=&x;  
  *p=20;  
  printf("%d %d",*p, x);  
  getch();  
  return 0;  
 }  

Answer: We are trying to change the value of a const variable. Such code may lead to unknown behaviour in program depending on compiler used. In Dev C++ code compiles with warning and produces output 20 20. Thus value of a constant is being changed through pointers. Such error can be prevented if we make use of pointer to constant to store the address of x instead of a simple integer pointer. If we use int const *p=&x; then *p=20 will produce a compilation error.




Question: What is output of following code snippets

c interview question 51

printf("atandon"+1);//P
printf("a%d%d%d"+2,1,2); //Q

Answer & Explanation

P : tandon
+1 removes 1 char from format specifier string.
Q: d12


+2 will remove 'a' and first % from format specifiers, remaining %d will be replaced by corresponding values => d12


c interviewQuestion: Explain #ifndef. Is there any alternative to it?

Answer: #ifndef is used to execute a piece of c code if particular macro is not defined.
#ifndef RSA

<code written here will execute only if we have defined constant RSA as #define RSA {some value}>

#endif

We can also use


#if !defined(RSA) instead of #ifndef RSA


Question: What is the use of # in macro functions?


Answer: It is used to return the string equivalent of the passed parameter. Consider the following example:-
#define debug(exp) printf(#exp " =%f",exp);

Now debug(x/y); will convert to printf("x/y" " =%f",x/y);



This will print: x/y =<value of x/y in float>


Question: Explain use of ‘##’ in macros.

Answer:
let's say you have
c interview
#define dumb_macro(a,b) a ## b
Now if you call the above macro as dumb_macro(hello, world)
It would result in
helloworld
which is not a string, but a symbol(token) and you'll probably end up with an undefined symbol error saying
'helloworld' doesn't exist unless you define it first. To make this legal you first need to declare the symbol like this.

int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'



## is called token passing argument since it is used to create tokens through passed arguments


Question: Find output of following code snippet in C++
c questions

#include <iostream>
#include <conio.h>
using namespace std;
int foo1(){
     cout<<"foo1 ";  
     return 1; 
}
int foo2(void* a, void* b){
    cout<<"foo2 ";
    return 2;
}
int main(){
        int x=~foo1()&~foo2(cout<<"a ",cout<<"b ");//foo1 b a foo2
        getch();
}


Answer:
foo1 b a foo2



Explanation: << operator associated with cout object returns a reference to itself this can be accepted by void* (generic pointer) ~ is negation operator. The output depends on order of execution of expression and order in which parameters are passed in function.



Question: What value is returned by cout<<"Hello";
c interview


Answer: cout is an object to represent standard output stream. << operator associated with it returns a reference to same standard output stream object. This allows chaining of << operators and thus

cout<<"hello"<<" world";


is same as cout<<"hello world";


c questionQuestion: Which library function will you use to convert a string to equivalent integer?
Answer: int atoi(const char*)

Write a c program to implement your own version of above function?
Answer: Refer
The C Programming Language, second edition,
by Brian Kernighan and Dennis Ritchie





Question: What is fall through? How is it useful? 
c question


Answer: Flow of control to following cases after the matching case in absence of break statement after the matching case is known as fall through.
Fall-through allows multiple labels to be associated with a single action.

Question: What is the significance of break statement after default?



Answer: Fall through can occur after default too. If default is not the last label and there are other labels after it without any break in between. Therefore as a defensive programming you may add a break after default too although it is logically unnecessary.


Find output of following code:
#include <stdio.h>
main()
{
    printf ("%*d\n", 10, 20);     // P
    printf ("%*d\n", 20, 10);     // Q
}


Explanation:
In P, 10 is substituted in place of * and it indicates putting the value 20 in 10 columns.


In Q, 20 is substituted for * and it indicates putting the value 10 in 20 columns.



Question: What is the use of volatile keyword in C Language?

c with AbhasBy declaring a variable as volatile in C we instruct the compiler that the value of that variable can be changed by means outside the code such as hardware or other program. It is important to note that volatile variables can be constants (declared const) if this code is not allowed to change its value. If we declare a variable as volatile then every time such variable is encountered in the code compiler fetches its value from memory instead of using any optimizations. This ensures that we are reading the correct value of such variable. Volatile memory access is required in case of files which can be read my multiple programs simultaneously.  


c questions answers
Question: What is difference between a character stored in a char variable eg. char ch='x' and a simple character constant ‘x’?

Answer:
Look at the following code

main()
{
    char b = 'c';
    printf("size of char constant %d\n", (int)sizeof('a'));
    printf("size of char variable %d",(int)sizeof(b));
}


Output:
size of char constant 4
size of char constant 1



Explanation: According to the ANSI/ISO 99 C standard, the expression 'a' starts with type int. If you have a function void f(int) and a variable char c, then f(c) will perform integral promotion, but f('a') won't because the type of 'a' is already int.


Question: What is the significance of value returned by main in C?

c interview
Answer: It tells the environment about the status of program execution. 0 signifies normal termination and non-zero value tells some error in execution. The value returned can be displayed using echo %errorlevel% in Windows and echo $? in UNIX.

Question: In JAVA main function doesn't return any value so how can you tell the environment about the status of program execution? 



Answer:  We can use System.exit(0); or System.exit(<non-zero error code as integer>);


c interview

Question: getchar() is a library function to input a character from console. What data type you should use to store the value returned by this function?

Answer: int !!!



Explanation: EOF is an integer constant defined in stdio.h while reading characters using getchar() EOF is returned instead of ASCII value of the character when no more characters are available. Therefore we must read the input from getchar() in an integer and not char directly so that the variable is big enough to read the EOF value.


c interview
Question: If we have given a pre-processor directive in a c program as "#define <name> <replacement-text>", every occurrence of <name> in program will be replaced by the corresponding <replacement-text>

Answer: False


Explanation: Replacements won't be made when <name> occurs as part of other name Eg. <prefix-name> also replacements won't be made if <name> occurs inside quotes.




c questions
Question: What is the output for following code snippet?

float d=22.44;
printf("%-8.1f",d);
printf("%-8.1f",d);



Answer: %X.Yf prints a float value right justified in X columns up to 1 digit after decimal. Minus can be used in format specifier to make the text left justified. Thus the code tells to print 22.44 as 22.4 left justified in a column whose width is eight.



c interview questions answers
Question: What are the input and output functions defined in C language?


Answer: There is no input or output function defined in c language. printf & scanf are parts of standard input output library that is normally accessible to a c program. The behaviour of standard input output functions are defined in ANSI standard and its properties should be same in any compiler that follows the standards.




Question: Find the output of following snippet

#include <stdio.h>
int main(){
   int c,f=100;
   c=5/9*(f-32); //A
   printf("%d\n",c);
   c=5.0/9.0*(f-32);//B
   printf("%d\n",c);
   c=5*(f-32)/9;//C
   printf("%d\n",c);
   getch();  

}



Output:
0
37
37


Explanation: In c automatic truncation to integer is done for int data type variables. On using float/double constant same can be prevented with the help of automatic type promotion.

Thursday, October 3, 2013

10 C Interview Questions and Answers

c interview questions and answers
In this post you can find 10 Latest c interview questions and answers. These are some of the best c language questions asked  to freshers in technical interviews. I have tried to provide answers with full explanation. If you are looking for simple c questions then you can have look at my previous posts. You may ask all your doubts by commenting in the post. I'll try my best to answer your questions at earliest.

C Placement questions answers for beginners

Question 53. Compare arrays and pointers {Give both similarities and difference}.

Answer: Array is nothing but a pointer in disguise. Array name stores base address of array. Thus we can say array points to a memory location of fixed size of a particular data type.
arr[1] is same as *(arr+1)
{In fact 1[arr] is same as arr[1] because they both are converted into *(1+arr) and *(arr+1)}
However array is not same as pointer. We may make a pointer point to an arbitrary location however an array always points to a constant memory location.
Eg.
int a[5]={1,2,3,4,5};
int *p=a;
=>p=&a[2]; or p++; are both correct but similar statements for array 'a' will invoke error.

C Pointer placement question answer with explanation

Question 54. Find output of C snippet given below (Assume address of variable ‘a’ is 100):

int main(){
  int a=5;
  int *p=&a;
  int x=(*p)++;// P
 printf("%d %d %u ",a,x,p);
  x=*p++; //Q
  printf("%d %d %u",a,x,p);
  getch();
}

Output
6 5 100
6 6 104

Explanation:
P: Increments a by one and stores old value in x => x=5 a incremented to 6
Q: This will make pointer move ahead and give value at the location pointed by it previously =>x=6, a remains 6

Advanced c programming question answer on strings

 Question 55. Explain the difference between a character array and a character pointer.

Answer:
int main(){
    char *cp = "Hello world";//Character pointer
 
    printf("%s\n",cp);
    //will place Hello world in the read-only parts of the memory
    //and making cp a pointer to that, making any writing operation on this memory illegal. While doing:
    //*(cp+1)='a'; is runtime error
 
    char s[] = "Hello world";//array of characters
    //puts the literal string in read-only memory and copies the string to newly allocated memory on the stack.
   //Making
 
    s[0] = 'J';//correct
    printf("%s",s);
    getch();
}

Tricky C Interview question on dangling pointers


Question 56. Find output of following C code:

char *getString()
{
    char str[] = "Will I be printed?";   
    return str;
}
int main()
{
    printf("%s", getString());
    getchar();
}

Output: Some garbage value
(PS:On running in Dev C++ I am getting warning in compilation "Function returns address of local variable" and no output)
The above program doesn't work because array variables are stored in Stack Section and have a definite lifetime. So, when getString returns, value at str are deleted and str becomes <dangling pointer>.

C Interview question on library function


Question 57. C library function to find the data type of variable

Answer:

int main(){
 
    int a=2;
    typeof(a) b=1;
    printf("%d %d",a,b);//2 1
    getch();
}

C Tricky interview question with answer and explanation

Question 58

#include<stdio.h>
void change()
{
  // Add a statement here such that printf in main prints 5
}


int main()
{
int i;
i=5;
change();
i=10;
printf("%d",i); /* this should print 5*/
getch();
}

Answer:

#define printf(x,y) printf("5")
You can use macro to change the default behaviour of library functions as well.

C interview question answer on pointer to function

 Question 59. Find Output of following code:

int fun(int a){
    printf("In fun %d\n",a);
    return a+1;
}
int fun2(int a){
    printf("In fun %d\n",a);
    return a-1;
}

int main(){
    int (*ptr)(int);
    ptr=fun;
    int x=(*ptr)(3);
   
    printf("In main %d\n",x);
   
    ptr=fun2;
     x=(*ptr)(3);
   
    printf("In main %d\n",x);
    getch();
}

Output:
In main 4
In main 2
27

C Interview question on structure

Question 60. Find output of following C code

int main(){
 struct test{
    char a;
    int b;   
 }t;
 printf("%d",sizeof(t)); 
 getch();     
}

Answer: Size might be 8 and not 5 as expected

Explanation: Size of structure might NOT be sum of size of its elements. It is large enough to hold all the members. There might be unnamed holes in memory due to alignment requirements.
28

C placement question answer for technical interviews

 Question 61. Find output of following code:

short func(short x) { 
   printf(“Hello World");    // P
   return x;
}

int main() {
   printf("%d", sizeof(func(3)));
   return 0;
}

Output
2
Explanation:
P: This statement is not executed since fun() is not called.
sizeof is a compile time operator. Operand is evaluated only if it is a variable length array. In above case all that matters to sizeof is the return type of the function.

C Interview question answer on structure pointer


Question 62. Find output of following C code
struct a{
   int b;
   int c;
   int d;
}i={7,2,3};
int main(){
    struct a *p=&i;
    printf("%d %d ",*p);
    getch();
}

Answer:
7 2
If we change the printf statement to printf("%d %d %d",*p); then 7 2 3 is displayed


Sunday, September 15, 2013

C Debugging Interview question

Find output of following code:

c interview questionsint main(){
    register int a=5;
    int *rp=&a;
    int **rpp=&rp
    printf("%d\n",**rp);  
    getch(); 
}

Answer: Error
Explanation: We can’t request address of a register variable. It is illegal to apply & operator to a variable declared as a register.

Basic C interview questions for Mass companies like Accenture, TCS, Infosys & Wipro

In this post freshers seeking job in IT sector can find some basic definitions related to c language. Such definitions are usually asked by companies such as TCS, CTS, Infosys, Accenture and Wipro during mass recruitment.

C Interview questions answers

Collection of Simple C Interview Questions: 

#1 Variable: named memory location used to store value of particular data type.
#2 Data type: Means to identify the type of data. Eg. int, float, char
#3 Pointers: A special type of variable that stores address of another variable.
#4 Compound Statement: Group of statements enclosed in {}
#5 Identifier: Names given by programmer to various parts of program. Eg. In int a=5; ‘a’ is an identifier.
#6 Token: Smallest individual unit of a program. Eg. variable, constants.
#7 function: Group of statements used to perform a particular task. It may or may not accept parameters and may or may not return a value. They help in code re-usability.
#8 Keyword: Words which convey special meaning to compiler. Eg. for, int, while etc.
#9 Recursion: When a function calls itself.
#10 Array: Collection of similar data type stored in contiguous memory location.
#11 structure: Collection of data of any data type stored in contiguous memory space.
#12 String: Array of character.

Other simple C language questions asked in mass companies:

#13 Difference between = and == operator
#14 Differences between C and C++
#15 Difference between for(), while and do while loops.
#16 Types of storage class in C (auto, register, extern and static)
#17 Program to reverse a number
#18 C program to swap numbers with and without temporary variable.
#19 Difference between structure and union.
#20 What is typedef.
#21 What is void pointer.
#22 What is null pointer.
#23 Differences between actual parameter and formal parameter.
#24 What is a function definition?
#25 What is a function signature?
#26 Differentiate between call by address and call by value.
#27 Differentiate between switch and if statement.
#28 Difference between malloc() and calloc()
#29 C Program to print factorial of a number.
#30 C Program to find sum of matrix
#31 C sorting programs: bubble, insertion and selection
#32 C code for linear and binary search

#33 What are type casting and type promotion?