C Program to Calculate the Sum of Natural Numbers

@codevarsity
 · 
2.1k views
 · 

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.

Code

#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;
}

Output

Enter a positive integer: 100
Sum = 5050

Comments