Q:

C Program to find given number is sum of first n natural numbers

belongs to collection: C Programming on Numbers

0

In this exercise, we learn how to write a C Program to find a given number is the sum of first n natural numbers?. We will write the C Program to find the given number is the sum of first n natural numbers or not using the loop and binary search. Let see an example,

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
int findSum(int data)
{
    int sum = 0, i, isEqual = 0;
    // Start adding numbers from 1
    for (i = 1; sum < data; i++)
    {
        sum += i;
        // If sum becomes equal to data
        // return i
        if (sum == data)
        {
            isEqual = i;
        }
    }
    return isEqual;
}
int main()
{
    int data = 15, isSumOfNaturalNumber = 0;
    printf("Enter number = ");
    scanf("%d", &data);
    isSumOfNaturalNumber = findSum(data);
    if(isSumOfNaturalNumber)
    {
        printf ("Sum of Natural number 1 to %d\n",isSumOfNaturalNumber);
    }
    else
    {
        printf("It is not a sum of 1 to n Natural number\n");
    }
    return 0;
}

 

Output:
Enter number = 10
Sum of Natural number 1 to 4

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C Program to swap two numbers using arithmetic ope... >>
<< C Program to swap two numbers using a third variab...