-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Sunday, September 13, 2020

Java Program To Reverse a Number using For Loop

  • September 13, 2020
  • by

 

Java Program To Reverse a Number using For Loop

In this Java Program, we reverse a number using For loop.

Logic :

   for (;num != 0;)

            {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;

            }

Step 1 : Import the Scanner Class

Step 2 :  Create the main method

Step 3 : Initialize num and reversenum equals to zero

Step 4 : Ask the user to enter the number by using System.out.println() method

Step 5 : Create Scanner object.

Step 6 : Store the captured input in num

Step 7 : Apply for loop logic to reverse the number

Step 8 : In for loop, num should be not equal to zero

Step 9 : Multiply reversenum with 10 and store its result in reversenum.

Step 10 : Add num%10 to reversenum and store the result into reversenum

Step 11 : Divide num by 10 and store the result in num.

Step 12 : Print the reversenum

Program :

import java.util.Scanner;

public class ForLoopReverseDemo 

    {

        public static void main(String args[])

        {

            int num=0;

            int reversenum = 0;

            System.out.println("Input your number and press enter:");

            //This statement will capture the user input

            Scanner sc = new Scanner(System.in);

            //Captured input would be stored in the number num

            num = sc.nextInt();

            //For loop: No initialization part as num is already initialized.

            //No increment/decrement part as logic

            //num = num/10 already decrements the value of num

            for (;num != 0;)

            {

                reversenum = reversenum * 10;

                reversenum = reversenum + num%10;

                num = num/10;

            }

         System.out.println("Reverse of specified number is:"+reversenum);                    

        }

}

Output :

Input your number and press enter:
56789111
Reverse of specified number is:11198765

For execution of the same do visit my YouTube Channel :

A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages