C# - Reverse Digits of a Number

Learn: How to reverse digits of a given number using C# program, this post has solved program with explanation.
Submitted by Ridhima Agarwal, on September 17, 2017 [Last updated : March 19, 2023]

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

Example

Input: 721
Output: 127

In this program, we are extracting digits one by one and calculating them to make a complete number (which will be reverse number).

C# program to reverse digits of a given number

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.