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.

To see this working, head to your live site.

Search

kevinzhao183

Mar 07

# Intro to Java 3/6/21 Homework

Intro to Java 3/6/21 Homework

2 comments

0

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

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; } }