4

In an interview I was asked to write an efficient program such that for each integer value given, a function is called.

For example: if user enters 1 then function one will get executed if user enters 5 then function five gets executed and so on..

I was not able to come up with an efficient idea, like we can't use an if statement for checking the value entered and then executing the corresponding functions.

Is there any way we can do this in an efficient manner?

3
  • 6
    Using a switch-case? Or perhaps an array of function pointers? Also "efficient" in regards to what? Commented Aug 22, 2018 at 13:00
  • Are the numbers small? Could they be used as indexes into an array (of pointers to functions)? Or perhaps use hash-tables or trees or other similar solutions? Commented Aug 22, 2018 at 13:00
  • 1
    function pointers in an array. Commented Aug 22, 2018 at 13:01

2 Answers 2

4

One of the option would be using function pointers, as below.

Declares a type of a void function

typedef void (*fp)();

define your functions

void func1()
{}
.
.
.
void func10()
{}

declare array of function pointers like below

fp function_pointers[10];  //declares the array

Initialize the function pointers like below

 function_pointers[0] = func1()
  .
  .
  function_pointers[9] = func10()

Call function using function pointers like below

 for (int i=0;i<10;i++)
 function_pointers[i]();
Sign up to request clarification or add additional context in comments.

1 Comment

what if one has to do it in cpp ? the same method is followed or is there some other way of doing the same?
3

Use function pointers.

Simple example:

#include <stdio.h>

//pointer to a void function declaration

typedef void(*someFunc)();

void f1() {
    printf("f1 function call\n");
}

void f2() {
    printf("f2 function call\n");
}

void f3() {
    printf("f3 function call\n");
}

//array of function pointers
const someFunc funcTable[] = {
    f1,
    f2,
    f3
};

int main() {
    uint number = 0;
    printf("Enter 0, 1 or 2\n");

    scanf("%u",&number);
    if(number < 3) {
        funcTable[number]();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.