In this tutorial, we will learn how to print lucas series up to N terms in C++.
What do you mean by Lucas series?
Lucas series is also defined as the sum of its two immediately previous terms. But here the first two terms are 2 and 1 whereas in Fibonacci numbers the first two terms are 0 and 1 respectively. The Lucas numbers are in the following integer sequence: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 ………….
We have to take n numbers of terms ‘n’ as input and print the lucas series up to n terms.
So here the code in c++ of print Lucas series which you can learn better on this……..
#include <iostream>
using namespace std;
// Function to print Lucas series up to N terms
void printLucasSeries(int n) {
int a = 2, b = 1; // Initial Lucas numbers
int nextTerm;
cout << "Lucas Series up to " << n << " terms:" << endl;
// Print the first two terms
cout << a << " " << b << " ";
// Loop to generate and print the next terms
for (int i = 2; i < n; ++i) {
nextTerm = a + b;
cout << nextTerm << " ";
a = b;
b = nextTerm;
}
}
int main() {
int n;
cout << "Enter the number of terms for Lucas series: ";
cin >> n;
// Check if the input is valid
if (n <= 0) {
cout << "Number of terms should be greater than zero.";
return 1;
}
// Call the function to print Lucas series
printLucasSeries(n);
return 0;
}
so here we take the ‘printlucasseries’ that takes an input integer parameter ‘n’ . its return ‘void’ , ,eaning it doent return any value. and and initializes the variable a and b in the lucas series and declare the “next term” which store the next term of the lucas series ………………………………………………………………………………………………………………………………………………….
Output of the code is :
Enter the number of terms for Lucas series: 7 Lucas Series up to 7 terms: 2 1 3 4 7 11 18 === Code Execution Successful ===