🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
The sum of natural numbers is a common mathematical task that can be easily solved using a loop or a mathematical formula. Natural numbers are positive integers starting from 1. For example, the sum of the first 5 natural numbers (1 + 2 + 3 + 4 + 5) is 15. This guide will show you how to create a Java program that calculates the sum of the first n natural numbers.
Problem Statement
Create a Java program that:
- Takes an integer input
nfrom the user. - Calculates and displays the sum of the first
nnatural numbers.
Example 1:
- Input:
n = 5 - Output:
The sum of the first 5 natural numbers is 15
Example 2:
- Input:
n = 10 - Output:
The sum of the first 10 natural numbers is 55
Solution Steps
- Prompt for Input: Use the
Scannerclass to read an integer inputnfrom the user. - Calculate the Sum Using a Loop: Use a loop to add the numbers from 1 to
n. - Display the Result: Print the calculated sum.
Sum=2n(n+1)
For example, if we want to find the sum of the first 5 natural numbers:
Sum=25(5+1)=15
Java Program
Approach 1: Using a for Loop
import java.util.Scanner;
/**
* Java Program to Find Sum of Natural Numbers using for loop
* Author: https://www.javaguides.net/
*/
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt the user for input
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
// Step 2: Calculate the sum using a for loop
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
// Step 3: Display the result
System.out.println("The sum of the first " + n + " natural numbers is " + sum);
}
}
Explanation
- Input: The program prompts the user to enter a positive integer
n. - Sum Calculation: The program uses a
forloop to iterate from 1 ton, adding each number to the variablesum. - Output: The program prints the sum of the first
nnatural numbers.
Output Example
Example 1:
Enter a positive integer: 5
The sum of the first 5 natural numbers is 15
Example 2:
Enter a positive integer: 10
The sum of the first 10 natural numbers is 55
Approach 2: Using the Formula ( \text{Sum} = \frac{n(n + 1)}{2} )
import java.util.Scanner;
/**
* Java Program to Find Sum of Natural Numbers using Formula
* Author: https://www.javaguides.net/
*/
public class SumOfNaturalNumbersFormula {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt the user for input
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
// Step 2: Calculate the sum using the formula
int sum = n * (n + 1) / 2;
// Step 3: Display the result
System.out.println("The sum of the first " + n + " natural numbers is " + sum);
}
}
Explanation
- Input: The program prompts the user to enter a positive integer
n. - Sum Calculation: The program calculates the sum using the formula ( \text{Sum} = \frac{n(n + 1)}{2} ), which provides a direct way to find the sum without looping.
- Output: The program prints the sum of the first
nnatural numbers.
Output Example
Example 1:
Enter a positive integer: 5
The sum of the first 5 natural numbers is 15
Example 2:
Enter a positive integer: 10
The sum of the first 10 natural numbers is 55
Conclusion
This Java program provides two methods to find the sum of the first n natural numbers: using a for loop and using a mathematical formula. Both methods are effective, but the formula method is more efficient because it calculates the sum in constant time without iteration. These methods are useful in various mathematical and computational tasks where the sum of natural numbers is required.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment