Java program to check triangular number
Answers
Answer:
Explanation:
A class Numbers contains the following data members and methods to check for triangular numbers.
A triangular number is formed by the addition of a consecutive sequence of integers starting from 1.
Example:
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 + 15
Therefore, 3, 6, 10, 15 are triangular numbers.
Class name: Numbers
Data members/instance variables:
n: integer to be checked whether it is triangular or not.
Member function/methods:
void getNum(): to accept the integer n.
int check(int): to check if n is triangular.
void display(): to display a suitable message whether n is triangular or not.
Specify the class Numbers giving details of the methods getNum(), check(int) and display(). The main() function need not be written.
import java.io.*;
class Numbers{
private int n;
public void getNum()throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("N = ");
n = Math.abs(Integer.parseInt(br.readLine()));
}
public int check(int num){
int sum = 0;
int i = 1;
if(num < 3)
return 0;
while(sum < num){
sum += i;
i++;
}
if(sum == num)
return 1;
return 0;
}
public void display(){
if(check(n) == 1)
System.out.println(n + " is triangular.");
else
System.out.println(n + " is not triangular.");
}
}