176k views
3 votes
Implement the function:

string get_ap_terms(int a, int d, size_t n);

which returns a string containing the first n terms of the arithmetic progression (AP) as a sequence of comma-separated values.

1 Answer

3 votes

Answer:

This is written in C++

Check comments for explanations

Program starts here

#include<iostream>

#include<string>

using namespace std;

//The function get_ap_terms begins here

string get_ap_terms(int a, int d, int size_tn)

{

// This line initializes the expected string to empty string

string result = "";

//The for iteration loops through the number of terms the function is expected to return

for(int i = 1; i<= size_tn;i++)

{

//This line checks if the loop is less than the number of terms

if(i < size_tn)

{

//This string gets the current term of the progression

result+=to_string(a)+ ", ";

//This line calculates the next term

a+=d;

}

else

{

//This line calculates the last term

result+=to_string(a);

}

}

//This line returns the string containing the first n terms of the arithmetic progression

return result;

}

//The main function starts here

int main()

{

//This line declares the first term (a), the common difference (d) and the number of terms (size_tn)

int a,d,size_tn;

//This line prompts the user for the first term

cout<<"First Term: ";

//This line gets the first term

cin>>a;

//This line prompts the user for the common difference

cout<<"Common Difference: ";

//This line gets the common difference

cin>>d;

//This line prompts the user for number of terms

cout<<"Number of Terms: ";

//This line gets the number of terms

cin>>size_tn;

//This line calls the function to print the string containing the first n terms

cout<<get_ap_terms(a, d, size_tn);

return 0;

}

//Program ends here

User Kiflay
by
4.6k points