ADVERTISEMENT
ADVERTISEMENT

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;
}

Output:

Sum of 10, 20 = 30
Sum of 10, 20, 30, 40 = 90
Sum of 10, 20, 30, 40, 50, 60 = 180

C Advance Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.