Saturday, April 19, 2008

C++ interview questions


  1. What will print out?

    main()
    {
    char
    *p1=“name”;
    char
    *p2;
    p2=(char*)malloc(20);
    memset (p2, 0, 20);
    while(*p2++ = *p1++);
    printf
    (“%s\n”,p2);

    }

    Answer:empty string.

  2. What will be printed as the result of the operation below:
    main()
    {
    int
    x=20,y=35;
    x=y++ + x++;
    y= ++y + ++x;
    printf
    (“%d%d\n”,x,y);

    }

    Answer : 5794

  3. What will be printed as the result of the operation below:
    main()
    {
    int x=5;
    printf(“%d,%d,%d\n”,x,x< <2,x>>2);

    }

    Answer: 5,20,1

  4. What will be printed as the result of the operation below:
    #define swap(a,b) a=a+b;b=a-b;a=a-b;

    void main()
    {
    int x=5, y=10;
    swap (x,y);
    printf(“%d %d\n”,x,y);
    swap2(x,y);
    printf(“%d %d\n”,x,y);
    }

    int swap2(int a, int b)
    {
    int temp;
    temp=a;
    b=a;
    a=temp;
    return 0;

    }

    Answer: 10, 5
    10, 5

  5. What will be printed as the result of the operation below:
    main()
    {
    char *ptr = ” Cisco Systems”;
    *ptr++; printf(“%s\n”,ptr);
    ptr++;
    printf(“%s\n”,ptr);

    }

    Answer:Cisco Systems
    isco systems

  6. What will be printed as the result of the operation below:
    main()
    {
    char s1[]=“Cisco”;
    char s2[]= “systems”;
    printf(“%s”,s1);
    }

    Answer: Cisco

  7. What will be printed as the result of the operation below:
    main()
    {
    char *p1;
    char *p2;

    p1=(char *)malloc(25);
    p2=(char *)malloc(25);

    strcpy(p1,”Cisco”);
    strcpy(p2,“systems”);
    strcat(p1,p2);

    printf(“%s”,p1);

    }

    Answer: Ciscosystems

  8. The following variable is available in file1.c, who can access it?:
    static int average;

    Answer: all the functions in the file1.c can access the variable.

  9. WHat will be the result of the following code?
    #define TRUE 0 // some code

    while(TRUE)
    {

    // some code

    }

    Answer: This will not go into the loop as TRUE is defined as 0.

  10. What will be printed as the result of the operation below:
    int x;
    int modifyvalue()
    {
    return(x+=10);
    }

    int changevalue(int x)
    {
    return(x+=1);
    }

    void main()
    {
    int x=10;
    x++;
    changevalue(x);
    x++;
    modifyvalue();
    printf("First output:%d\n",x);

    x++;
    changevalue(x);
    printf("Second output:%d\n",x);
    modifyvalue();
    printf("Third output:%d\n",x);

    }

    Answer: 12 , 13 , 13

  11. What will be printed as the result of the operation below:
    main()
    {
    int x=10, y=15;
    x = x++;
    y = ++y;
    printf(“%d %d\n”,x,y);

    }

    Answer: 11, 16

  12. What will be printed as the result of the operation below:
    main()
    {
    int a=0;
    if(a==0)
    printf(“Cisco Systems\n”);
    printf(“Cisco Systems\n”);

    }

    Answer: Two lines with “Cisco Systems” will be printed.

  13. What is C++?

    Released in 1985, C++ is an object-oriented programming language created by Bjarne Stroustrup. C++ maintains almost all aspects of the C language, while simplifying memory management and adding several features - including a new datatype known as a class (you will learn more about these later) - to allow object-oriented programming. C++ maintains the features of C which allowed for low-level memory access but also gives the programmer new tools to simplify memory management.
  14. What is the difference between realloc() and free()?

    The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, no action will occur. The realloc subroutine changes the size of the block of memory pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and returns a new pointer to the block. The pointer specified by the Pointer parameter must have been created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer.
  15. What is function overloading and operator overloading?Function overloading: C++ enables several functions of the same name to be defined, as long as these functions have different sets of parameters (at least as far as their types are concerned). This capability is called function overloading. When an overloaded function is called, the C++ compiler selects the proper function by examining the number, types and order of the arguments in the call. Function overloading is commonly used to create several functions of the same name that perform similar tasks but on different data types.
    Operator overloading allows existing C++ operators to be redefined so that they work on objects of user-defined classes. Overloaded operators are syntactic sugar for equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the language (but they can improve understandability and reduce maintenance costs).
  16. What are the advantages of inheritance?

    It permits code reusability. Reusability saves time in program development. It encourages the reuse of proven and debugged high-quality software, thus reducing problem after a system becomes functional.
  17. What do you mean by inline function?
    The idea behind inline functions is to insert the code of a called function at the point where the function is called. If done carefully, this can improve the application's performance in exchange for increased compile time and possibly (but not always) an increase in the size of the generated binary executables.
  18. Write a program that ask for user input from 5 to 9 then calculate the average
    #include "iostream.h"
    int main() {
    int MAX = 4;
    int total = 0;
    int average;
    int numb;
    for (int i=0; i
    cout << "Please enter your input between 5 and 9: "; cin >> numb;
    while ( numb<5>9) {
    cout << "Invalid input, please re-enter: "; cin >> numb;
    }
    total = total + numb;
    }
    average = total/MAX;
    cout << "The average number is: " <<> return 0;
    }
  19. Write a short code using C++ to print out all odd number from 1 to 100 using a for loop
    for( unsigned int i = 1; i < = 100; i++ ) if( i & 0x00000001 ) cout <<>
  20. What is the difference between declaration and definition?
    The declaration tells the compiler that at some later point we plan to present the definition of this declaration.
    E.g.: void stars () //function declaration
    The definition contains the actual implementation.
    E.g.: void stars () // declarator
    {
    for(int j=10; j>=0; j--) //function body
    cout<<”*”; cout<

  21. What is the difference between an ARRAY and a LIST?
    Answer1
    Array is collection of homogeneous elements.
    List is collection of heterogeneous elements.

    For Array memory allocated is static and continuous.
    For List memory allocated is dynamic and Random.

    Array: User need not have to keep in track of next memory allocation.
    List: User has to keep in Track of next location where memory is allocated.

    Answer2
    Array uses direct access of stored members, list uses sequencial access for members.

    //With Array you have direct access to memory position 5
    Object x = a[5]; // x takes directly a reference to 5th element of array

    //With the list you have to cross all previous nodes in order to get the 5th node:
    list mylist;
    list::iterator it;

    for( it = list.begin() ; it != list.end() ; it++ )
    {
    if( i==5)
    {
    x = *it;
    break;
    }
    i++;
    }
  22. What is the difference between class and structure?
    Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
    Class: Class is a successor of Structure. By default all the members inside the class are private.

  23. What do you mean by inheritance?
    Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

  24. What is virtual class and friend class?
    Friend classes are used when two or more classes are designed to work together and need access to each other's implementation in ways that the rest of the world shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.
  25. What is a class?
    Class is a user-defined data type in C++. It can be created to solve a particular kind of problem. After creation the user need not know the specifics of the working of a class.
  26. What is abstraction?
    Abstraction is of the process of hiding unwanted details from the user.
  27. What is polymorphism? Explain with an example?
    "Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or reference) to assume (be replaced by) or become many different forms of object.
    Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings
  28. How do you decide which integer type to use?
    It depends on our requirement. When we are required an integer to be stored in 1 byte (means less than or equal to 255) we use short int, for 2 bytes we use int, for 8 bytes we use long int.

    A char is for 1-byte integers, a short is for 2-byte integers, an int is generally a 2-byte or 4-byte integer (though not necessarily), a long is a 4-byte integer, and a long long is a 8-byte integer.
  29. What does extern mean in a function declaration?
    Using extern in a function declaration we can make a function such that it can used outside the file in which it is defined.

    An extern variable, function definition, or declaration also makes the described variable or function usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.

    If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.
  30. What is the difference between char a[] = “string”; and char *p = “string”;?
    In the first case 6 bytes are allocated to the variable a which is fixed, where as in the second case if *p is assigned to some other value the allocate memory can change.
  31. What’s the auto keyword good for?
    Answer1
    Not much. It declares an object with automatic storage duration. Which means the object will be destroyed at the end of the objects scope. All variables in functions that are not declared as static and not dynamically allocated have automatic storage duration by default.

    For example
    int main()
    {
    int a; //this is the same as writing “auto int a;”
    }

    Answer2
    Local variables occur within a scope; they are “local” to a function. They are often called automatic variables because they automatically come into being when the scope is entered and automatically go away when the scope closes. The keyword auto makes this explicit, but local variables default to auto auto auto auto so it is never necessary to declare something as an auto auto auto auto.

  32. How do I declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
    Answer1
    If you want the code to be even slightly readable, you will use typedefs.
    typedef char* (*functiontype_one)(void);
    typedef functiontype_one (*functiontype_two)(void);
    functiontype_two myarray[N]; //assuming N is a const integral

    Answer2
    char* (* (*a[N])())()
    Here a is that array. And according to question no function will not take any parameter value.

  33. What does extern mean in a function declaration?
    It tells the compiler that a variable or a function exists, even if the compiler hasn’t yet seen it in the file currently being compiled. This variable or function may be defined in another file or further down in the current file.

  34. How do I initialize a pointer to a function?
    This is the way to initialize a pointer to a function
    void fun(int a)
    {

    }

    void main()
    {
    void (*fp)(int);
    fp=fun;
    fp(1);

    }
  35. How do you link a C++ program to C functions?
    By using the extern "C" linkage specification around the C function declarations.
  36. Write a program to find the binary form for the given charcter input.
    eg:- for 'A' ASCII value is 65 and its binary form is 1000001.
    #include
    #include
    #define MAX_SIZE 10

    void main()
    {
    int d,i,j[MAX_SIZE],k = MAX_SIZE - 1,l ;
    char a;

    clrscr();

    for ( i = 0 ; i <= MAX_SIZE ; i++ ) { j[i] = 0 ; } printf("n Enter the Letter " ) ; scanf ( "%c",&a) ; printf ( "n The Input is : %c",a) ; d = (int) a; printf ( " n The Decimal Format of %c is : %d " ,a,d ) ; i = d ; do { l = i%2 ; j[k] = l ; i = i/2; k-- ; }while ( i != 0 ); i = 0 ; l = 0 ; while ( j[i] == 0 ) { i++ ; l++ ; } printf ( " n The Binary Format of %c is : ",a ); for ( i = l ; i <>
  37. How many ways are there to initialize an int with a constant?
    Two.
    There are two formats for initializers in C++ as shown in the example that follows. The first format uses the traditional C notation. The second format uses constructor notation.
    int foo = 123;
    int bar (123);

  38. n C++, what is the difference between method overloading and method overriding?
    Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class.
  39. Differences of C and C++
    Could you write a small program that will compile in C but not in C++ ?

    In C, if you can a const variable e.g.
    const int i = 2;
    you can use this variable in other module as follows
    extern const int i;
    C compiler will not complain.

    But for C++ compiler u must write
    extern const int i = 2;
    else error would be generated.
  40. What is an accessor?
    An accessor is a class operation that does not modify the state of an object. The accessor functions need to be declared as const operations

  41. What is a Null object?
    It is an object of some class whose purpose is to indicate that a real object of that class does not exist. One common use for a null object is a return value from a member function that is supposed to return an object with some specified properties but cannot find such an object.

  42. Name some pure object oriented languages.
    Smalltalk, Java, Eiffel, Sather.

  43. How do you write a function that can reverse a linked-list?
    Answer1:

    void reverselist(void)
    {
    if(head==0)
    return;
    if(head-
    return;
    if(head-
    {
    head-
    tail-
    }
    else
    {
    node* pre = head;
    node* cur = head-
    node* curnext = cur-
    head-
    cur-

    for(; curnext!=0; )
    {
    cur-
    pre = cur;
    cur = curnext;
    curnext = curnext-
    }

    curnext-
    }
    }

    Answer2:

    node* reverselist(node* head)
    {
    if(0==head || 0==head->next)
    //if head->next ==0 should return head instead of 0;
    return 0;

    {
    node* prev = head;
    node* curr = head->next;
    node* next = curr->next;

    for(; next!=0; )
    {
    curr->next = prev;
    prev = curr;
    curr = next;
    next = next->next;
    }
    curr->next = prev;

    head->next = 0;
    head = curr;
    }

    return head;
    }
  44. What is the difference between Stack and Queue?
    Stack is a Last In First Out (LIFO) data structure.
    Queue is a First In First Out (FIFO) data structure
  45. Write a fucntion that will reverse a string.
    char *strrev(char *s)
    {
    int i = 0, len = strlen(s);
    char *str;
    if ((str = (char *)malloc(len+1)) == NULL)
    /*cannot allocate memory */
    err_num = 2;
    return (str);
    }
    while(len)
    str[i++]=s[–len];
    str[i] = NULL;
    return (str);

    truck insurance
    truck insurance Counter



No comments: