Java Program to find sum of digits without using recursion.
package
javaprgms;
import
java.util.Scanner;
public class
SumOfDigits {
public static void main(String[] args) {
int number;
@SuppressWarnings("resource")
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);
}
}
Output:
Please Enter a number
231
Sum of Digits =6
Java Program to find sum of digits using recursion.
package
javaprgms;
import java.util.Scanner;
public class sd {
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();
sd ob= new sd();
System.out.println("Sum
of Digits ="+ob.CalRecSum(number));
}
}
Output:
Please Enter a number
342435
Sum of Digits =21
No comments:
Post a Comment