write a program to accept a number then print the sum of digits and number of digits present in it.(e.g.if the input number is 225, the sum of digits is 9 and number of digits is 3).
Answers
Answered by
4
Required Answer:-
Question:
- Write a program to accept a number and print the sum of digits and the number of digits present in it.
Solution:
Here comes the program.
import java.util.*;
public class Number {
public static void main(String[] args) {
int n,c=0,s=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number: ");
n=sc.nextInt();
while(n!=0) {
s+=n%10;
c++;
n/=10;
}
System.out.println("Sum of digits: "+s);
System.out.println("Number of digits: "+c);
sc.close();
}
}
Algorithm:
- START
- Accept the number.
- Initialise count = 0, sum = 0
- Divide the number till the number is not zero.
- Increment the value of count.
- Add the remainder to sum variable when the number is divided by 10.
- Display the sum and number of digits.
- STOP.
See the attachment for output ☑.
Attachments:
Similar questions