Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements