I need help writing a c program I am to find the sum of fthe
I need help writing a c++ program.
I am to find the sum of fthe first 20 terms in the sequence the array. I am almost possitive a for loop is to be utilized and a sum can be done with that function but I am having problems writing the program. Please help me. Also, please include all code and explain if possible.
Im using C++ Visual Studio Cummunity 2015
Solution
#include<iostream>
using namespace std;
int main()
{
//Array to hold 20 terms
int arr[20];
//Initialize first 2 terms of the sequence and assign it to array
arr[0] = -1;
arr[1] = 3;
//Variables for generating next 18 terms
int next_term,last,second_last;
last = arr[1];
second_last = arr[0];
int i = 2;
//Generate next 20 terms
while(i<20)
{
next_term = 3*last-4*second_last;
second_last = last;
last = next_term;
arr[i] = next_term;
i++;
}
//Compute the sum and print the 20 terms
int sum = 0;
cout << \"First 20 terms of the series is : \";
for(i=0;i<20;i++)
{
cout << arr[i] << \" \";
sum = sum+arr[i];
}
cout << endl;
//Display the sum
cout << \"Sum of first 20 terms of the series is : \" << sum << endl;
return 0;
}
OUTPUT:
First 20 terms of the series is : -1 3 13 27 29 -21 -179 -453 -643 -117 2221 7131 12509 9003 -23027 -105093 -223171 -249141 145261 1432347
Sum of first 20 terms of the series is : 1006698
