Sum of N Natural Numbers

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!

Lecture 15:- Sum of N Natural Numbers

The sum of the first N natural numbers is a common mathematical problem that can be solved using a formula or a loop in programming. The formula for finding the sum of the first N natural numbers is:

Sum = (N * (N + 1)) / 2

Here's an example Java program that calculates the sum of the first N natural numbers using a loop:

javaCopy code

import java.util.Scanner; public class SumOfNaturalNumbers {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter the value of N: ");        int N = scanner.nextInt();        // Calculate the sum using a loop        int sum = 0;        for (int i = 1; i <= N; i++) {            sum += i;        }        System.out.println("Sum of the first " + N + " natural numbers is: " + sum);        scanner.close();    } }

Example output:

mathematicaCopy code

Enter the value of N: 5 Sum of the first 5 natural numbers is: 15

In the program above, we use a for loop to iterate from 1 to N and keep adding each number to the sum variable. After the loop, we print the final sum.

However, it's worth noting that for large values of N, using the formula (N * (N + 1)) / 2 is more efficient than using a loop to add individual numbers. The formula has a time complexity of O(1), while the loop-based approach has a time complexity of O(N).

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?