C Exercises: Product of a variable number of integers
C Variadic function: Exercise-2 with Solution
Write a C program to find the product of a variable number of integers passed as arguments to a function using variadic functions.
Sample Solution:
C Code:
#include <stdio.h>
#include <stdarg.h>
int multiply(int count, ...) {
int result = 1;
va_list args;
va_start(args, count);
for (int i = 0; i < count; i++) {
int num = va_arg(args, int);
result *= num;
}
va_end(args);
return result;
}
int main() {
int p1 = multiply(4, 2, 3, 4, 5);
int p2 = multiply(3, 5, 10, 15);
printf("Product of 2, 3, 4, and 5: %d\n", p1);
printf("Product of 5, 10, and 15: %d\n", p2);
return 0;
}
Sample Output:
Product of 2, 3, 4, and 5: 120 Product of 5, 10, and 15: 750
Explanation:
In the above program, the multiply() function takes a variable number of arguments using the ... syntax. The function then initializes a 'va_list' variable args using the 'va_start()' macro and loops through each argument using the 'va_arg()' macro. The function multiplies each argument together to get the final product, which is then returned.
In the main() function, we call the multiply() function with a different number of arguments each time, and the function calculates the product of all the arguments passed to it.Flowchart:
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Sum of a variable number of integers.
Next: Maximum and minimum of a variable number of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming-exercises/variadic/c-variadic-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics