Sum of Natural Numbers In C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C, to calculate the sum of the first N natural numbers (1+2+3+...+N), you can use a loop to iterate through the numbers and add them together.

Here is an example of how this can be done using a for loop:

Copy code

#include <stdio.h> int main() {    int n, sum = 0;    printf("Enter the value of n: ");    scanf("%d", &n);    for (int i = 1; i <= n; i++) {        sum += i;    }    printf("Sum of first %d natural numbers: %d", n, sum);    return 0; }

This program prompts the user to enter an integer value for n, and then uses a for loop to iterate through the numbers from 1 to n, adding each number to the sum. Finally, it prints the result.

Alternatively, you can also use the formula to calculate the sum of natural numbers which is N*(N+1)/2,

Copy code

#include <stdio.h> int main() {    int n, sum = 0;    printf("Enter the value of n: ");    scanf("%d", &n);    sum = n*(n+1)/2;    printf("Sum of first %d natural numbers: %d", n, sum);    return 0; }

This program also prompts the user to enter an integer value for n and then uses the formula to calculate the sum of the first n natural numbers. Finally, it prints the result.

It's important to note that the first program will have a time complexity of O(n) while the second program will have a time complexity of O(1) which is more efficient and faster.

4. Operators

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?