lcat

My personal /var/log

[C++] Recursive array average

#include <iostream>

float calculate_average(float *x, int offset, size_t length);

int main()
{
    size_t length;
    float *x;
    float average;
    
    std::cout << "Input array length: ";
    std::cin >> length;
    x = new float[length];
    
    std::cout << "Input space-separated elements: ";
    for (int i = 0; i < length; i++)
        std::cin >> x[i];
    
    average = calculate_average(x, 0, length);
    std::cout << "Average: " << average; 
    
    delete[] x;
    return 0;
}

float calculate_average(float *x, int offset, size_t length) {
    if (offset == length-1)
        return x[0]/length;
    return x[0]/length + calculate_average(&x[1], offset+1, length);
}
Created: 2021-10-28T08:24:25, Last updated: 2021-10-28T08:24:25, ID: c731bb2a-aa2d-4626-8a75-19120bcabb96