C Exercises: Compute the sum of a variable number of integers passed as arguments using an inline function
Write a C program to compute the sum of a variable number of integers passed as arguments using an inline function.
Sample Solution:
C Code:
#include <stdio.h>
#include <stdarg.h>
inline int inline_sum(int count, ...) {
int sum = 0;
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
sum += va_arg(args, int);
}
va_end(args);
return sum;
}
int main() {
int total = inline_sum(5, 1, 2, 3, 4, 5);
printf("Sum is %d\n", total);
int total2 = inline_sum(3, 6, 10, -16);
printf("Sum is %d\n", total2);
return 0;
}
Sample Output:
Sum is 15 Sum is 0
Explanation:
In the above exercise, the sum function takes a variable number of arguments using the stdarg.h library. It first initializes a va_list object with va_start, then iterates through the arguments in a loop. It adds each one to a running sum. Finally, it cleans up with va_end and returns the sum.
In main(), we call sum twice with different sets of integers and print out the results.
Flowchart:
C Programming Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics