Skip to main content

Check triangular number

Short answer

Add natural numbers 1,2,3,... to sum until sum >= n. If sum equals n and n>0, it's triangular; else not.

Write a program to check whether a given integer is a triangular number or not. (Any number is a triangular number if the sum of natural number from 1 to any number i is exactly equal to that number. For e.g 1,3,6,10,15 etc are triangular number as, 1+2=3, 1+2+3=6, 1+2+3+4=10, 1+2+3+4+5=15)

A triangular number is the sum 1 + 2 + ... + i for some i. The program keeps adding 1, 2, 3, ... to sum until sum reaches or passes the given number. If it stops at exactly n, the number is triangular.

#include <stdio.h>
int main(void)
{
    int n, i = 1, sum = 0;
    printf("Enter an integer: ");
    scanf("%d", &n);
    while (sum < n)
    {
        sum += i;
        i++;
    }
    if (sum == n && n > 0)
        printf("%d is a triangular number\n", n);
    else
        printf("%d is not a triangular number\n", n);
    return 0;
}

Output for 15:

Enter an integer: 15 is a triangular number

Check: 1+2+3+4+5 = 15. For 14 the sums go 1, 3, 6, 10, 15 (more than 14), so 14 is not a triangular number.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 5 questions →