#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
int total = 0;
va_start(args, count);
for (int i = 0; i < count; i++) {
int num = va_arg(args, int);
total += num;
}
va_end(args);
return total;
}
int main() {
int result1 = sum(3, 2, 4, 6);
int result2 = sum(5, 1, 3, 5, 7, 9);
printf("Result 1: %d\n", result1);
printf("Result 2: %d\n", result2);
return 0;
}
Here's a breakdown of the code:
We include the
The sum() function takes the count argument, followed by the ellipsis (...) to indicate a variable number of arguments.
Inside the sum() function, we declare a va_list variable named args to hold the list of arguments.
We use the va_start() macro to initialize the args list with the last known named argument (in this case, count).
We use a for loop to iterate count times. Inside the loop, we use the va_arg() macro to retrieve each integer argument from the args list.
We add the retrieved integer to the total variable.
After the loop, we call the va_end() macro to clean up the args list.
The main() function demonstrates the usage of the sum() function by calling it with different numbers of integers.
We print the results using the printf() function.
By providing the expected input and executing the code, you should see the sum of the integers printed, as specified in the problem statement on HackerRank.