ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Reverse Numbers in Java, C, C#?

Updated on July 1, 2018
rajkishor09 profile image

Raj is an ardent coder who loves exploring new technology. He is an IT pro with 9 years of exp in C#, Angular, React, Vue.

Source

If you just started your programming language learning then it is obvious that your instructor might ask you to write a program to reverse a number in C, C# or Java. I saw many people apply different logic to reverse number like first converting that number to string and then reverse that using any built in string reverse method/function and again converting back to integer. But let me explain you what your instructor exactly wants you to do to reverse a number. We will not use any string reverse or any inbuilt method/function to do so; rather we will use mathematical logic to reverse any user inputted number. I am also going to create new function/method for this purpose and will name it ReverseNumber() which will help you to understand how to create function/method for specific logic.

If you feel your idea about function is not clear then you can read my C programming language tutorial on function and its types. You might find this interesting that function in C and C++ is called method in modern languages like C#, Java. Meaning of both word is same, so never get confused.

How to reverse any number applying mathematical logic

In this section I will explain you how to reverse a number using simple mathematical logic. Those who scares math don’t worry this is going to be very easy explanation as it doesn’t have any complex calculations. Let’s start with our example, we are going to reverse a number say 123 to 321.

We will take few variables to store values; variable names are self explanatory so I am not going to explain which variable is going to hold which value. As you know that length (no. of digits) of 123 is 3 so we have 3 iterations below which explains what happens in each iteration and which variable holds what value.

Variables

numberToReverse = 123, reversedNo = 0, tempNo = 0; 
tempNo = numberToReverse;

Iteration 1:

reversedNo = (reversedNo * 10) + (tempNo % 10) =  (0 * 10) + (123 % 10) = 0 + 3 = 3
tempNo = tempNo / 10 = 123 / 10 = 12

After completing 1st iteration value of reversedNo is 3 and value of tempNo is 12.

Iteration 2:

reversedNo = (reversedNo * 10) + (tempNo % 10) =  (3 * 10) + (12 % 10) = 30 + 2 = 32
tempNo = tempNo / 10 = 12 / 10 = 1

After completing 2nd iteration value of reversedNo is 32 and value of tempNo is 1.

Iteration 3:

reversedNo = (reversedNo * 10) + (tempNo % 10) =  (32 * 10) + (1 % 10) = 320 + 1 = 321
tempNo = tempNo / 10 = 1 / 10 = 0

Congratulation guys we have successfully reversed the given number. After this iteration value of reversedNo would be 321 and value of tempNo would be 0. As I told you earlier that length of 123 is 3 so we have 3 iterations. If you try with any other number like 40678 then there will be 5 iterations as length of 40678 is 5. So don’t get confuse why I am showing here only 3 iterations to reverse a number.

C program to reverse a number

#include "stdio.h"
#include "conio.h"

int ReverseNumber(int numberToReverse);

void main()
{
	int numberToReverse = 0;
	clrscr();
	printf("Enter any number to reverse : ");
	scanf("%d", &numberToReverse);
	printf("Reversed number is : %d", ReverseNumber(numberToReverse));
	getch();
}

int ReverseNumber(int numberToReverse) {
	int reversedNo = 0, tempNo = 0;
	tempNo = numberToReverse;
	while (tempNo > 0) {
		reversedNo = (reversedNo * 10) + (tempNo % 10);
		tempNo = tempNo / 10;
	}
	return reversedNo;
}

Explanation of reverse number program

As I explained it earlier, I applied same logic in all programs. Above program is divided into two parts or you can say in two functions, first is “main()” and second is “ReverseNumber()” function. I have kept number reverse logic in “ReverseNumber()” function and I think this function is good example for those who find writing function difficult. To reverse any number just pass that number as parameter of “ReverseNumber()” function and this function will return reversed value. Don’t you think it’s very simple to have function?

