ADVERTISEMENT
ADVERTISEMENT

java program to find sum and product of all digits of a number using class

In this program we will read a positive integer number and then calculate product of all digits using a class. For example, if input number is 12345 - sum of all digits, product of all digits will be 15 , 120.

// Java program to find sum and product of 
// all digits using class

import java.util.*;

class DigitsOpr {
  private int num;

  //function to get value of num
  public void getNum(int x) {
    num = x;
  } /*End of getNum()*/

  //function to calculate sum of all digits
  public int sumDigits() {
    int n, sum = 0;
    n = num; //keep value of num safe

    while (n > 0) {
      sum += (n % 10); //find digit using n=n%10 
      n /= 10;
    }
    return sum;
  } //End of sumDigits()

  //function to calculate product of all digits
  public int productDigits() {
    int n, pro;
    n = num; //keep value of num safe
    pro = 1;
    while (n > 0) {
      pro *= (n % 10); //find digit using n=n%10 
      n /= 10;
    }
    return pro;
  } //End of productDigits()
}

public class Main {
  public static void main(String[] s) {
    DigitsOpr dig = new DigitsOpr();
    int n;

    Scanner sc = new Scanner(System.in);

    //read number
    System.out.print("Enter an +ve integer number:");
    n = sc.nextInt();

    dig.getNum(n);
    System.out.println("SUM of all digits: " + dig.sumDigits());
    System.out.println("PRODUCT of all digits: " + dig.productDigits());

  }
}

Output

Compile: javac Main.java
Run: java Main

Output: Enter an +ve integer number:1234567 SUM of all digits: 28 PRODUCT of all digits: 5040

Java Class and Object Programs »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.