Thursday, October 15, 2015

Java Fundamentals Homework - Sum the Numbers from 1 to N


Hello,

This is my first ever blog, so I decided what better to post, than my homework from Java Fundamentals which is due on 20.10.15. I hope my solutions can be of some assistance to
whoever is reading. Thank you for your time. Lets begin with the first Problem from the homework.


Problem: Sum the Numbers from 1 to N


Create a Java program that reads a number N from the console and calculates the sum of all numbers from 1 to N (inclusive).




import java.util.Scanner;

public class Sum1toN {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);

        int number = Integer.parseInt(console.nextLine());
        int increase = 0;

        for (int i = 1; i <=number; i++){
            increase += i;
            }
        System.out.print(increase);
        }
    }

No comments:

Post a Comment