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.
Program:
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.
Output:
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.