Showing posts with label c interview questions. Show all posts
Showing posts with label c interview questions. 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?

Saturday, August 11, 2012

Pointers in c questions for interview


In this article I will be posting some good c pointer interview questions answers. Pointers in C are special type of variables that are used to point the value of particular data type by storing address of that particular data type. Pointers in c play role in call by reference when we want any change in formal parameter to get reflected in actual parameters. In this post you can find some basic pointer questions in c.

C pointers questions and answers subjective type

  • What is a pointer?
  •  How to make a pointer to pointer data type?
  • Explain call by reference using pointers in c.
  • Explain pointer to functions in c language.


Function pointers in C

Function Pointers are variables, which point to the address of a function. A running program gets a certain space in the main-memory. Both, the executable compiled program code and the used variables, are put inside this memory. Thus a function in the program code is nothing more than an address.

Syntax to create function pointers in c
 return type (*fnPointer) (arguments-list);

We can assign address of similar function (with same arguments list, return type) by writing
fnPointer=&fnName; // or fnPointer=fnName;

Now we can call the function being pointed as
(*fnPointer)(argument-list);

·         Explain the use of generic pointers/void pointer in C.
Generic pointers in C are useful when we want same variable to point to different variables at different times.
Example c program for generic pointer (source: http://www.faqs.org/docs/learnc/x658.html):
main()
{
  int i;
  char c;
  void *the_data;

  i = 6;
  c = 'a';

  the_data = &i;
  printf("the_data points to the integer value %d\n", *(int*) the_data);

  the_data = &c;
  printf("the_data now points to the character %c\n", *(char*) the_data);

  return 0;
}
Generic pointers can’t be dereferenced directly. We can’t write *the_data in above code. We need to first do type casting and then dereference them

More interview questions on pointers in c (Multiple choice type objective questions)
You can also download this post as pdf at

Friday, July 13, 2012

C interview Programs and Programming related questions answers [PDF]

In this post I will try to answer some common c interview questions related to coding or programming as a sample. You will find links to several solved c programming questions answers in this post that can help you to prepare for c interview. I will try my best to provide as many c interview programs as possible.

C in one of the first language taught to engineering students. Therefore knowledge of c is judged in interviews of both fresher’s as well as experienced programmers. C programs listed here can help freshers and even people with 1-3 years of experience in programming. Some typical c programs questions asked in interview are mentioned below:

C Interview code snippets | Good c interview question with answers for test


More commonly asked c interview question programs


Pattern questions asked in technical c interviews
*                   *
* * *           * * *
* * * * *   * * * * *
* * * * * * * * * * *
1
121
12321
1234321
12321
121
1
       2
     4 5 6
   6 7 8 9 10
     4 5 6
       2
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1

Friday, June 1, 2012

Very common C Interview questions answers programs

In this post you can find some very general and basic commonly asked c interview questions programs solved. If you are properly trained in C language and have good knowledge of basic concepts of your programming in c course content then it would be easy for you to crack such cool interview question. For more help on C Interview questions you must check out this page which has huge collection of best c interview puzzles.


Sample program questions with code :


Write a program in C to display a message without using semi colon anywhere in program

Answer:
#include <stdio.h>
void main()
{
if(printf(”Hello”))
{}
}
We can write the printf inside while or switch as well for same result.


Write a c program to add two numbers without add operator?
Use two subtract operators together to work as add operator.
#include <stdio.h>
#include <conio.h>
int main(){
          int a=1,b=2,c;
          c=a-(-b);
          printf(“%d”,c);
          getch();
          return 0;

C Interview Questions | Common C pointer Interview question with solution

C Pointer/string interview questions answers


What is Output of following c snippet?
int main(){
   char *s="Abhas";
   printf("%s",s+s[1]-s[3]); 
   getch();
}
Answer:
bhas
Reason: In the above program role of %s is to display the string whose address is passed as an argument. This is how a standard printf statement works in c language. Now since we have passed s- s[1]+ s[3] as an argument therefore first value of this expression is evaluated. Here ‘s’ would refer to address of first character in string ‘s’. Since we are subtracting s[1] from s[3] characters at corresponding position (that are ‘a’ and ‘b’) would be subtracted.  On subtracting ‘a’ from ‘b’ (ASCII Value) we get 1 which is added to address of first character in ‘s’ (also referred as ‘s’). Now printf would get address of second character (address of first character + 1) as argument so it will display the string starting from second position.  Hence output is bhas.

Monday, May 28, 2012

C Interview debugging questions | Find error in snippet type C Interview questions


Debugging questions are common in C Language interviews. In this post you can find some example c interview questions related to debugging.


Find error in following c snippet?
#include <stdio.h>
#include <conio.h>
int x;
int x=0;
int x;
int main(){
   printf("%d",x); 
   getch();
   return 0;
}
Answer:
No error. Global variables can have several declarations in C. Same is true for function declarations.

Find error in following c snippet?
#include <stdio.h>
#include <conio.h>
int x;
int x=0;
int x;
int x=1;
int main(){
   printf("%d",x); 
   getch();
   return 0;
}
Answer:
Error in Line number 6. Global variables can have several declarations in C but only one definition. Same is true for function declarations.

Also check out C interview example programs Questions exercises

You can find more such c interview question in related post mentioned below:

C interview example programs Questions exercises

Here are some common C Interview programming exercise technical questions answers usually asked from freshers in B.Tech Computer science or Information technology by most IT companies.

Frequently asked c programs interview questions


1. Write a program to display a message without using semi colon anywhere in program.

2. Write a program in C language to swap two numbers without using third variable or any mathematical operator.
(Hint: Use logical operator XOR)

3. Write a C data structure implementation of link list and code a function that can reverse the singly linked list without using any additional link list.
(Hint: You must reverse each link as you are traversing the link list and you must keep note of next element in some variable (before reversing the link) because when you reverse the link address of its old next element would be lost.)

4. C Interview Programs to print patterns : 

1  2  3  4
5  6  7
8  9
10 

1 1 2 3 5 8 13 21

1   2   3   4
12 13 14 5
11 16 15 6
10 9   8   7
         
1
12
123
1234
12345

1    1
 2  2
   3
 4  4
5    5

5. Write a program in c language to concatenate two strings without using library functions.


For more c interview question programs etc. click here

Check out more C interview questions in related posts below. In this blog you can also find number of free pdf which you can download and read later.

C interview basic questions and answers for freshers

Free download c interview programs as pdf

Friday, April 27, 2012

C interview basic questions and answers for freshers

Latest collection of interview questions on C for freshers. Find output type c interview question involving string concept.


What is Output of following c snippet?
int main(){
   char *s="Abhas";
   printf("%s",s+ 2); 
   getch();
}
Answer:
has
Explanation: In the above program role of %s is to display the string whose address is passed as an argument. This is how a standard printf statement works in c language. Now since we have passed s + 2 as an argument therefore first value of this expression is evaluated. Here ‘s’ would refer to address of first character in string ‘s’. Now printf would get address of third character (address of first character + 2) as argument so it will display the string starting from third position.  Hence output would be ‘has’.

50 C Interview Questions Answers
Logical C Interview Questions Answers

Find more objective c interview questions answers. Download latest pdf on c interview questions and answers, Test your c skills. 

Free download c interview programs as pdf

Simple C Interview questions and definitions

Read more related posts below.


C interview test Questions and Answer in DOC

Test type subjective logical C interview questions answers




Give two use of bitwise and (&) operator?

It can be used to check whether particular bit is set or not. Eg suppose we have a number 101. Now if we want to check whether its second bit is on or off. To know this we must simply do bitwise and operation on this number with 010. Since result is 0 therefore we can acknowledge that second bit is low in our case.

It can be used to unset particular bit. Eg if you want to unset second LSB of any number then you must simply do bitwise operation between that number and …11111101.




You can see the related posts for more c interview questions answers.

Also you can find some questions mentioned in this website in doc and pdf format uploaded at mediafire.com in one of these related blog post.