Q:

C# program to reverse digits of a given number

belongs to collection: C# Basic Programs | Looping programs

0

Given an integer number and we have to print its digits in reverse order.

Example:

Input: 721
Output: 127

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program:

using System;

namespace system
{
    class reverse
    {
    	static void Main(String[] args)
    	{
		int a=721, rev=0, b;

		//condition to check if the number is not 0
		while(a!=0)
		{
			b=a%10;        //extract a digit
			rev=(rev*10)+b;   //reverse the digits logic
			a=a/10;             //remained number
		}
		Console.WriteLine("The reverse of the number is: " +rev); 
    	}
    }
}

Output

The reverse of the number is: 127

Explanation:


Inital value of a (input number): a = 721
Inital value of rev = 0


Iteration 1:
	b = a%10  → 721%10 = 1
	rev = (rev*10)+b  → (0*10)+1 = 1
	a = a/10 → 721/10 = 72

Iteration 2:
	b = a%10  → 72%10 = 2
	rev = (rev*10)+b  → (1*10)+2 = 12
	a = a/10 → 72/10 = 7

Iteration 3:
	b = a%10  → 7%10 = 7
	rev = (rev*10)+b  → (12*10)+7 = 127
	a = a/10 → 7/10 = 0

Now, the value of a is "0", condition will be fasle
Output will be 127.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< C# program to find sum of all digits of a given nu...