1. Java Program to find sum of digits without using recursion.
- package com.instaceofjava;
- import java.util.Scanner;
- public class SumOfDigits {
- public static void main(String[] args) {
- int number;
- Scanner in = new Scanner(System.in);
- System.out.println("Please Enter a number");
- number=in.nextInt();
- int sum=0 ;
- while(number!=0){
- sum=sum+(number%10);
- number=number/10;
- }
- System.out.println("Sum of Digits ="+sum);
- }
- }
- Please Enter a number
- 123
- Sum of Digits=6
2. Java Program to find sum of digits using recursion.
- package com.instaceofjava;
- import java.util.Scanner;
- public class SumOfDigits {
- int sum;
- public int CalRecSum(int n){
- if(n==0){
- return sum;
- }
- else{
- sum+=n%10;
- CalRecSum(n/10);
- }
- return sum;
- }
- public static void main(String[] args) {
- int number;
- Scanner in = new Scanner(System.in);
- System.out.println("Please Enter a number");
- number=in.nextInt();
- SumOfDigits ob= new SumOfDigits();
- System.out.println("Sum of Digits ="+ob.CalRecSum(number));
- }
- }
Output:
- Please Enter a number
- 326
- Sum of Digits=11
public class SumOfDigits {
ReplyDeletepublic static void main(String[] args) {
String a = String.valueOf(123456);
String aa[] = a.split("");
int sum =0;
for(String bb:aa){
if(!bb.equals(""))
sum=sum+(Integer.valueOf(bb));
}
System.out.println(sum);
}
}
public static sumDigits(int number){
ReplyDeletereturn sumDigits(number, 0);
}
private static sumDigits(int number, int sum) {
return number == 0 ? sum : sumDigits(number / 10, sum + number % 10);
}
I faced this question in AGILE CRM company interview. Thanks :)
ReplyDelete