Lucas Sequence problem in JAVA:
a = 0, b=0, c=1 are the 1st three terms. All other terms in the Lucas sequence are generated by the sum of their 3 most recent predecessors.
Question: Write a program to generate the first n terms of a Lucas Sequence.
Input Format:
Input consists of a single integer which corresponds to n.
Output Format:
Output consists of the n terms of the Lucas Sequence, separated by a single space. There are no leading or trailing spaces in the output.
Sample Input
5
Sample Output
0 0 1 1 2
Write a program to print Lucas Sequence number in java:
import java.io.*;
import java.util.*;
class Main{
public static void main(String[]args)
{
int i,n,a=0,b=0,c=1,d=0;
i=3;
Scanner s=new Scanner(System.in);
n=s.nextInt();
if(n==1)
{
System.out.println("0");
}
else if(n==2)
{
System.out.println("0 0");
}
else if(n==3)
{
System.out.println("0 0 1");
}
else
{
System.out.println("0 0 1 ");
while(i!=n)
{
d=a+b+c;
System.out.println(d+" ");
a=b;
b=c;
c=d;
i++;
}
}
}
}
What is Loop in Java:
A program may require that a group of statements be executed repeatedly, until some logical condition has been satisfied.
Sometimes the required number of repetitions is known in advance; and sometimes the computation continues indefinitely until the logical condition becomes true.
All of these operations are carried out using the various control constructs in java. In this session, let us try to explore how this is accomplished.
Thank you very much 🙏
ReplyDelete