w3resource

C Exercises: Compute the sum of a variable number of integers passed as arguments using an inline function


11. Variadic Sum Inline Variants

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:

Flowchart: Compute the sum of a variable number of integers passed as arguments using an inline function.

For more Practice: Solve these Related Problems:

  • Write a C program to compute the average of a variable number of integers using an inline variadic function.
  • Write a C program to calculate both the sum and product of a variable number of integers using an inline function.
  • Write a C program to sum the squares of a variable number of integers using an inline variadic function.
  • Write a C program to compute the cumulative sum from a variable number of integers passed as arguments using an inline function.

Go to:


PREV : Reverse String Inline Variants.
NEXT : C Programming File Handling Exercises Home.

C Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.