C Interview Programs in Function Pointers, string functions, fibonacci numbers

by Dhoka Ratan on February 1, 2009


c interview questions Here are five challenging questions in C language. These are subset of frequently asked C interview questions in Interview Mantra. Question.51 is an advanced question that tests the ability to declare and use function pointers and array of function pointers. Question.52(simulation of strcmp), Question.53(simulation of strcat) test the knowledge of C standard library ‘stdio.h’ and programming ability to simulate a function of known functionality. Question.54(generation of fibonacci numbers) tests the adroit ability of programming and math skills. Question.55 tests basic knowledge and ability to use control structures in C.

  1. Declare an array of three function pointers where each function receives two integers and returns float.
  2. Declaration:

    float (*fn[3])(int, int);

    Program: Illustrates the usage of above declaration

    include<stdio.h>
    float (*fn[3])(int, int);
    float add(int, int);
    
    int main() {
     int x, y, z, j;
      for (j = 0; j < 3; j++){
      fn[j] = &add;
     }
     x = fn[0](10, 20);
     y = fn[1](100, 200);
     z = fn[2](1000, 2000);
     printf("sum1 is: %d \n", x);
     printf("sum2 is: %d \n", y);
     printf("sum3 is: %d \n", z);
     return 0;
    }
    
    float add(int x, int y) {
     float f = x + y;
     return f;
    }

    Download Code

    Output:

    sum1 is: 30
    sum2 is: 300
    sum3 is: 3000

    Explanation:
    Here ‘fn[3]‘ is an array of function pointers. Each element of the array can store the address of function ‘float add(int, int)’.

    fn[0]=fn[1]=fn[2]=&add
    Wherever this address is encountered add(int, int) function is called. External link to this question
    Back to top

  3. Write a program to compare two strings without using strcmp() function.
  4. strcmp() function compares two strings lexicographically. strcmp is declared in stdio.h
    Case 1: when the strings are equal, it returns zero.
    Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
    a) When string1 is greater than string2, it returns positive value.
    b) When string1 is lesser than string2, it returns negative value.

    Syntax:
    int strcmp (const char *s1, const char *s2);
    Read more about strcmp.

    Program: to compare two strings.

    #include<stdio.h>
    #include<string.h>
    int cmpstr(char s1[10], char s2[10]);
    
    int main() {
     char arr1[10] = "Nodalo";
     char arr2[10] = "nodalo";
     printf(" %d", cmpstr(arr1, arr2));
     //cmpstr() is equivalent of strcmp()
     return 0;
    }
    
    //s1, s2 are strings to be compared
    int cmpstr(char s1[10], char s2[10]) {
     //strlen function returns the length of argument string passed
     int i = strlen(s1);
     int k = strlen(s2);
     int bigger;
    
     if (i < k) {
      bigger = k;
     }
     else if (i > k) {
      bigger = i;
     }
     else {
      bigger = i;
     }
    
     //loops 'bigger' times
     for (i = 0; i < bigger; i++) {
      //if ascii values of characters s1[i], s2[i] are equal do nothing
      if (s1[i] == s2[i]) {
      }
      //else return the ascii difference
      else {
       return (s1[i] - s2[i]);
      }
     }
     //return 0 when both strings are same
     //This statement is executed only when both strings are equal
     return (0);
    }

    Download Code

    Output:

    -32

    Explanation:
    cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr().

    Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ascii difference of the differing characters and exit.
    Back to top

  5. Write a function to concatenate two strings without using strcat function.
  6. strcat(string1,string2) is a C standard function declared in the header file string.h
    The strcat() function concatenates string2, string1 and returns string1. Read more about strcat().

    Program: Program to concatenate two strings

    #include<stdio.h>
    #include<string.h>
    char *strct(char *c1, char *c2);
    
    char *strct(char *c1, char *c2) {
     //strlen function returns length of argument string
     int i = strlen(c1);
     int k = 0;
     //loops until null is encountered and appends string c2 to c1
     while (c2[k] != '\0') {
      c1[i + k] = c2[k];
      k++;
     }
     return c1;
    }
    
    int main() {
     char string1[15] = "first";
     char string2[15] = "second";
     char *finalstr;
     printf("Before concatenation:"
     " \n string1 = %s \n string2 = %s", string1, string2);
     //addresses of string1, string2 are passed to strct()
     finalstr = strct(string1, string2);
     printf("\nAfter concatenation:");
     //prints the contents of string whose address is in finalstr
     printf("\n finalstr = %s", finalstr);
     //prints the contents of string1
     printf("\n string1 = %s", string1);
     //prints the contents of string2
     printf("\n string2 = %s", string2);
     return 0;
    }

    Download Code

    Output:

    Before concatenation:
    string1 = first
    string2 = second
    After concatenation:
    finalstr = firstsecond
    string1 = firstsecond
    string2 = second

    Explanation:
    string2 is appended at the end of string1 and contents of string2 are unchanged.

    In strct() function, using a for loop, all the characters of string ‘c2′ are copied at the end of c1. return (c1) is equivalent to return &c1[0] and it returns the base address of ‘c1′. ‘finalstr’ stores that address returned by the function strct().
    Back to top

  7. Write a program to generate the fibonacci series
  8. Fibonacci series: Any number in the series is obtained by adding the previous two numbers of the series.

    Let f(n) be n’th term.
    f(0)=0;
    f(1)=1;
    f(n)=f(n-1)+f(n-2); (for n>=2)
    Series is as follows
    0
    1
    1 (1+0)
    2 (1+1)
    3 (1+2)
    5 (2+3)
    8 (3+5)
    13 (5+8)
    21 (8+13)
    34 (13+21)
    …and so on

    Program: to generate Fibonacci Series(10 terms)

    #include<stdio.h>
    int main() {
     //array fib stores numbers of fibonacci series
     int i, fib[25];
     //initialized first element to 0
     fib[0] = 0;
     //initialized second element to 1
     fib[1] = 1;
     //loop to generate ten elements
     for (i = 2; i < 10; i++) {
      //i'th element of series is equal to the sum of i-1'th element and i-2'th element.
      fib[i] = fib[i - 1] + fib[i - 2];
     }
     printf("The fibonacci series is as follows \n");
     //print all numbers in the series
     for (i = 0; i < 10; i++) {
      printf("%d \n", fib[i]);
     }
     return 0;
    }

    Download Code

    Output:

    The fibonacci series is as follows
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34

    Explanation:
    The first two elements are initialized to 0, 1 respectively. Other elements in the series are generated by looping and adding previous two numbers. These numbers are stored in an array and ten elements of the series are printed as output.
    Back to top

  9. Write a c program which ask the user for a number between 1 to 9 and shows the number, if the user inputs anything out of the specified range the program should show an error and then again ask for a valid input. Compute this program without using a switch case.
  10. Program: Program for accepting a number in a given range.

    #include<stdio.h>
    int getnumber();
    
    int main() {
     int input = 0;
     //call a function to input number from key board
     input = getnumber();
     //when input is not in the range of 1 to 9,print error message
     while (!((input <= 9) && (input >= 1))) {
      printf("[ERROR] The number you entered is out of range");
      //input another number
      input = getnumber();
     }
     //this function is repeated until a valid input is given by user.
     printf("\nThe number you entered is %d", input);
     return 0;
    }
    
    //this function returns the number given by user
    int getnumber() {
     int number;
     //asks user for a input in given range
     printf("\nEnter a number between 1 to 9 \n");
     scanf("%d", &number);
     return (number);
    }

    Download Code

    Output:

    Enter a number between 1 to 9

    45

    [ERROR] The number you entered is out of range

    Enter a number between 1 to 9

    4

    The number you entered is 4

    Explanation:
    getfunction() function accepts input from user. ‘while’ loop checks whether the number falls within range or not and accordingly either prints the number(If the number falls in desired range) or shows error message(number is out of range).
    Back to top


About the Author:  This post was written by Ratan Dhoka. He is an alumnus of Kakatiya Institute of Technology. He enjoys coding in C and Java. You can reach him at ratan_jain77@yahoo.com


  • Anonymous

    Very Good Stuff…useful for interviews…Thanks a lot !!

  • http://www.interviewmantra.net Sridhar

    Thanks for your encouraging comments!

    - Interview Mantra Team

  • Anonymous

    Please provide me the solution of:
    Write a program to generate the string regarding the given number eg.197 will generate one hundred ninety seven

  • Anonymous

    excellent….

  • http://www.orkut.co.in/Main#Profile.aspx?uid=17858176128094951472 Saurabh Manchanda

    @Anonymous

    Write a program to generate the string regarding the given number eg.197 will generate one hundred ninety seven

    Solution:

    http://pastebin.com/f72b7bd80

    ____

    Saurabh Manchanda
    (saurabh.manchanda@yahoo.co.in)
    ____

  • Anonymous

    nice answer!

  • Anonymous

    Thanks a lot Saurabh for the answer

  • Anonymous

    What is the program that compares two series of numbers and outputs the total quantity of equal numbers?

  • Dinakar

    nice site……………..

  • http://facebook badkutt

    write a program that will generate prime numbers between 1-100 and store the numbers in an array called prime numb.it should also display whether the number is even or odd

  • rashmi

    thanks so much!!

  • Gopal

    Thanks

  • http://www.lfastat.com PRAVINKUMAR.S

    really very usefull. lot of thanks to author of this site., thanks and regards s.pravin

  • Chethan

    hi shiva,, ur blob is very useful for me.. keep doing the good work
    can u please explain solution in detail for
    **
    Declare an array of three function pointers where each function receives two integers and returns float.
    **
    it is there above,,but not explained in detail.. please help..

  • S.Sunil kumar

    I want string programs using recursion method (without using any in-built function ).can you please send the programs to my email id .my email id is :
    s_ssk@yahoo.co.in

  • INDRAJA

    THANK YOU SIR,VERY GOOD INTERVIEW QUESTIONS AND IT IS HELPING A LOT TO THE PEOPLE WHO ARE PREPARING FOR INTERVIEWS

  • palayekula nagendra

    this was very good to C learners and these are very good interview questions.it is very helpful to who are preparing for interviews.

  • baby akila

    I need a program for checking whether the given number is prime or not using pointers in C LANGUAGE.

  • chandra

    can u give code for this?
    1 2 0 4 0
    3 4 5 0 7
    0 8 9 10 0
    13 0 15 16 17
    0 21 0 24 25

  • Ssss

    Does 
    Program to concatenate two strings is safe, I don’t think so. you should 
    allocate a fresh memory for new string, I hope you got it.

  • eshwar

    #include
    #include
    int count(int n,int m)
    {
    int c=0;
    if(m>=n)
    {
    while(n>0)
    {
    if(n%10==m%10)
    c++;
    n/=10;
    m/=1o;
    }
    else
    {
    while(m>0)
    {
    if(n%10==m%10)
    c++;
    n/=10;
    m/=1o;}
    }
    return (c);}

    main()
    {
    int p,q,total;
    printf(“enter two numers”);
    scanf(“%d”,&p);
    scanf(“%d”,&q);
    total=count(p,q);
    printf(“n equal no of digits are=%d”,total);
    getch();

    }

  • sri

    hi it ll be useful for us to prepare for interview if u put all these programs in a pdf or word format. can u do this help for us?

  • sandeep

    U could hv posted few more programs on strings like Reverse a given string without using lib functions …..

Previous post:

Next post: