3
28/10/2024 7:10 pm
Topic starter
Create a Java program that reads a number N from the console and calculates the sum of all numbers from 1 to N (inclusive).
Must be like this:
1 Answer
2
28/10/2024 7:11 pm
This inclusive means that in the for loop you must be careful - add <=; Here is my solution:
import java.util.Scanner; public class SumNumbersFromOneToN06 { public static void main(String[] args) { Scanner console = new Scanner(System.in); int number = Integer.parseInt(console.nextLine()); int sum = 0; for (int i = 0; i <= number; i++) { sum = sum + i; } System.out.println(sum); } }