C Program to find sum of all natural numbers

Category: C Program
Tags: #cprogram#loops

Write a C Program to find the sum of all natural numbers from 1 to n using for loop and while loop. How to find the sum of all natural numbers from 1 to n using while and for loop. Logic to find the sum of all natural numbers within the given range using for loop and while loop.

C Program to find the sum of all natural numbers from 1 to n using for loop

#include <stdio.h>

void main()
{
    int sum = 0, i, n;
    printf("Enter value of n: ");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
        sum = sum + i;

    printf("Sum of numbers 1-%d: %d", n, sum);
}

C Program to find the sum of all natural numbers from 1 to n using while loop

#include <stdio.h>

void main()
{
    int sum = 0, i = 1, n;
    printf("Enter value of n: ");
    scanf("%d", &n);

    while(i <= n)
    {
        sum = sum + i;
        i++;
    }

    printf("Sum of numbers 1-%d: %d", n, sum);
}

Output

Enter value of n: 20
Sum of numbers 1-20: 210