The Artima Developer Community
Sponsored Link

Java Buzz Forum
Java Program to find Sum of Digits

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
instanceof java

Posts: 576
Nickname: instanceof
Registered: Jan, 2015

instanceof java is a java related one.
Java Program to find Sum of Digits Posted: Dec 19, 2015 10:58 PM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by instanceof java.
Original Post: Java Program to find Sum of Digits
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Latest Java Buzz Posts
Latest Java Buzz Posts by instanceof java
Latest Posts From Instance Of Java

Advertisement

1. Java Program to find sum of digits without using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. public static void main(String[] args) {
  7.  
  8. int number;
  9. Scanner in = new Scanner(System.in);
  10.  
  11. System.out.println("Please Enter a number");
  12.  
  13. number=in.nextInt(); 
  14.  
  15. int sum=0 ;
  16.  
  17. while(number!=0){
  18.  
  19. sum=sum+(number%10);
  20. number=number/10;
  21. }
  22.  
  23. System.out.println("Sum of Digits ="+sum);
  24.  
  25. }
  26. }
Output:

  1. Please Enter a number
  2. 123
  3. Sum of Digits=6


2. Java Program to find sum of digits using recursion.

  1. package com.instaceofjava;
  2. import java.util.Scanner;
  3.  
  4. public class SumOfDigits {
  5.  
  6. int sum;

  7. public int CalRecSum(int n){
  8.  
  9. if(n==0){
  10. return sum;
  11. }
  12. else{
  13.  
  14.  sum+=n%10;
  15.  CalRecSum(n/10);
  16.  
  17.  
  18. return sum;
  19. }

  20. public static void main(String[] args) {
  21.  
  22. int number;
  23. Scanner in = new Scanner(System.in);
  24.  
  25. System.out.println("Please Enter a number");
  26.  
  27. number=in.nextInt(); 
  28.  
  29. SumOfDigits   ob= new SumOfDigits();
  30. System.out.println("Sum of Digits ="+ob.CalRecSum(number));
  31.  
  32. }
  33.  
  34. }
Output:

  1. Please Enter a number
  2. 326
  3. Sum of Digits=11

Read: Java Program to find Sum of Digits

Topic: Is Your Employer a “Best Place To Work” For Developers? Previous Topic   Next Topic Topic: Functional vs Imperative Programming. Fibonacci, Prime and Factorial in Java 8

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use