Sum Of Digits | Write a program in Java to print the sum of digits of a number. | ISC Computer Science | ICSE Computer Application

Image is Unavailable

Algorithm

  1.   Start
  2. in:=0
  3. temp:=0
  4. digit:=0
  5. sum:=0
  6. Print "Enter a number"
  7. Read n
  8. temp=in
  9. sum=0
  10. If temp>0, go to step 11 or else go to step 11 or else go to step 15
  11. digit=temp%10
  12. sum=sum+digit
  13. temp=temp/10
  14. Go to step 10
  15. Print "The sum of digits of "+in+" is "+sum
  16. Stop

Program

BufferedReader

import java.io.*;
class DigiSum
{
    int in, temp, digit, sum;
    void accept() throws IOException
    {
        BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
        System.out.println("Enter a number");
        in=Integer.parseInt(br.readLine());
    }
    
    void sumOfDigits()
    {
        temp=in;
        sum=0;
        while(temp>0)
        {
            digit=temp%10;
            sum=sum+digit;
            temp=temp/10;
        }
    }
    
    void display()
    {
        System.out.println("The sum of digits of "+in+" is "+sum);
    }
    
    void main() throws IOException
    {
        accept();
        sumOfDigits();
        display();
    }
}

Scanner

import java.util.*;
class DigiSum
{
    int in, temp, digit, sum;
    void accept()
    {
        Scanner sc=new Scanner (System.in);
        System.out.println("Enter a number");
        in=sc.nextInt();
    }
    
    void sumOfDigits()
    {
        temp=in;
        sum=0;
        while(temp>0)
        {
            digit=temp%10;
            sum=sum+digit;
            temp=temp/10;
        }
    }
    
    void display()
    {
        System.out.println("The sum of digits of "+in+" is "+sum);
    }
    
    void main()
    {
        accept();
        sumOfDigits();
        display();
    }
}

Documentation

Variable Description

 Data TypeVariable NameDescription
 intin To store the number accepted by the user 
 inttemp To act as a temp variable 
 intdigit To store the digit of the number 
 intsum To store the sum of digits of a number 

Method Description

Return Type Method NameDescription
 voidaccept() To accept data from the user 
 voidsumOfDigits() To calculate the sum of digits of a number 
 voiddisplay() To display the sum of digits 
 voidmain() To act as an entry gateway for the compiler 

Output

Image is Unavailable





Share with all ISC Computer Science Students you know.

Comment below with all your program requests and blog suggestions.

Follow us on social media by clicking on these links. 
Instagram : @ISCJavaCode
Twitter: @ISCJavaCode
Reddit: @ISCJavaCode
Pinterest: @ISCJavaCode
Facebook: @ISCJavaCode
LinkedIn : ISC Java Code 


Stay Healthy
Stay Happy
Stay Helpful



Comments

You might also like:

Conversion of Complex Sentences to Simple Sentences

Conversion of Compound Sentences to Complex Sentences.

Conversion of Complex Sentences to Compound Sentences