A Java Program to find the single digit sum of a number
This program can be used to find the single digit sum of the given number in java. In this post you can find recursive as well as iterative method. Unlike just finding the sum of digits in a given integer, if further finds the same until a single digit is achieved.
Screenshots [Demo]
The Iterative Method:
The Recursive Method:
Stuck anywhere, ask us. We will be glad helping you :)
Screenshots [Demo]
The output of both Recursive and Iterative method are displayed above !
The Iterative Method:
import java.util.Scanner; class SingleIte { public static void main(String []as) { Scanner sc=new Scanner(System.in); int n,s=0,f=0; System.out.print("Enter The digit: "); n=sc.nextInt(); while(f==0) { while(n>0) { s=s+(n%10); n=n/10; } if(s<10) f=1; else { n=s; s=0; } } System.out.println("The Sigle digit sum is: "+s); } }
The Recursive Method:
import java.util.Scanner; class SingleRec { public static void singleSum(int n) { int s=0; while(n>0) { s=s+(n%10); n=n/10; } if(s<10) System.out.println("The Sigle digit sum is: "+s); else singleSum(s); } public static void main(String []as) { Scanner sc=new Scanner(System.in); System.out.print("Enter The digit: "); singleSum(sc.nextInt()); } }
Stuck anywhere, ask us. We will be glad helping you :)
Thank you Sir but what if the the input is negative integer ?
ReplyDelete