A series XYZ is given below. First three elements (element no. 0 to element no. 2) of the series are 1, 2 and 3 respectively. After that, any ith element of the series (for i>2) is the sum of the previous three elements. For example, 6 = 1+2+3 and 68 = 11+20+37. Your task is to write a program that prints the first 10 elements of this series.
You may use arrays but you are not allowed to use linkedlist.
XYZ Series: 1, 2 , 3 ,6 ,11 ,20 ,37 ,68 ,125 ,230 ,423 ,778 ,1431 ,2632 ,4841
#include <iostream>
int main()
{
const int last_index = 10 - 3;
int buffer[3] = {1, 2, 3};
std::cout << "XYZ Series: " << buffer[0] << ", " << buffer[1] << ", " << buffer[2] << ", ";
for(int i=0; i < last_index; ++i)
{
const int sum = buffer[0] + buffer[1] + buffer[2];
std::cout << sum << (i == last_index - 1 ? "\n" : ", ");
buffer[0] = buffer[1];
buffer[1] = buffer[2];
buffer[2] = sum;
}
return 0;
}
Comments
Leave a comment