how to compute sum of 2 numbers in java code example

Example 1: how to output sum of even numbers in java between two user values

//import classes
import java.util.*;

public class chapter5no9
{
    static Scanner console = new Scanner(System.in);

    public static void main(String[] args)
    {

    //Part A
    int firstNum;
    int secondNum;
    int sumEven;

    System.out.println("Please enter an integer: ");
    firstNum = console.nextInt();

    System.out.println("Please enter another integer less than the first integer: ");
    secondNum = console.nextInt();

    //Part B
    if (firstNum < secondNum)
    {
        System.out.print("Your second number is greater than the first.  So Please re-enter: ");
        secondNum = console.nextInt();
    }
    else
    {
        System.out.print("Odd Numbers: ");
        firstNum++;
        while (firstNum > secondNum)
        {
            if (secondNum % 2 != 0)
            {
                System.out.print(" " + secondNum);
            }
            secondNum++;
        }

        System.out.println();
        System.out.print("Sum of Even Numbers: ");
        firstNum++;
        while (firstNum > secondNum)
        {
            if (secondNum % 2 != 0)
            {
                System.out.print(" " + secondNum);
            }
            secondNum++;
        }
    }
}

Example 2: sum of numbers in java

public class SumNatural {

    public static void main(String[] args) {

        int num = 100, sum = 0;

        for(int i = 1; i <= num; ++i)
        {
            // sum = sum + i;
            sum += i;
        }

        System.out.println("Sum = " + sum);
    }
}

Tags:

Java Example