Write a Java program to print the above pattern till “n” numbers.
Answers
Here we need to find the sum and factorial of a number by using Scanner class.
Program Códe :
import java.util.*;
class series
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter term no")
int n = sc.nextInt();
double sum = 0.0;
for (int i = 2; i<=n; i++)
{
int s = 0, f = 1;
for(int j = 1; j<=i; j++)
{
s = s + j;
f = f * j;
}
sum = sum + (double) s/f;
}
System.out.println("Sum of the series="+sum)
}
}
Output :
Enter term no
3
Sum of the series=2.5
Working :
Let's take the term no as 3.
The i loop is starting from 2 therefore, the i loop will run only 2 times.
1st Iteration :
i = 2 and n = 3
Inside the j loop,
j = 1 and i = 2
- s = s + j = 0 + 1 = 1
- s = s + j = 1 + 2 = 3
- f = f * j = 1 * 1 = 1
- f = f * j = 1 * 2 = 2
- sum = sum + s/f = 0.0 + 3/2 = 1.5
2nd Iteration :
i = 3 and n = 3
Inside the j loop,
j = 1 and i = 3
- s = s + j = 0 + 1 = 1
- s = s + j = 1 + 2 = 3
- s = s + j = 1 + 2 + 3 = 6
- f = f * j = 1 * 1 = 1
- f = f * j = 1 * 2 = 2
- f = f * j = 1 * 2 * 3 = 6
- sum = sum + s/f = 0.0 + 6/6 = 1.0
Final sum = 1.5 + 2.0 = 2.5
For better understanding refer to the attachment.