Answer to Question #266128 in C++ for zxc

Question #266128

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


1
Expert's answer
2021-11-15T12:36:34-0500
#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;    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS