-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigitSum.java
More file actions
36 lines (28 loc) · 833 Bytes
/
digitSum.java
File metadata and controls
36 lines (28 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
# calculate the sum of all the digits of an integer input
steps:
-> calls digitSum function with input
-> the function runs a for loop to calculate the sum of all digits until input != 0
-> rightmost digit of the input is extracted each time & added to the sum variable
-> at the end, the function returns the calculated digit sum
*/
import java.util.Scanner;
public class Main
{
public static int digitSum (int num)
{
int sum = 0;
for (int lastDigit; num != 0; num /= 10)
{
lastDigit = num % 10;
sum += lastDigit;
}
return sum;
}
public static void main (String[] args)
{
Scanner sc = new Scanner (System.in);
int num = sc.nextInt();
System.out.print (digitSum (num));
}
}