Java Online Compiler
Example: Sum of Natural Numbers (Iterative) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sum of Natural Numbers (Iterative) import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Prompt user for input System.out.print("Enter a positive integer (n): "); int n = scanner.nextInt(); // Step 2: Validate input if (n < 0) { System.out.println("Please enter a non-negative integer."); } else { // Step 3: Calculate sum iteratively int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } // Step 4: Display the result System.out.println("The sum of natural numbers up to " + n + " is: " + sum); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS