99.3k views
5 votes
Write an application that calculates the product of a series of integers that are passed to method product using a variable-length argument list. Test your method with several calls, each with a different number of arguments.

User Mangooxx
by
5.7k points

1 Answer

2 votes

Answer:

The method written in C++ is as follows:

#include <iostream>

#include <stdarg.h>

using namespace std;

int prod(int listsnum,...) {

va_list mylist;

int product = 1;

va_start(mylist, listsnum);

for (int i = 0; i < listsnum; i++)

product *= va_arg(mylist, int);

va_end(mylist);

return product;

}

Step-by-step explanation:

This line defines the method along with the series of integers

int prod(int listsnum,...) {

This declares the variable-length list using va_list as the declaration

va_list mylist;

This initializes product to 1

int product = 1;

This initializes the variable-length list

va_start(mylist, listsnum);

The following iteration calculates the product of the list

for (int i = 0; i < listsnum; i++)

product *= va_arg(mylist, int);

This ends the the variable-length list

va_end(mylist);

This returns the product of the list

return product;

}

To call the method from the main, make use of:

cout<<"Product: "<<prod(4, 2,3,4,5);

The first 4 in the list indicates the number of items in the list while the 4 other items represents the list elements

You can also make use of:

cout<<"Product: "<<prod(2, 6,5);

User Ozzy
by
6.0k points