Monday, March 24, 2008

Tricky C questions @ Tech Interviews.com

Tricky C questions @ Tech Interviews.com
  1. How do you write a program which produces its own source code as its output?
  2. How can I find the day of the week given the date?
  3. Why doesn’t C have nested functions?
  4. What is the most efficient way to count the number of bits which are set in a value?
  5. How can I convert integers to binary or hexadecimal?
  6. How can I call a function, given its name as a string?
  7. How do I access command-line arguments?
  8. How can I return multiple values from a function?
  9. How can I invoke another program from within a C program?
  10. How can I access memory located at a certain address?
  11. How can I allocate arrays or structures bigger than 64K?
  12. How can I find out how much memory is available?
  13. How can I read a directory in a C program?
  14. How can I increase the allowable number of simultaneously open files?
  15. What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?

58 Responses to “Tricky C questions”

  1. Manoj Kumar Bana Says:

    Q. How do you write a program which produces its own source code as its output?
    Ans:
    #include
    #include

    using namespace std;
    int main()
    {
    char buf[100];
    string str;
    int size=100;
    ifstream in(”filename.cpp”,ios::in);
    while(!in.eof())
    {
    while(in.getline(buf,size))
    {
    str=buf;
    cout

  2. viral Says:

    How can I return multiple values from a function?
    ans. return structure from function which can hold multiple variable

  3. viral Says:

    What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?
    Ans. as c:\\newdir\file.dat contains escape charatcer i.e. “\” which internally means to escape character following “\” hence we need to provide double back slash “\\”.

  4. Mike Mountrakis Says:

    1.How do you write a program which produces its own source code as its output?
    Ans:
    Supposing that our executable has the same name with source code file
    and source code file has an exentsion of .c:

    #incude
    int main(int argc, char * argv[] )
    {
    FILE * fp,
    int c;
    char fname[100] = {”};

    if( argc day, today->month, today->year );
    mktime(today);
    DayOfWeek = today->tm_wday;
    if( DayOfWeek == 0 )
    printf(”Sunday”);
    …..
    else if ( DayOfWeek == 6 )
    printf(”Saturday”);

    3. Why doesn’t C have nested functions?
    C Compilers do not allow class types so they do not support internal function reference table like a C++ compiler does.
    Instead, you can use a structure having members function pointers. Older C++ compilers use to transform the C++ sources to C using this isomorphic transformation.

    4. What is the most efficient way to count the number of bits which are set in a value?
    Ans:
    What type of data ? What architecture (Big endian or Little endian)?
    In general:
    Use sizeof() to get the size of type.
    Use logical AND with the maximum value of the type and the given value.
    Count the maximum position in architecture’s bit order that is set to 1 in the result of the previous step.

    5. How can I convert integers to binary or hexadecimal?
    Ans:
    In order to print them use appropriate format in printf.
    In order to assign them use specifiers like
    int x = FFx; x = 101110b;
    Integers are kept in the same format inside program’s heap/stack.

    6. How can I call a function, given its name as a string?
    Ans:
    Simple way (students)

    void foo( void );
    void zoo( void );

    void caller( const char * fname )
    {

    if( strcmp(fname,”foo”) == 0 )
    foo();
    else if ( strcmp(fname,”zoo”) == 0 )
    zoo();
    else
    default;
    }
    Better Way:
    Use an XML schema that describes keywords associated with functions implemented as dynamic libraries. Use expat library to parse the elements and call functions.

    Correct Way:
    Use a lexer and compiler builder (lex,yacc) to create a set of tokens and handler functions. Good but time expensive way.

    Compile the function as a dll and call it during run time using

    7. How do I access command-line arguments?
    Ans :
    Declare your main() like:

    int main(int argc, char * argv[])
    {
    }
    argc is the number of arguments stated in the command line.
    Use argv[0] to get the program (process) name
    Use argv[1],…, to argv[argc-1] to get the command lines

    8 How can I return multiple values from a function?
    Ans:
    Return a structure that has been previously allocated. This structure holds all the values to be returned. Example follows:

    struct MyStruct * foo( struct MyStruct * in )
    {
    in->member1 = …
    ….
    in->memberN = …
    return in;
    }

    The most ordinary solution: Allow many pointers as arguments and assign values inside the body of function

    void * foo1( int * out1, char *out2 , …. , my_t * outN )
    {
    *out1 = 10;
    *out2 = ‘Y’;

    outN = …
    }

    9 How can I invoke another program from within a C program?

    Ans:
    Use in UNIX use the exec, execl, execv, execle, execve, execlp, execvp functions.

    10 How can I access memory located at a certain address
    Ans :
    Use a pointer to that address.

    11 How can I find out how much memory is available?
    Ans:
    In your user memory quota? In the system’s quota??
    try this simple program to access memory quota available for a process.

    #include
    #define KEY 1024
    main()
    {
    char *p;
    unsigned long i;

    for (i=0; ; i++ )
    {
    p = (char * )malloc( i * KEY * KEY );
    if ( p== null )
    break;
    }
    printf(”I can use %ul keys.”, i );
    }
    To check the memory available you need to access systems spcific calls like UNIX free

    12 How can I read a directory in a C program?
    Ans:
    Like the following code illustrates:

    #include “stdio.h”
    #include “dirent.h”
    #include “errno.h”
    int main()
    {
    DIR *pdir;
    struct dirent *pfile;

    if (!(pdir = opendir( “MyDirectoryPath” ) ) )
    {
    perror(”Can’t open this directory.”);
    return 1;
    }

    while( (pfile = readdir(pdir)) )
    {
    if ( 0 == strcmp(pfile->d_name,”.”) )
    continue;
    else if( 0 == strcmp(pfile->d_name,”..”) )
    continue;
    else
    printf(”File : %s\n”, pfile->d_name );
    }
    return 0;
    }

    13 How can I increase the allowable number of simultaneously open files?
    Ans:
    This is system depended. In some you cannot.

    14 What’s wrong with the call fopen(”c:\newdir\file.dat”, “r”)?
    Ans:
    Special character ‘\’ is not protected from the compiler. It sould be like:
    “c:\\newdir\\file.dat”

  5. Saleem Ansari Says:

    Q)Prograon to convert an integer to binary

    char *uitob(char *s, unsigned int i)
    {
    char *cp = s;
    unsigned int bit_mask = (UINT_MAX - (UINT_MAX >> 1));
    do
    {
    *cp++ = (i & bit_mask) ? ‘1′ : ‘0′;
    } while (bit_mask >>= 1);

    *cp = ”;
    return s;

    }

    Q)Program to counte the number of bits set to 1

    int bits_set( int word )
    {
    int tmp;

    tmp = (word >> 1) & 033333333333;
    tmp = word - tmp - ((tmp >> 1) & 033333333333);
    return (((tmp + (tmp >> 3)) & 030707070707) % 077);

    }

    Q)Why no nested functions in C?

    Got the answer from USENET:
    From a syntactic point of view, there is no “real” reason why a
    structured, imperative language like C could not have nested functions.
    The characteristics of a nested function would be that it would be just
    like an ordinary function, only that it is only callable from within the
    function it is nested in, and the local variables of that function act
    as additional global variables to the nested function.
    As a University exercise, I have had to write a syntactical analyser for
    the language Mini-Pascal, which is exactly what I am talking about, a
    structured, imperative language with nested functions. I could see
    nested functions in C working like they work in Mini-Pascal.
    There is only one thing that prevents nested functions from making sense
    in C: function pointers. Suppose a function returns a pointer to one of
    its nested functions, and someone calls that nested function directly?

    Here’s an example:

    typedef void (*function)(void);
    function foo(void) {
    int local = 0;
    void bar(void) {
    local = 1;
    }
    return bar;
    }

    int main(void) {
    function baz=foo();
    baz();
    return 0;

    }

    The way I see it, execution proceeds as normal up to the “baz();” line.
    Here the function bar() nested in foo() is called, and bar() starts
    storing 1 in the address it *thinks* belongs to local in foo() - only
    oops, no one ever bothered to allocate that address. Undefined Behaviour
    Time!
    Adding safeguards to function pointers to prevent this from happening
    would add needless baggage to the C runtime system. Perhaps this is why
    K&R chose not to include nested functions?

    Q) Program that outputs its own code

    Solution1:

    #include
    int main ()
    {
    int c;
    FILE *f = fopen (__FILE__, “r”);
    if (!f) return 1;
    for (c=fgetc(f); c!=EOF; c=fgetc(f))
    putchar (c);
    fclose (f);
    return 0;

    }

    Solution2:

    #include
    main()
    {
    printf(”itself\n”);
    exit(0);

    }

    Solution3:

    main(a){a=”main(a){a=%c%s%c;printf(a,34,a,34);}”;printf(a,34,a,34);}

    Soultion4:

    #include
    main(){char*c=”\\\”#include%cmain(){char*c=%c%c%c%.102s%cn%c;printf(c+2,c[102],c[1],*c,*c,c,*c,c[1]);exit(0);}\n”;printf(c+2,c[102],c[1],*c,*c,c,*c,c[1]);exit(0);}

  6. lalitsingh Says:

    above Q & ans are very interesting i have got one more Q

    Qwithout using third variable how to swap two variable
    ans
    a=a+b;
    b=a-b;
    a=a-b;
    this que was asked to me in my interview

  7. Sango Says:

    >Qwithout using third variable how to swap two variable
    >ans
    >a=a+b;
    >b=a-b;
    >a=a-b;
    >this que was asked to me in my interview

    One more way,
    a = a*b
    b = a/b
    a = a/b

    -cheers,
    SB

  8. Arka Mandal Says:

    may i know what is GUTTER in windows?

  9. Nabarun Sengupta Says:

    Q> swap two variables without using third variable in a line?
    A> main()
    {
    int a,b;
    a=10;
    b=20;
    a^=b^=a^=b;
    printf(”%d%d”,a,b);
    }

  10. Adarsh Says:

    hi 2 question to be solved
    1)print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!
    2) print numbers till we want without using loops or condition statements like specifically(for,do while, while swiches, if etc)!!!!!

  11. Parameshwar Hegde Says:

    1.How do you write a program which produces its own source code as its output?
    Ans:
    #include
    #include

    int main()
    {
    char str[2000];
    fstream file_op(”path_of_the_file”,ios::in);
    while(!file_op.eof())
    {
    file_op.getline(str,2000);
    cout

  12. manohar Says:

    print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!

    void main()
    {
    if(printf(”;”))
    {}
    }

    Manohar

  13. barnali basak Says:

    what is the difference between #include and #include”filename”?

  14. MANV Says:

    solution4:-
    …….
    int num=10; //one can have any value
    int count=0;

    while(num>0)
    {
    num=num&(num-1);
    count++;
    }
    ………

  15. shanky Says:

    int i;
    size of(i)
    options:
    is it
    1.)compiler dependant
    2.)machine dependant

  16. Ravi Gupta Says:

    Give a one-line C expression to test whether a number is a power of 2.
    [No loops allowed - it’s a simple test.]

  17. solidcube Says:

    All the above answers to question 1 are naive. It’s a trick question and it’s designed to separate the manual labor programmers from the guys who actually know what they’re doing.

    Try doing it without filesystem calls or “cute” tricks and it enters a whole new order of complexity.

    This type of program is called a quine. It’s been described by Hofstader among others.

    Here’s an analogous problem. Try to write a sentence that enumerates exactly how many of each letter that the sentence contains.

    As in: “This sentence contains five a’s, six b’s…”

    Try it and you’ll see what I mean.

    You all fail the interview. Next applicant.

  18. D.K. Says:

    Give a one-line C expression to test whether a number is a power of 2.
    bool isPower = x>0 && !(x&x-1)

  19. Inman Says:

    How do you write a program which produces its own source code as its output?

    #include
    #include
    #include

    int main()
    {
    char buf[100];
    char *str;
    int size=100;
    ifstream in(__FILE__,ios::in);
    while(!in.eof())
    {
    while(in.getline(buf,size))
    {
    str=buf;
    cout

  20. Parameshwar Hegde Says:

    1.How do you write a program which produces its own source code as its output?
    Ans:
    #include
    #include
    using namespace std;

    int main()
    {
    char str[500];
    fstream file_op(”c://param/filetest.cpp”,ios::in);
    while(!file_op.eof())
    {
    file_op.getline(str,2000);
    cout

  21. Ranjeet Kumar Bhatta Says:

    Can anybody give me the source code in C ro reverse a
    number using only bitwise operators ???????????

    Thanks.

  22. Raju Says:

    pls write the progrms.
    1)program for fibnocii series.
    2)Palandrom.
    3)reverse the given nuber.
    4)count the number of words,chars,numbers,special chars in the given input throuh commandline args

  23. Vipin PV Says:

    print a semicolon using Cprogram without using a semicolon any where in the C code in ur program!!!!

    void main()
    {
    if(printf(”%c\n”,59))
    {}
    }

  24. vikas kumar Says:

    The name of memory model, whose size exceeds 64K is
    (a) huge (b) large (c)medium (d)small
    (e) other

  25. Vipin P. V Says:

    Ques: int fun(int arr[], int n)
    In this function the array contains the first “n” natural numbers. Since the natuaral number includes 0 (zero) also , one number will be missing from the array. Find out the missing number in an efficient way. The array will not be in a sorted manner.

  26. MorbidAngel Says:

    #
    Sango said,

    >Qwithout using third variable how to swap two variable
    >ans
    >a=a+b;
    >b=a-b;
    >a=a-b;
    >this que was asked to me in my interview

    One more way,
    a = a*b
    b = a/b
    a = a/b

    -cheers,
    SB

    Be careful of type value range when using operator *. For example if a and b are char (1 byte representation), when multiply a by b, you can go past the 256 borde.

    Cheers,
    Morbid Angel

  27. Renganathan E Says:

    Q. How do you write a program which produces its own source code as its output?
    Ans:
    char *s=”char *s=%c%s%c;main(){printf(s,34,s,34);}”;
    main(){printf(s,34,s,34);}

  28. Ramya Says:

    Q.without using third variable how to swap two variable?
    Ans:
    a= a^b
    b= a^b
    a= a^b

  29. Ramya Says:

    Q.Give a one-line C expression to test whether a number is a power of 2.
    Ans: printf(((x&1)==0)?”TRUE”:”FALSE”);

  30. KAUSIK Says:

    Q.without using third variable how to swap two variable?
    Ans:
    a= a^b
    b= a^b
    a= a^b
    It is right.ok

    a = a*b
    b = a/b
    a = a/b

    it is worng like that
    if
    b=0;

    then the code gives the result as indefinite value.
    So To my opinion, it is not right.

  31. srikar Says:

    without using third variable how to swap two variable?
    ans:
    a=a+b;
    b=a-b;
    a=a-b;

  32. Mayank Shrivastava Says:

    Q. > How do you write a program which produces its own source code as its output?

    #include
    void main()
    {
    FILE *fp,*ft;
    char MITM[100];
    fp=fopen(”pro.c”,”r”);
    if(fp==NULL)
    {
    printf(”ERROR”);
    }
    ft=fopen(”data.txt”,”w+”);
    if(ft==NULL)
    {
    printf(”ERROR”);
    }
    while(getc(fp)!=EOF)
    {

    fscanf(fp,”%s”,MITM);
    printf(”%s\n”,MITM);
    fprintf(ft,”%s\n”,MITM);
    }
    }

  33. Fouzina Says:

    Q.print numbers till we want without using loops or condition statements like specifically(for,do while, while swiches, if etc)!!!!!
    Ans:
    static int i=0;
    main()
    {
    if (getch()==’n') exit(0);
    printf(”%d\n”,i++);
    main();
    }

  34. Ranjeet Says:

    How can I add,subtract,divide,multiply 2-numbers using bitwise operator only??

  35. Valentin Heinitz Says:

    Question 1:
    The answer of Manoj Kumar Bana is not what is required.
    This task was given once in Obfuscated C Contest, and the anwer is more trikier.

  36. ErRoR Says:

    quest: write a program of fibonacci series.
    ans :
    #include
    main()
    {
    int *fib;
    fib[0]=0;
    fib[1]=1;
    for(int i=2;;i++)
    {
    fib[i]=fib[i-1]+fib[i-2];
    }
    return 0;
    }

  37. M.A.Moscoso Says:

    Q1.

    #include “stdafx.h”
    #include

    int main(int argc, char* argv[])
    {
    FILE *fp;
    fp = fopen( argv[0] , “r” ) ;
    while ( feof( fp ) == 0 )
    printf( “%c” , fgetc( fp ) ) ;
    return 0;
    }

    Q13. - use _findfirst()

    struct _finddata_t _dirdata;
    long hFile;
    if( (hFile = _findfirst(”*.*”, &_dirdata)) != -1L)
    {
    printf( “filename: %s” , _dirdata.filename ) ;
    }

    Q14. - How to increase number of open files ?

    In your SystemRoot%\System32
    locate the “config.nt” file
    then modify the environment variable
    files=40
    increase it to your expected
    number of files to be opened, ex.
    files=100

  38. samrat Says:

    Write a prgm that prints its own output.

    Soln:
    #include
    #include>process.h>

    void main()
    {
    system(”type filename.cpp”);
    }

    filename is the name of the file in which you have saved ur prgm.

  39. samrat Says:

    How to return multiple values frm a fncn?

    Soln:
    Create an array using pointer in the calling fncn.
    Pass this pointer to the called fncn as argument.
    Store the return values in the array.

    #include

    void func(int *ptr)
    {
    ptr[0]=1;
    ptr[1]=2;
    }

    void main()
    {
    int *ptr=new int[2];
    func(ptr);
    cout

  40. Todd Says:

    I think if you encounter an interview test with some of these questions, you should just put down the pen and get as far away from that place as possible. Few of these questions help you identify a good programmer; many of the questions actually encourage horrible practice.

    (I would fire any programmer that worked for me that used one of these techniques to switch the value of two variables, excepting some sort of weird processor limitations ).

  41. Muhammed Ashref Says:

    Q. > How do you write a program which produces its own source code as its output?
    Ans:
    char*s=”char*s=%c%s%c;main(){printf(s,34,s,34);}”;main(){printf(s,34,s,34);}

  42. Uma Thangaraj Says:

    Q. > what is the difference between
    #include and #include”filename”?

    Ans:
    #include searches for the file in the include directory whereas #include “filename” searches for the file in the current working directory.

  43. Rita Says:

    I have an query regarding C program…Its how we can execute a piece of code before execution of code written in main function? e.g if in main() we have added two numbers and outside main() we have subtracted two numbers ,so I want that the output of subtractibg two numbers should come first than adding two numbers…

  44. mona Says:

    printing “;” without using “;” is like this(59 is the ascii value for “;”):

    #include”stdio.h”

    main()
    {
    if(printf(”%c”,59))
    {}
    }

  45. punit hissaria Says:

    1 prog
    reversing words in file, selecting all words with Capital letters in a file etc etc.
    2
    .write a program,to replace the strings in a file.The programs are provided with the command line agruments,arguments are string to be searched ,string which is replaced n output to another file.
    eg: in a file “str1″ string is searched n should be replaced by “str2″ in the output file.

    2.write a program using files,in a file search for string ‘a’ and if it is followed by a vowel then,replace ‘a’ by ‘an’ n save it to another file.

    3.in a file,reverse the entire line and check if palindrome words are present.

    4.write a program on file redundency .

  46. Pankaj Kolhe Says:

    I have query is that, How we can add two numbers without using ‘+’ operator ?
    &
    How we can displayinteger no after setting tenth bit is ‘1′ irrespective of final value.Display the same no after setting tenth bit to ‘0′

  47. zulquarnain Says:

    what is the output of this programe?
    main()
    {
    int i=0;
    printf(”%d%d%d%d”,–i,i++,++i,i++);
    }

  48. zulquarnain Says:

    how can u run a programme without using main?

  49. parul agrawal Says:

    /* adding of two numbers without using ‘+’ operator*/

    #include
    int sum( int,int);
    int main()
    {

    int a,b;
    int s=0;
    printf(” enter the nos\n”);
    scanf(”%d%d”,&a,&b);
    s=sum(a,b);
    printf(”%d”,s);
    }

    int sum(int x,int y)
    {
    int xor,and,temp,i;
    xor = x ^ y;
    and = (x & y);
    and

  50. parul agrawal Says:

    what is the output of this programe?
    main()
    {
    int i=0;
    printf(”%d%d%d%d”,–i,i++,++i,i++);
    }

    sol). the output will be 2220 as manipulation will start from right to left but printing from left to right

  51. St0le Says:

    Such prog. are called “Quines”. Following is a Basic Quine..

    //Quine By St0le!
    #include
    char *p=”#include %c%c char *p=%c%s%c; %c%c void main(){%c%c printf(p,13,10,34,p,34,13,10,13,10,13,10,13,10); %c%c }”;
    void main(){
    printf(p,13,10,34,p,34,13,10,13,10,13,10,13,10);
    }

  52. Devendra Singh Says:

    I have an query regarding C program…Its how we can execute a piece of code before execution of code written in main function? e.g if in main() we have added two numbers and outside main() we have subtracted two numbers ,so I want that the output of subtractibg two numbers should come first than adding two numbers…

    use #pragma

  53. Panchdev Says:

    Write a prgm that prints its own output.

    #include
    #include
    int main(){
    FILE *fp;
    char c;
    fp=fopen(”file2.cpp”,”r”);
    while((c=getc(fp))!=EOF)
    {printf(”%c”,c);}
    fclose(fp);
    getch();
    return 0;
    }

  54. chandrashekhar Says:

    Will this program is going to execute ?
    #include
    123;
    int main()
    {
    34;
    return 0;
    }
    if yes why ?
    if no why ?
    please reply fast

  55. brijesh Says:

    without using third variable how to swap two variable?
    ans:
    a=a^b;
    b=a^b;
    a=a^b;
    Advantage : with this method we can avoid overflow.

  56. st0le Says:

    better yet, use this

    a^=b^=a^=b;

  57. SHIV Says:

    To print a semicolon without using semicolon else where in the program

    #include
    void main()
    {
    if(printf(”;”))
    {}
    }

  58. Udaya Prakash Says:

    What’s wrong with the call
    fopen(”c:\newdir\file.dat”, “r”)?

    In C strings, \ should be used as \\ escape sequence.
    Therefore the right way of doing this is
    fopen(”c:\\newdir\\file.dat”, “r”)

No comments:

如何发掘出更多退休的钱?

如何发掘出更多退休的钱? http://bbs.wenxuecity.com/bbs/tzlc/1328415.html 按照常规的说法,退休的收入必须得有退休前的80%,或者是4% withdrawal rule,而且每年还得要加2-3%对付通胀,这是一个很大...