Variadic Sum Function
C
Hard
4 views
Problem Description
Create a function like printf that returns the sum of a variable number of integers. The first parameter will be the count, the rest will be numbers. Do that.
Official Solution
#include <stdio.h>
#include <stdarg.h>
/* Function to sum variable number of integers */
int sum(int count, ...) {
va_list args; // To store the variable arguments
int total = 0;
va_start(args, count); // Initialize args starting after 'count'
for (int i = 0; i < count; i++) {
int num = va_arg(args, int); // Get next int argument
total += num;
}
va_end(args); // Clean up
return total;
}
int main() {
int result;
/* Example usage */
result = sum(5, 10, 20, 30, 40, 50); // sum of 5 numbers
printf("Sum = %dn", result);
result = sum(3, 7, 14, 21); // sum of 3 numbers
printf("Sum = %dn", result);
result = sum(0); // sum of 0 numbers
printf("Sum = %dn", result);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!