Computer Science, asked by Anujpatel3973, 9 months ago

Write a program to illustrate ""variablelength arguments"".

Answers

Answered by Abhis506
0

Following is a + example to demonstrate the use of default arguments. We dwrite

Answered by ridhimakh1219
0

Write a program to illustrate ""variablelength arguments"".

Explanation:

C program to illustrate variable number of parameters and calculate its average.

#include <stdio.h>

#include <stdarg.h>

double average(int num,...) {

  va_list valist;

  double sum = 0.0;

  int i;

  va_start(valist, num); //initialize valist for num number of arguments

  for (i = 0; i < num; i++) {

     //access all the arguments assigned to valist

     sum += va_arg(valist, int);

  }

  va_end(valist); //clean memory reserved for valist

  return sum/num;

}

int main() {

  printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));

  printf("Average of 5, 10, 15 = %f", average(3, 5,10,15));

}

Output

Average of 2, 3, 4, 5 = 3.500000

Average of 5, 10, 15 = 10.000000

Note

In above Function, double average(int num,...) is defined that accepts variable number of parameters depending upon the problem statement.

In the above C program, function call average() is made two times and number of parameters passed to the function varied. 3 dots (…) indicates that function average() function can accept any number of parameters during run time.

The header file <stdarg.h> is included in C program to use variable length argument functions.

It is denoted by three dotes (…)

Similar questions