C PROGRAMMING PROGRAM • FUNCTIONS, PREPROCESSOR & COMMAND LINE
Add Values Using a Variadic Function
Learn how to add values using a variadic function using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Sum = 66
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdarg.h>
int sum_values(int count, ...)
{
va_list arguments;
va_start(arguments, count);
int sum = 0;
for (int index = 0; index < count; index++) sum += va_arg(arguments, int);
va_end(arguments);
return sum;
}
int main(void)
{
printf("Sum = %d\n", sum_values(5, 4, 8, 15, 16, 23));
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Sum = 66
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Receive a count followed by that many integer arguments and visit each with va_arg.
- Display the computed result.
Receive a count followed by that many integer arguments and visit each with va_arg.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
