C# program to convert a decimal number into an octal number

Here, we are going to learn how to convert a decimal number into an octal number in C#? By Nidhi Last updated : April 15, 2023

Decimal to Octal Conversion in C#

Here we will read a decimal number and then convert it into a corresponding octal number.

C# program for decimal to octal conversion

The source code to convert a decimal number to the octal number is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to convert a decimal number into an octal number.

using System;

class Program
{
    static void Main(string[] args)
    {
        int decNum = 0;
        int octNum = 0;
        string temp = "";
        

        Console.Write("Enter a Decimal Number :");
        decNum = int.Parse(Console.ReadLine());


        while (decNum != 0)
        {
            temp += decNum % 8;
            decNum = decNum / 8;
        }

        for (int i = temp.Length - 1; i >= 0; i--)
        {
            octNum = octNum * 10 + temp[i] - 0x30;
        }

        Console.WriteLine("Octal Number is " + octNum);
    }
}

Output

Enter a Decimal Number :11
Octal Number is 13
Press any key to continue . . .

Explanation

In the above program, we create a class Program that contains the Main() method, In the Main() method we read a decimal number from user input and then convert the decimal number into the corresponding octal number.

while (decNum != 0)
{
    temp += decNum % 8;
    decNum = decNum / 8;
}

In the above code, we find the remainder of the decimal number after dividing by 8 and then concatenate into the string, because the base of the octal number is 8.

for (int i = temp.Length - 1; i >= 0; i--)
{
    octNum = octNum * 10 + temp[i] - 0x30;
}

In the above code, we reversed the remainder string and covert into the integer number and then print the result on the console screen.

C# Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





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