import java.io.*;
public class SumOfDigits
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter Number::");
int n = Integer.parseInt(br.readLine());
int t = n;
int r;
for (r = 0; n > 0; n = n / 10)
r = r + n % 10;
System.out.println("\nSum of Digits of " + t + " is :: " + r);
}
}
OUTPUT::
Enter Number::12345
Sum of Digits of 12345 is :: 15
public class SumOfDigitsRecursive
{
int sum(int n)
{
int res;
if (n < 0)
n *= -1; // making number positive
if (n == 0)
return 0;
else
{
res = n % 10 + sum(n / 10);
return res;
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Number:: ");
int n = Integer.parseInt(br.readLine());
SumOfDigitsRecursive obj = new SumOfDigitsRecursive();
int s = obj.sum(n);
// Displaying Result
System.out.println("\nSum of Digits is:: " + s);
}
}
public class SumOfDigits
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter Number::");
int n = Integer.parseInt(br.readLine());
int t = n;
int r;
for (r = 0; n > 0; n = n / 10)
r = r + n % 10;
System.out.println("\nSum of Digits of " + t + " is :: " + r);
}
}
OUTPUT::
Enter Number::12345
Sum of Digits of 12345 is :: 15
Using Recursive Function
import java.io.*;public class SumOfDigitsRecursive
{
int sum(int n)
{
int res;
if (n < 0)
n *= -1; // making number positive
if (n == 0)
return 0;
else
{
res = n % 10 + sum(n / 10);
return res;
}
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Number:: ");
int n = Integer.parseInt(br.readLine());
SumOfDigitsRecursive obj = new SumOfDigitsRecursive();
int s = obj.sum(n);
// Displaying Result
System.out.println("\nSum of Digits is:: " + s);
}
}
OUTPUT::
Enter Number:: 12345
Sum of Digits is:: 15