java sum two numbers code example
Example 1: java sum of two numbers program intellij
public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 15, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Example 2: java sum of two numbers program intellij
import java.util.Scanner;
public class AddTwoNumbers2 {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Example 3: 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 += i;
}
System.out.println("Sum = " + sum);
}
}