Coders Packet

If a 4 digit number is as input (Ex: 1234). Print the output as (2345) in Java

By Ginna Srilekha

If 4 digit number is given as input, we should add 1 to each of its digits and display the output. For Example: 1234. We should print the 2345 as output. So Let's Start.

First we need to take input from the user and save it in variable n.Let us assume our input is take another variable num and save the content of n in num.Now we should count the number of digits in num. So divide the num by 10(1234/10=123.4 ==>123) and increment count.Now count =1.Repeat the process till num=0. When num=0,count=4.

Now we should add 1111 to 1234 to make it 2345.So to get 1111,we use for loop.Now in for loop,take another variable d.Let d=1

For i=1,i<count(1<4) : d=d*10 (d=1*10=10) and d=d+1(d=10+1=11)

For i=2,i<count(2<4) : d=d*10 (d=11*10=110) and d=d+1(d=110+1=111)

For i=3,i<count(3<4) : d=d*10 (d=111*10=1110) and d=d+1(d=1110+1=1111).

For i=4,condition fails .It comes out of for loop.Now take another variable sum and let sum=0.Now add n and d and save it in sum.


print sum.


import java.util.Scanner;
class NextDig
  public static void main(String args[])
    int count=0,num,d=1,sum=0;
    Scanner s=new Scanner(;
System.out.println("Enter 4 digit number:"); int n=s.nextInt(); num=n; while(num!=0) { num=num/10; count=count+1; } for(int i=1;i<count;i++) { d=d*10; d=d+1; } sum=n+d; System.out.println("Value:"+sum); } }


Enter 4 digit number:

Download Complete Code


No comments yet