I am new to Java Programming and I stumbled upon below copy pasted code ( which I found from: How to sum digits of an integer in java?)
I am struggling to understand this code and basically would like an explanation on the following line: sum += c -'0'; What does this line evaluate to? and what is the purpose of -'0' ?
thanks all in advance.
import java.util.Scanner;
public class RandomPractice1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("enter some digits: "); String digits = input.nextLine(); //try digits 55 int sum = 0; for (char c : digits.toCharArray()) { sum += c -'0'; } System.out.printf("sum of numbers %s is %d\n", digits, sum); //the answer is 10 } }