Program to Reverse a Number - (C# Basic Programs)
Reversing a number is a basic programming exercise that helps beginner programmers learn about variables, loops, and conditional statements. In this tutorial, we will discuss a program to reverse a number using C# programming language.
Syntax
The syntax for reversing a number in C# is as follows:
int num = 1234;
int reversedNum = 0;
while (num > 0) {
int remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
Example
using System;
public class Program {
public static void Main(string[] args) {
int num, reversedNum = 0, remainder;
Console.WriteLine("Enter a positive integer:");
num = int.Parse(Console.ReadLine());
while (num != 0) {
remainder = num % 10;
reversedNum = reversedNum * 10 + remainder;
num /= 10;
}
Console.WriteLine("The reversed number is: " + reversedNum);
}
}
Output:
Enter a positive integer:
7481
The reversed number is: 1847
Explanation
The program first prompts the user to input a positive integer. It then goes through a loop that separates each digit of the input and concatenates it in reverse order to form the reversed number. The process involves calculating the remainder when the input integer is divided by 10, and then adding that remainder to the reversed number being built.
Use
Reversing a number is a program that provides practice for beginner C# programmers to develop an understanding of loops, conditional statements, integer variables, and arithmetic operations. It can also be used as a subroutine in other more complex programs where reversing a number is necessary.
Summary
In this tutorial, we have discussed a program to reverse a number using C# programming language. We have seen the syntax, an example, explanation, and use of the program. This basic programming exercise can help beginner programmers build a solid foundation and prepare them for more complex programs that require a deeper understanding of conditional statements and loops.