Variadic Functions in C | HackerRank Solution

Hello coders, today we are going to solve Variadic Functions HackerRank Solution in C.

Variadic Functions

Contents

Problem

Variadic functions are functions which take a variable number of arguments. In C programming, a variadic function will contribute to the flexibility of the program that you are developing.

The declaration of a variadic function starts with the declaration of at least one named variable, and uses an ellipsis as the last parameter, e.g.

int printf(const char* format, ...);

In this problem, you will implement three variadic functions named sum()min() and max() to calculate sums, minima, maxima of a variable number of arguments. The first argument passed to the variadic function is the count of the number of arguments, which is followed by the arguments themselves.

Input Format

  • The first line of the input consists of an integer number_of_test_cases.
  • Each test case tests the logic of your code by sending a test implementation of 3, 5 and 10 elements respectively.
  • You can test your code against sample/custom input.
  • The error log prints the parameters which are passed to the test implementation. It also prints the sum, minimum element and maximum element corresponding to your code.

Constraints

  • 1 <= Number_of_test_cases <= 50
  • 1 <= element <= 1000000

Output Format

“Correct Answer” is printed corresponding to each correct execution of a test implementation.”Wrong Answer” is printed otherwise.

Sample Input 0

1

Sample Output 0

Correct Answer
Correct Answer
Correct Answer

Solution – Variadic Functions in C

int  sum (int count,...) {
    int sum=0;
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        sum+=va_arg(values,int);
    }
    va_end(values);
    return sum;

}

int min(int count,...) {
    int min=MAX_ELEMENT,test;  
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        test=va_arg(values,int);
        if(min>test){
            min=test;
        }  
    }
    va_end(values);
    return min;

}

int max(int count,...) {
    int max=MIN_ELEMENT,test;
    va_list values;
    va_start(values,count);
    for(int i=0;i<count;i++){
        test=va_arg(values,int);
        if(max<test){
            max=test;
        }  
    }
    va_end(values);
    return max;
}

Disclaimer: The above Problem (Variadic Functions) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published.