Write a C Program to Calculate Sum of Natural Numbers.

Prince Patel
By -
0

Write a C Program to Calculate Sum of Natural Numbers.



Understanding the Problem

Before we dive into the code, let's understand the problem at hand. We are tasked with calculating the sum of the first 'n' natural numbers. Natural numbers are the positive integers starting from 1, such as 1, 2, 3, and so on.

Approach

To calculate the sum of natural numbers without using structures and functions, we can take a straightforward iterative approach. We'll use a loop to iterate through the natural numbers up to 'n', and in each iteration, we'll add the current natural number to a running total. Finally, we'll display the calculated sum.

Here's a  C Program to Calculate Sum of Natural Numbers:

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

      printf("Enter a positive integer: ");
      scanf("%d", &n);

      if (n <= 0)
     {
          printf("Please enter a valid positive integer.\n");
          return 1; // Exit with an error code
     }

     for (int i = 1; i <= n; i++)
     {
             sum += i; // Add the current natural number to the sum
     }

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

  • In this program, we declare two variables: n to store the input natural number and sum to store the running sum. 
  • We prompt the user to enter a positive integer using printf and then scan the input using scanf.
  • We check if the input 'n' is valid (greater than 0) and provide an error message if it's not.
  • We use a for loop to iterate from 1 to 'n'. In each iteration, we add the current value of 'i' to the sum variable.
  • Finally, we print the result using the printf function.
Output:






Tags:

Post a Comment

0Comments

Post a Comment (0)