Write a program to input a number and print whether it is a Triangular Number or not

A triangular number is a number which is found by adding natural numbers from 1.

For example:

1+2+3+4 = 10

Therefore 10 is a triangular number

1 2 3 4 5 6 7 8 9 |
<h2>Output 1</h2> Enter a number: 21 The number is a Triangular Number. <h2>Output 2</h2> Enter a number: 50 The number is not a Triangular Number. |

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.io.*; public class Triangular_num { public static void main()throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); int n, i, s=0; System.out.println("Enter a number:"); n = Integer.parseInt(r.readLine()); for(i=1;;i++) { s = s+i; if(s==n) { System.out.println("The number is a Triangular Number."); break; } if(s>n) { System.out.println("The number is not a Triangular Number."); break; } } } } |

## Leave a Reply

You must be logged in to post a comment.