Sum Of Two Digits in Java


Q. Write a Java program for Sum of Two Digits

 import java.util.Scanner;

public class SumOfTwoDigits {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read a two-digit number from the user
        System.out.print("Enter a two-digit number: ");
        int number = scanner.nextInt();

        // Check if the number has exactly two digits
        if (number >= 10 && number <= 99) {
            int firstDigit = number / 10;       // Get tens digit
            int secondDigit = number % 10;      // Get ones digit
            int sum = firstDigit + secondDigit;

            System.out.println("Sum of digits = " + sum);
        } else {
            System.out.println("Please enter a valid two-digit number.");
        }

        scanner.close();
    }
}

Q. Write an algorithm for Sum of Two Digits

1. Start
2. Read a two-digit number and store it in number
3. Check if number is between 10 and 99
    a. If not, display "Invalid input" and stop
4. Extract the first digit: firstDigit = number / 10
5. Extract the second digit: secondDigit = number % 10
6. Calculate the sum: sum = firstDigit + secondDigit
7. Print the result
8. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.