Hello im new to java and in my class my prof wants us to create a program that will compute the sum of two numbers. (Use methods) For example: Input an integer: 95 //Expected Output: The sum is 14 //(9+5=14)
im really lost on this one because i really don’t know how to do this please help
Advertisement
Answer
If you use Java you can use this code:
JavaScript
x
12
12
1
int num = 95;
2
int sum = 0;
3
4
while (0 != num) {
5
// add the last digit of the given number to the sum
6
sum = sum + (num % 10);
7
// remove the last digit of the given number
8
num = num / 10;
9
}
10
11
System.out.println(sum);
12
(The code in JavaScript is very similar)