Home »
C solved programs »
Advance C programs
C program to demonstrate example of Variable Arguments
This program will demonstrate example of Variable Arguments, in this program we will create a user define function for calculating sum of N arguments, using Variable Arguments we can pass multiple arguments in the function.
Example of Variable Arguments using C program
/*C program to demonstrate example of Variable Arguments.*/
#include <stdio.h>
#include <stdarg.h>
/*find sum of numbers*/
int sum(int N, ...)
{
int loop,sum;
va_list va; /*for argument list*/
va_start(va,N); /*init with number of arguments*/
/*access arguments & calculating sum*/
sum=0;
for(loop=0;loop<N;loop++){
sum+=va_arg(va,int);
}
return sum;
}
int main()
{
printf("Sum of 10, 20 = %d\n",sum(2,10,20));
printf("Sum of 10, 20, 30, 40 = %d\n",sum(4,10,20,30,30));
printf("Sum of 10, 20, 30, 40, 50, 60 = %d\n",sum(6,10,20,30,30,40,50));
return 0;
}
Sum of 10, 20 = 30
Sum of 10, 20, 30, 40 = 90
Sum of 10, 20, 30, 40, 50, 60 = 180
You may also be interested in...
C/C++ Tips and Tricks...