New Question!!
Q) WAP in JAVA to print the following series:
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15......Nth term
_______
Note:-
•You must attach your dry-run,code and the output with your written code compiled successfully in the Java compiler
•ABSOLUTELY NO SPAMMING
•Also please attach your Variable Description Table
_
Thank you
:)
Answers
Answer:
I have attached 4 attachments see.
The 1st program prints the output in the same line.
The 2nd program prints the output(different tables ) in different line.
The 3rd photo is the output of 1st program
The 4th photo is the output of 2nd program.
Note: I added the value of n different so that you are sure that the output prints correctly.
Hope it helps.....
Also note the class name you write on your own.I wrote pattern you can write series.
Required Answer:-
Question:
Write a program in Java to display the series,
1 2 3 4 5 2 4 6 8 10....N terms.
Solution:
This is a nice question. Here is the code.....
import java.util.*;
public class Series {
public static void main(String[] args) {
int n, a=1, b=1, c=1;
Scanner sc=new Scanner(System.in);
System.out.print("Enter n - ");
n=sc.nextInt();
for(int i=1;i<=n;i++)
{
System.out.print(a+" ");
a+=b;
c++;
if(c>5)
{
c=1;
a=b+1;
b=a;
}
}
sc.close();
}
}
Sample I/O:
Enter n - 12
Output: 1 2 3 4 5 2 4 6 8 10 3 6
Dry Run:
Assume n = 8
When i = 1:
a = 1
b = 1
c = 2
(c > 5) = false
Output: 1
Now, a = 2
When i = 2:
a = 2
b = 1
c = 3
(c > 5) = false
Output: 2
Now, a = 3
When i = 3:
a = 3
b = 1
c = 4
(c > 5) = false
Output: 3
Now, a=4
When i = 4:
a = 4
b = 1
c = 5
(c > 5) = false
Output: 4
Now, a = 5
When i = 5:
a = 5
b = 1
c = 6
(c > 5) is true.
So,
a = b + 1 = 2
b = a = 2
c = 1 (again)
i.e, a = 2 and b = 2,c = 1
Output: 5
When i = 6:
a = 2
b = 2
c = 2
(c > 5) = false
Output: 2
Now, a = 4
When i = 7:
a = 4
b = 2
c = 3
(c > 5) = false
Output: 4
Now, a = 6
When i = 8:
a = 6
b = 2
c = 4
(c > 5) = false
Output: 6
Now, a = 8
When i = 9:
i <= n is false. Loop is terminated here.
Variable Description:
- n (int):- To take number of terms as input.
- a(int):- Nth term of this series is stored here.
- b(int):- Used to increment the value of a so as to get the next term of the series.
- c(int):- Counter variable.
Output is attached.