C

C Program To Calculate The Sum Of The First N Natural Numbers

Find the sum of the first n natural numbers with this program. We’ll look at two C programs that compute the sum of natural numbers. In the first C program, we use the for loop to find the sum, and in the second, we use the while loop.
You should be familiar with the following C Programming Concepts in order to understand these programs:

  • C loop programming
  • While loop in C programming

Example 1: Use a for loop to find the sum of natural numbers.

The user enters the value of n, and the program uses a for loop to calculate the sum of the first n natural numbers.

#include <stdio.h>
int main()
{
    int n, count, sum = 0;

    printf("Enter the value of n(positive integer): ");
    scanf("%d",&n);

    for(count=1; count <= n; count++)
    {
        sum = sum + count;
    }

    printf("Sum of first %d natural numbers is: %d",n, sum);

    return 0;
}

Output:

Enter the value of n(positive integer): 6
Sum of first 6 natural numbers is: 21

Example 2: Using a while loop, compute the sum of natural numbers

#include <stdio.h>
int main()
{
    int n, count, sum = 0;

    printf("Enter the value of n(positive integer): ");
    scanf("%d",&n);

    /* When you use while loop, you have to initialize the
     * loop counter variable before the loop and increment
     * or decrement it inside the body of loop like we did 
     * for the variable "count"
     */
    count=1;
    while(count <= n){
    	sum = sum + count;
    	count++;
    }

    printf("Sum of first %d natural numbers is: %d",n, sum);

    return 0;
}

Output:

Enter the value of n(positive integer): 7
Sum of first 7 natural numbers is: 28

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button