Function SumDigits Learn programming Java

Lesson:

Functions


Exercise:

Function SumDigits 39


Objetive:

Create a function SumDigits that receives a number and returns any results in the sum of its digits. For example, if the number is 123, the sum would be 6.

Console.Write( SumDigits(123) );
6


Code:

public class Main
{
	public static int SumDigits(int n)
	{
		String number = String.valueOf(n);

		int sum = 0;

		for (int i = 0; i < number.length(); i++)
		{
			sum += Integer.parseInt(number.substring(i, i + 1));
		}

		return sum;
	}

	public static void main(String[] args)
	{
		System.out.println(SumDigits(123));
	}
}