Q:

C Program to find the sum of natural numbers upto n

0

In this exercise, we learn how to write a C Program to find the sum of natural numbers upto n.  We will take the help of iterative statements like for, while or do-while loop to find the SUM of the natural numbers.

All Answers

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

C Program to find the sum of natural numbers upto n using For Loop

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will calculate the sum of natural numbers up to n terms with the help of for loop.

#include<stdio.h>
int main()
{
    int num, i;
    unsigned long int sum = 0;
    printf("Please Enter any Integer number = ");
    scanf("%d", &num);
    if(num >0)
    {
        for(i = 1; i <= num; i++)
        {
            sum += i;
        }
        printf("Sum = %ld\n",sum);
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Output:

Please Enter any Integer number = 5
Sum = 15

---------------------------------------------------------------------------------------------------

C Program to find the sum of natural numbers upto n using while Loop

In the below program, we will ask the user to enter the value of ‘n’. After entering the value of ‘n’ we will calculate the sum of natural numbers up to n terms with the help of a while loop.

#include<stdio.h>
int main()
{
    int num, i = 0;
    unsigned long int sum = 0;
    printf("Please Enter any Integer number = ");
    scanf("%d",&num);
    if(num >0)
    {
        while(i <= num)
        {
            sum += i;
            i++;
        }
        printf("Sum = %ld\n",sum);
    }
    else
    {
        printf("Enter Valid number\n");
    }
    return 0;
}

Outout:

Please Enter any Integer number = 5
Sum = 15

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now