Pages

Monday, January 13, 2025

First sum of natural numbers in C language

The actual calculation behind:-

1. while(i<=n) {

    sum = sum + i;
    i++;
}

or

2. for(i = 1; i<=n; i++) {
sum += i; // sum = sum + i;
}

advantages of for loop:-
-  more easier.
- makes code concise and more clean.


// First sum of natural numbers in C language
#include <stdio.h>

int main() {
    int n, sum = 0; /// sum = 0 stores the number in memory
    printf("Enter your first N natural number: ");
    scanf("%d", &n);
    
    // Using a loop to calculate the sum
    // for(int i = 1; i <= n; i++) {
    //     printf("%d\n", i);
    //     sum += i;
    // }
    sum = (n*(n+1))/2;
    
    printf("The first sum of %d Natural numbers are: %d\n", n, sum);
    
    

    return 0;
}


FORMULA:- 


No comments:

Post a Comment

how to become red on codeforces by Errichto Algorithms | explained simply in a blog

 Yes. I found an available transcript of the video and summarized it simply. The video is “How To Become Red Coder? (codeforces.com)” by Err...