C++ code to check triangular number



Suppose we have a number n. We have to check whether the number is triangular number or not. As we know, if n dots (or balls) can be arranged in layers to form a equilateral triangle then n is a triangular number.

So, if the input is like n = 10, then the output will be True.

Steps

To solve this, we will follow these steps −

for initialize i := 1, when i <= n, update (increase i by 1), do:    if i * (i + 1) is same as 2 * n, then:       return true return false

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; bool solve(int n){    for (int i = 1; i <= n; i++){       if (i * (i + 1) == 2 * n){          return true;       }    }    return false; } int main(){    int n = 10;    cout << solve(n) << endl; }

Input

10

Output

1
Updated on: 2022-03-29T11:31:34+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements