Home »
.Net »
C# Programs
Find the Magnitude of an Integer Number in C#
Given an integer number and we have to find its magnitude using C# program.
By Nidhi Last updated : April 15, 2023
Magnitude of an Integer Number
Here we will find the magnitude of an integer number, here magnitude of a number specify the length of number, for example:
Number= 543623; Then the magnitude of the number is 6.
C# program to find the magnitude of an integer number
The source code to find the magnitude of an integer number in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
// Write a program to find the
// magnitude of an integer number in C#.
using System;
public class MagnitudeDemo {
public static int GetMagnitude(int num) {
int magnitude = 0;
while (num > 0) {
magnitude++;
num = num / 10;
}
return magnitude;
}
public static void Main() {
int num = 34521;
int mag = 0;
mag = GetMagnitude(num);
Console.WriteLine("Magnitude: " + mag);
}
}
Output
Magnitude: 5
Press any key to continue . . .
Explanation
In the above program, we created a class MagnitudeDemo that contains GetMagnitude() and Main() methods. The GetMagnitude() method returns the magnitude of the specified number.
Here we divide the number by 10 till it becomes 0. In every iteration of while loop we increase the value of magnitude variable by 1 and reduce the number num by 1 digit in length.
In the Main() method, we created an integer variable num initialized with 34521 and then pass the variable in the static method GetMagnitude() and get the magnitude in local variable mag and then printed the value of mag on the console screen.
C# Basic Programs »