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

This program calculates the sum of 1+2+3….+n but asks for an upper and lower bound to do so.

My Code

import java.util.Scanner;


public class TheSumBetweenTwoNumbers {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        
        System.out.print("First? ");
        int first = Integer.parseInt(reader.nextLine());
        
                System.out.print("Last? ");
        int last = Integer.parseInt(reader.nextLine());
        
        int tick = first;
        int sum = first;
        
        while (last > tick){
            sum = sum + tick;
            sum++;
            tick++;
        }
        
        System.out.println("Sum is " + sum);
        
    }
}

Model Code

import java.util.Scanner;

 

 

public class TheSumBetweenTwoNumbers {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        

        System.out.print("First: ");

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

        System.out.print("Last: ");

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

        int sum = 0;

 

        int number = first;

        while (number <= last) {

            sum += number;

            number++;

        }

 

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

        

    }

}

Comments

It’s amazing how different the model code is from my code even though they both do the same thing.

Leave a Reply

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