Line no. 16 - 24 is “ReverseNumber()” function and this function takes integer as parameter and return returns integer. We have declared prototype of this function in line no. 4 (know more about function and function prototype here). In this function we have declared two variable of integer type. One will hold temporary value (tempNo) and other will hold final reversed value (reversedNo). In line no. 19 we have while loop which check whether value of tempNo variable is greater than zero (0) or not. This while loop will continue executing its statement till value of tempNo is 0 or less than 0. I am not going to explain logic written inside while loop as it’s been already discussed in beginning of this tutorial.

It’s time to see how we are calling this function from main() function. For us line no. 11 and 12 is interesting one. In line no. 11 we are storing user inputted value to variable numberToReverse. Now we have number to reverse we can call our function “ReverseNumber()” to reverse it. In line no. 12 we did same thing, we called “ReverseNumber()” function and then outputted that value on screen. We can write line no. 12 in different way also, what I used in program is shortcut method.

We can write line no. 12 in following way also:

int result = 0; // declare this in line no. 8.

//you can replace line no. 12 with below 2 lines,
//output will remain same.

result = ReverseNumber(numberToReverse);
printf("Reversed number is : %d",result);

C++ program to reverse a number

#include "conio.h"
#include "iostream.h"

int ReverseNumber(int numberToReverse);

void main()
{
	int numberToReverse = 0;
	clrscr();
	cout<<"Enter any number to reverse : ";
	cin>>numberToReverse;
	cout<<"Reversed number is : "<<ReverseNumber(numberToReverse);
	getch();
}

int ReverseNumber(int numberToReverse) {
	int reversedNo = 0, tempNo = 0;
	tempNo = numberToReverse;
	while (tempNo > 0) {
		reversedNo = (reversedNo * 10) + (tempNo % 10);
		tempNo = tempNo / 10;
	}
	return reversedNo;
}
C & C++ have same editor, so i kept only one output for both code sample.
C & C++ have same editor, so i kept only one output for both code sample. | Source

How to reverse number in C#?

using System;

namespace BasicPrograms
{
    public class NumberReverse
    {
        static void Main(string[] args)
        {
            int numberToReverse = 0;
            Console.Write("Enter any number to reverse : ");
            string num = Console.ReadLine();
            numberToReverse = Convert.ToInt32(num);
            Console.WriteLine("Reversed number is : {0}", ReverseNumber(numberToReverse));
            Console.ReadLine();
        }

        public static int ReverseNumber(int numberToReverse)
        {
            int reversedNo = 0, tempNo = 0;
            tempNo = numberToReverse;
            while (tempNo > 0)
            {
                reversedNo = (reversedNo * 10) + (tempNo % 10);
                tempNo = tempNo / 10;
            }
            return reversedNo;
        }
    }
}

How to reverse number in C# output

I used visual studio 2010 ultimate to develop this code.
I used visual studio 2010 ultimate to develop this code. | Source

How to reverse a number in Java?

import java.util.Scanner;

public class NumberReverse {
    
	public static void main(String[] args) {
		int numberToReverse = 0, reversedNo = 0;
		System.out.print("Enter any number to reverse : ");
		Scanner input=new Scanner(System.in);
		numberToReverse = Integer.parseInt(input.next());		
		System.out.println("Reversed number is : " + ReverseNumber(numberToReverse));
	}
	
	public static int ReverseNumber(int numberToReverse)
	{
		int reversedNo = 0, tempNo = 0;
		tempNo = numberToReverse;
		while (tempNo > 0)
		{
			reversedNo = (reversedNo * 10) + (tempNo % 10);
			tempNo = tempNo / 10;
		}
		return reversedNo;
	}
}

Reverse a number in Java

I used J Creator to develop code in java.
I used J Creator to develop code in java. | Source

Reverse number program poll.

Did this help you to learn about reverse number program logic?

See results

© 2012 RAJKISHOR SAHU

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      amirslovakia 

      4 years ago

      thank you very much

    • profile image

      Gaga 

      5 years ago

      I don't care

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)