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

Write a program that uses a function called recursive_compute_sum to calculate t

ID: 665483 • Letter: W

Question

Write a program that uses a function called recursive_compute_sum to calculate the sum of the first n integers. The function will take one argument, an integer, and then return the sum of the first n integers. For example, if the user calls recursive_compute_sum(5), then your function would return 15 which is 1 + 2 + 3 + 4 + 5. Your function should compute this sum using a recursive method as we did in class and in lab.

Next, write another function, iterative_compute_sum, that also takes one integer argument and returns the sum of the first n integers. This function, however, does not use a recursive method but will instead compute the sum using a while loop and then returning the answer.

The program you turn in should have the following main program but should work for any values, not just 10:

int main(int argc, char* argv[])

{ printf("%d ", recursive_compute_sum(10)); printf("%d ", iterative_compute_sum(10));

return 0;

}

Explanation / Answer

#include <stdio.h>
int iterative_compute_sum(int n)
{
    int sumi=0,current=1;
    while(current<=n)
    {
        sumi+=current;
        current++;
    }
    return sumi;
}
int recursive_compute_sum(int n)
{
    if(n==1)
        return 1;
    int sumi=recursive_compute_sum(n-1)+n;
    return sumi;
}
int main(int argc, char* argv[])
{
    printf("%d ", recursive_compute_sum(10));
    printf("%d ", iterative_compute_sum(10));
    return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote