Print all triangular numbers in range of 3 to n.
import java.util.*;;
public class Triangle {
int n;
boolean check(int n) {
int sm = 0;
for (int x = 0; x < n; x++) {
sm += x;
if (sm > n)
return false;
else if (sm == n)
return true;
}
return false;
}
void input() {
Scanner sc = new Scanner(System.in);
System.out.print("Value of n: ");
n = sc.nextInt();
sc.close();
}
void print() {
System.out.print("Triangular Numbers:- ");
for (int x = 3; x <= n; x++)
if (check(x))
System.out.print(x + ", ");
}
public static void main(String[] args) {
Triangle a = new Triangle();
a.input();
a.print();
}
}
Name | Type | Uses |
---|---|---|
global | ||
n | int | to store entered number for evaluation |
void main() | ||
a | Triangle | Object to call the functions of the class |
void input() | ||
sc | Scanner | to take user input |
boolean check() | ||
sm | int | to store sum of consecutive numbers |
x | int | a counter variable for the for loop |
void input() | ||
x | int | a counter variable for the for loop |