JAVA Write a main method that prompts user for an integer. Your main then calls
ID: 3669691 • Letter: J
Question
JAVA
Write a main method that prompts user for an integer. Your main then calls the
three methods on the input number and prints the results. Make sure that the results are
printed from main not from the individual methods.
printSequence: Method taking a positive or negative integer as input, then printing either:
all integers starting from 0 to the input number if number is
positive, or all integers from 0 down to the input number if the number is negative.
tringularNum: Method taking a positive integer as input. It then
computes and returns the triangular number of the input integer. The triangular
number of an integer is defined as the sum of all numbers from 1 up to the given
integer.The triangular number 5 is 1 + 2 + 3 + 4 + 5 = 15.
factorial: Method taking a positive integer as input. It then
computes and returns the factorial of the input integer.
Explanation / Answer
import java.util.Scanner;
class Assignment
{
public static void main(String args[])
{
int n, c, fact = 1;
int trianglenumber=1;
int sequencenumber;
int seq[],tri,facto;
System.out.println("Enter an integer");
Scanner in = new Scanner(System.in);
n = in.nextInt();
seq[]=printSquence(n);
tri=triangularNum(n);
facto=factorialNum(n);
System.out.println("Sequence is"+seq[]);
System.out.println("Triangular Number is"+tri);
System.out.println("Factorial is"+facto);
}
public int printSequence(int n)
{
for ( c = 0 ; c <= n ; c++ )
{
sequencenumber=c;
return sequencenumber;
}
}
public int triangularNum(int n)
{
for ( c = 1 ; c < n ; c++ )
{
trianglenumber=tianglenumber+c;
}
return trianglenumber;
}
public int factorialNum(int n)
{
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
}
return fact;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.