fork download
  1. #include<stdio.h>
  2. #include <stdarg.h>
  3.  
  4. // The sum() function can accept variable number of arguements.
  5. int sum(int num_of_arguments, ... )
  6. {
  7. /* A list to store the aruements. In example, this may contain
  8.   1,2,3 and 4 elements on successive calls from main()
  9.   */
  10. va_list args;
  11. int sum= 0, i;
  12.  
  13. /* Directing the va_list args initialized above to start storing
  14.   all parameters folloowing the first parameter 'num_of_arguments'.
  15.   */
  16. va_start (args, num_of_arguments );
  17.  
  18. /* Loop until all parameters are seen. */
  19. for (i= 0; i< num_of_arguments; i++ )
  20. /* Extract the next value in argument list and add it to sum. */
  21. sum += va_arg (args,int);
  22.  
  23. /* Signal that we are done with our usage of the list */
  24. va_end (args);
  25.  
  26. return sum; /* Returns the calculated sum.*/
  27. }
  28. int main()
  29. {
  30. int result;
  31.  
  32. result=sum (1,1);
  33. printf("result of calling sum() with 2 arguement: %d \n", result);
  34.  
  35. result=sum (2,1,2);
  36. printf("result of calling sum() with 3 arguement: %d \n", result);
  37.  
  38. result=sum (3,1,2,3);
  39. printf("result of calling sum() with 4 arguement: %d \n", result);
  40.  
  41. result=sum (4,1,2,3,4);
  42. printf("result of calling sum() with 5 arguement: %d \n", result);
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
result of calling sum() with 2 arguement: 1 
result of calling sum() with 3 arguement: 3 
result of calling sum() with 4 arguement: 6 
result of calling sum() with 5 arguement: 10