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 1234.now 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.

sum=n+d=1234+1111=2345.

print sum.

Code:

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.in);
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); } }

Output:

Enter 4 digit number:
1234
Value:2345

Download Complete Code

Comments

No comments yet