Adding One Each Digits Program in Java


If a five-digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits. For example, if the number that is input is 12391 then the output should be displayed as 23402.


The program prompts the user to enter a five-digit number using the System.out.println statement and then reads the input using the Scanner class.

The program then performs the following steps for each digit:

  • Extracts the digit using integer division and modulus operators.
  • Adds one to the extracted digit.
  • Multiplies the result of step 2 by the appropriate power of 10.
  • Adds the result of step 3 to a running sum.

Finally, the program outputs the sum of the modified digits using the System.out.println statement.

Note that this program assumes that the input is a valid five-digit number and that the result will be a valid integer. It also assumes that the input and output will not exceed the range of the int data type.

Source Code

import java.util.Scanner;
class Add_One_Each_Digit
{
	public static void main(String args[])
	{
		Scanner input = new Scanner(System.in);
		System.out.println("Enter the Five Digits Numbers :");
		int num = input.nextInt();
		System.out.println("Original Digits :"+num);	
		int a,sum=0;
		a = (num / 10000)+1;
		num = num % 10000;
		sum=sum+(a*10000);
 
		a = (num / 1000)+1;
		num = num % 1000;
		sum = sum+(a*1000);
 
		a = (num / 100)+1;
		num = num % 100;
		sum = sum+(a*100);		 
 
		a = (num / 10)+1;
		num = num % 10;
		sum = sum+(a*10);		 
 
		a = num+1;
		sum = sum+a;
 
		System.out.println("Adding One to Each Digits :"+sum);
	}
}

Output

Enter the Five Digits Numbers :
53278
Original Digits :53278
Adding One to Each Digits :64389