write a program to generate a triangle or an inverted triangle till 'n' terms based
upon users choice of triangle to be displayed.
Ans:
import [Link];
public class KboatPattern
{
public void choosePattern()
{
Scanner in = new Scanner([Link]);
[Link]("Type 1 for a triangle");
[Link]("Type 2 for an inverted triangle");
[Link]("Enter your choice: ");
int ch = [Link]();
[Link]("Enter the number of terms: ");
int n = [Link]();
switch (ch) {
case 1:
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
[Link](i + " ");
}
[Link]();
}
break;
case 2:
for (int i = n; i > 0; i--)
{
for (int j = 1; j <= i; j++)
{
[Link](i + " ");
}
[Link]();
}
break;
default:
[Link]("Incorrect Choice");
}
}
}
THE OUTPUT IS:
The output of this program will depend on the user’s input. For example, if the
user enters 3 for the number of terms and chooses 1 for a triangle, the output will
be:
1
2 2
3 3 3
If the user chooses 2 for an inverted triangle, the output will be:
3 3 3
2 2
1
If the user enters anything other than 1 or 2 for the choice, the program will
print Incorrect Choice.
THE VDT TABLE IS:
Variable Type Initial Value Purpose
in Scanner new Scanner([Link]) To read input from the user
ch int User input The choice of pattern
n int User input The number of terms in the pattern
i int 1 or n Loop counter for the outer loop
j int 1 Loop counter for the inner loop
Q]Write Java program to find the sum of the given series:
1 + (1/2!) + (1/3!) + (1/4!) + ………. + (1/n!)
Ans:
import [Link];
public class KboatSeriesSum
{
public static void main(String args[])
{
Scanner in = new Scanner([Link]);
[Link]("Enter n: ");
int n = [Link]();
double sum = 0.0;
for (int i = 1; i <= n; i++)
{
long f = 1;
for (int j = 1; j <= i; j++)
{
f *= j;
}
sum += (1.0 / f);
}
[Link]("Sum=" + sum);
}
}
THE OUTPUT IS:
The output of the program depends on the user input for n. The program calculates
the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/n!. For example, if the user
enters n = 4, the output will be:
Enter n: 4
Sum=1.6666666666666667
THE VDT TABLE IS:
Variable Type Initial Value Purpose
in Scanner new Scanner([Link]) To read input from the user
n int User input The number of terms in the series
sum double 0.0 To store the sum of the series
i int 1 Loop counter for the outer loop
f long 1 To store the factorial of i
j int 1 Loop counter for the inner loop