sum of numbers in java code example
Example 1: sum of digits in java
import java.io.*;
public class sd
{
public static void main(String [] args)throws IOException
{
InputStreamReader hi = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(hi);
System.out.println("Enter the number");
int num=Integer.parseInt(in.readLine());
int sum=0;
while(num>=0)
{
int rem=n;
sum+=rem;
int quo=n/10;
n=quo;
}
System.out.println(sum);
}
}
Example 2: java accept 2 integers from the user, and using a method add these numbers and print the result
static void M1(int num1, int num2) {
int sum = num1 + num2;
System.out.println("sum of " + num1 + " and " + num2+ " = " + sum);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1,num2;
System.out.println("Enter a number: ");
num1 =input.nextInt();
System.out.println("Enter 2nd number: ");
num2 =input.nextInt();
input.close();
M1(num1, num2);
}
}
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);
}
}