Advertisement
dmilicev

function_with_variable_list_of_arguments.c

Feb 7th, 2020
279
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None
  1. /*
  2.  
  3.     function_with_variable_list_of_arguments.c
  4.  
  5.  
  6.     https://www.tutorialspoint.com/cprogramming/c_variable_arguments.htm
  7.  
  8.  
  9.     You can find all my C programs at Dragan Milicev's pastebin:
  10.  
  11.     https://pastebin.com/u/dmilicev
  12.  
  13. */
  14.  
  15. #include <stdio.h>
  16. #include <stdarg.h> // for variable list of arguments, va_start() and va_end()
  17.  
  18. double average(char text[],int num,...) {
  19.  
  20.     va_list valist;
  21.     double sum = 0.0;
  22.     int i;
  23.  
  24.     va_start(valist, num);      // initialize valist for num number of arguments
  25.  
  26.     for (i = 0; i < num; i++)   // access all the arguments assigned to valist
  27.       sum += va_arg(valist, int);
  28.  
  29.     va_end(valist);             // clean memory reserved for valist
  30.  
  31.     printf("\n %s \n", text);
  32.  
  33.     return sum/num;
  34. }
  35.  
  36. int meny( char meny_title[],
  37.           int number_of_meny_items, ... )
  38. {
  39.     int i;
  40.     va_list valist;
  41.  
  42.     printf("\n%s\n", meny_title);
  43.  
  44.     va_start(valist, number_of_meny_items);     // initialize valist for num number of arguments
  45.  
  46.     for (i = 0; i < number_of_meny_items; i++)  // access all the arguments assigned to valist
  47.         printf("%s\n", va_arg(valist, char*) );
  48.  
  49.     va_end(valist);                             // clean memory reserved for valist
  50.  
  51.     return 0;
  52. }
  53.  
  54.  
  55. int main(void)
  56. {
  57.     printf("Average of 2, 3, 4, 5 = %f \n", average("This is text",4, 2,3,4,5) );
  58.     printf("Average of 5, 10, 15 = %f \n",  average("This is text",3, 5,10,15) );
  59.  
  60.     meny(   "MENY TITLE",
  61.             5,
  62.             "1. first item",
  63.             "2. second item",
  64.             "3. third item",
  65.             "4. fourth item",
  66.             "5. fifth item" );
  67.  
  68.  
  69.     return 0;
  70.  
  71. } // main()
Advertisement
RAW Paste Data Copied
Advertisement