Wednesday, 12 August 2015

Sum Of Digits

package com.JavaInterview.Programs;

import java.util.Scanner;

/**
 * Find Out Factorial of a number
 * 
 * @author:http://javainterviewprograms.blogspot.in/
 * 
 */

public class SumOfDigit {

 int totalSum = 0;

 public int sum(int number) {

  if (number == 0) {
   return totalSum;

  } else {
   totalSum += (number % 10);
   sum(number / 10);
  }
  return totalSum;
 }

 public static void main(String args[]) {
  Scanner input = new Scanner(System.in);
  System.out.println("Please enter number :");
  int number = input.nextInt();

  SumOfDigit SD = new SumOfDigit();
  System.out.println("sum Of Digit of Number  " + number + " :"
    + SD.sum(number));
 }
}

Output:
Please enter number :
23
sum Of Digit of Number  23 :5


No comments:

Post a Comment

Difference between final, finally and finalize()?

final :Final is a keyword. Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final ...