Geometric number sequence

A geometric sequence is a series of numbers where each term after the first is found by multiplying the previous term by a constant called the common ratio. This type of sequence is fundamental in various mathematical and real-world applications, such as calculating compound interest, population growth, and more. In this article, we will demonstrate how to generate a geometric sequence using C++.

Code Example

#include <iostream>
#include <vector>

// Function to generate a geometric sequence
std::vector<double> generateGeometricSequence(double firstTerm, double commonRatio, int numberOfTerms) {
    std::vector<double> sequence;
    double term = firstTerm;
    
    for (int i = 0; i < numberOfTerms; ++i) {
        sequence.push_back(term);
        term *= commonRatio;
    }
    
    return sequence;
}

int main() {
    double firstTerm = 2.0;
    double commonRatio = 3.0;
    int numberOfTerms = 5;

    std::vector<double> sequence = generateGeometricSequence(firstTerm, commonRatio, numberOfTerms);
    
    std::cout << "Geometric sequence: ";
    for (double term : sequence) {
        std::cout << term << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

Code Explanation

Function to Generate Geometric Sequence

std::vector<double> generateGeometricSequence(double firstTerm, double commonRatio, int numberOfTerms) {
    std::vector<double> sequence;
    double term = firstTerm;
    
    for (int i = 0; i < numberOfTerms; ++i) {
        sequence.push_back(term);
        term *= commonRatio;
    }
    
    return sequence;
}

This function generates a geometric sequence given the first term, common ratio, and the number of terms. It initializes the sequence with the first term and iteratively multiplies the current term by the common ratio to generate the next term. Each term is then added to the vector sequence.

Main Function

int main() {
    double firstTerm = 2.0;
    double commonRatio = 3.0;
    int numberOfTerms = 5;

    std::vector<double> sequence = generateGeometricSequence(firstTerm, commonRatio, numberOfTerms);
    
    std::cout << "Geometric sequence: ";
    for (double term : sequence) {
        std::cout << term << " ";
    }
    std::cout << std::endl;
    
    return 0;
}

In the main function, we define the first term, common ratio, and the number of terms for the geometric sequence. We then call the generateGeometricSequence function with these parameters to generate the sequence. Finally, we print the sequence to the console.

Output

When the above code is executed, it produces the following output:

Geometric sequence: 2 6 18 54 162 

This output shows the first five terms of the geometric sequence starting with 2 and having a common ratio of 3. Each term is generated by multiplying the previous term by the common ratio.