Banner Header

Saturday, 2 September 2017

C Program to Calculate the Sum of Natural Numbers

C Program to Calculate the Sum of Natural Numbers

To compute the sum of natural numbers from 1 to n (entered by the user), loops can be used. You will learn how to use for loop and while loop to solve this problem.



The positive numbers 1, 2, 3... are known as natural numbers. The programs below takes a positive integer (let say n) as an input from the user and calculates the sum up to n.

Example #1: Sum of Natural Numbers Using for Loop


#include <stdio.h>
int main()
{
    int n, i, sum = 0;
   
    printf("Enter a positive integer: ");
    scanf("%d",&n);
    for(i=1; i <= n; ++i)
    {
        sum += i;   // sum = sum+i;
    }
    printf("Sum = %d",sum);
    return 0;
}
The above program takes the input from the user and stores in variable n. Then, for loop is used to calculate the sum upto the given number.

Output
Enter a positive integer: 100
Sum = 5050
In both programs, the loop is iterated n number of times. And, in each iteration, the value of i is added to sum and i is incremented by 1.
Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iteration is known.
The above programs doesn't work properly if the user enters a negative integer. Here's a little modification of the above program to take input from the user until positive integer is entered.

Click on the download button to download file

download button


C Program to Calculate the Sum of Natural Numbers Reviewed by Waqas Ahmed Mir PC on September 02, 2017 Rating: 5 C Program to Calculate the Sum of Natural Numbers To compute the sum of natural numbers from 1 to n (entered by the user), loops can be used...

No comments: