Write a program that prints out the sum of the numbers from 1 to n, where n can be any positive integer. Use a method to calculate this sum, with one parameter of one int n. You can also read in the int from the user to make the program more interactive.

top of page

bottom of page

import java.util.Scanner; class Main { public static void main(String[] args) { Scanner x = new Scanner(System.in); int n = x.nextInt(); int sum = 0; if (n >= 1){ sum = my_sum(n); System.out.println(sum); } } public static int my_sum(int n) { int sum = 0; for ( int a=1; a <=n; a++ ) { sum = sum + a; } return sum; } }

I actually don't know how to do this one.