Object-Oriented Programming with Java, part I – Exercise 32

This program calculates the series 1+2+3+…+n where n is input by the user.

My Code

import java.util.Scanner;

public class TheSumOfSetOfNumbers {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        
        System.out.print("Until what? ");
        int input = Integer.parseInt(reader.nextLine());
        
        int tick = 1;
        int sum = 1;
        
        while (input > tick){
            sum = sum + tick;
            sum++;
            tick++;
        }
        
        System.out.println("Sum is " + sum);

    }
}

Model Code

import java.util.Scanner;

 

public class TheSumOfSetOfNumbers {

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

 

        System.out.print("Until what? ");

        int limit = Integer.parseInt(reader.nextLine());

 

        int sum = 0;

        int number = 1;

        while (number <= limit) {

            sum += number;

            number++;

        }

 

        System.out.println("Sum is " + sum);

    }

}

Comments

The model solution is better than mine and definitely easier to follow.

Leave a Reply

Your email address will not be published. Required fields are marked *