Q:

C# program to find the magnitude of an integer number

belongs to collection: C# Basic Programs | basics

-1

C# program to find the magnitude of an integer number

All Answers

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

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.

// 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.

 

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

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to demonstrate the example of the left-... >>
<< C# program to swap numbers using XOR operator...