Calculating the Sum of First n Natural Numbers using Loops in C || Unveiling the Logic behind Sum of First n Natural Numbers

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

    // Prompt user to enter a number
    printf("Enter a number: ");
    scanf("%d", &n);

    // Loop to calculate the sum of first n natural numbers
    for (int i = 0; n >= i; i++)
    {
        ; // Accumulate the current value of 'i' into 'sum'
        /*For n=3,
        when loop executes first time(i=1),sum = sum + i means 0+1=1
        when loop executes second time(i=2),sum = sum + i means 1+2=3
        when loop executes third time(i=3),sum = sum + i means 3+3;
        */
    }

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

    return 0;
}

// Blog Title: "Sum of First n Natural Numbers: Exploring Loops in C Programming"
// Keywords: C programming, loops, natural numbers, sum calculation, number series

 Certainly! The expression `sum = sum + i` is a common construct in programming and represents an assignment operation that updates the value of the variable `sum`.


Here's a breakdown of how it works in the context of your code:


1. **Initialization**: At the beginning of the program, the variable `sum` is initialized to 0. This is the initial value of the sum.


2. **Loop Iteration**: The `for` loop iterates from `i = 0` up to `n` (inclusive), where `n` is the number entered by the user.


3. **Accumulation**: In each iteration of the loop, the value of `i` (which represents the current loop iteration number) is added to the current value of `sum`.


   For example:

   - In the first iteration (`i = 0`), `sum` remains 0 + 0 = 0.

   - In the second iteration (`i = 1`), `sum` becomes 0 + 1 = 1.

   - In the third iteration (`i = 2`), `sum` becomes 1 + 2 = 3.

   - And so on...


4. **Final Result**: After the loop completes all iterations, the variable `sum` holds the sum of the first `n` natural numbers. This is the sum you are calculating and displaying at the end of your program.


So, the expression `sum = sum + i` is used to incrementally accumulate the value of `i` into the variable `sum`, effectively calculating the sum of the numbers from 0 up to `n`.


It's a fundamental concept in programming to update variables based on calculations, and it plays a key role in many algorithms and programs.

Comments

Popular posts from this blog

Weird Algorithm || Introductory Problem || CSES