Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Functions with variable number of arguments In mathematics, a geometric progress

ID: 3642010 • Letter: F

Question

Functions with variable number of arguments
In mathematics, a geometric progression, also known as a geometric sequence, is a sequence of numbers where each term after the first is found by multiplying the previous one by a fixed non-zero number called the common ratio. For example, the sequence 2, 6, 18, 54, ... is a geometric progression with common ratio 3. Similarly 10, 5, 2.5, 1.25, ... is a geometric sequence with common ratio 1/2.
Write a function isGeometric with variable number of arguments that takes an integer first argument followed by any number of arguments of type double and returns true if the arguments of type double form a geometric sequence, and false if they don’t. The first argument (an integer) is the number of double arguments to consider. Provide a main program to test the function.

Explanation / Answer

#include <iostream>

#include <stdarg.h>

using namespace std;

bool isGeometric(int count, ...);

int main() {

       if(isGeometric(5, 6.0, 3.0, 13.0, 6.0, 7.0)) {

              cout << "It is geometric" << endl;

       }

       if(isGeometric(4, 2.0, 6.0, 18.0, 54.0)) {

              cout << "It is geometric" << endl;

       }

       if(isGeometric(4, 10.0, 5.0, 2.5, 1.25)) {

              cout << "It is geometric" << endl;

       }

}

bool isGeometric(int count, ...) {

       va_list doubles;

       va_start(doubles, count);

       bool ret = true;

       double ratio;

       double *list = new double[count];

       for(int i = 0; i < count; ++i) {

              list[i] = va_arg(doubles, double);

              if(i == 1) {

                     ratio = list[1] / list[0];

              }

              if(i > 1) {

                     if(list[i] / list[i-1] != ratio) {

                           ret = false;

                     }

              }

       }

       va_end(doubles);

       return ret;

}