w3resource

C#: Convert an octal number into binary


C# Sharp For Loop: Exercise-54 with Solution

Write a program in C# Sharp to convert an octal number into binary.

C# Sharp: Convert an octal number into binary

Sample Solution:-

C# Sharp Code:

using System;  // Importing necessary namespace

public class Exercise54  // Declaration of the Exercise54 class
{  
    public static void Main()  // Main method, entry point of the program
    {
        int n1, n5, p = 1;  // Declaration of variables
        int dec = 0, i = 1, j, d;
        int binno = 0;
	
        Console.Write("\n\n");
        Console.Write("Convert Octal to Binary:\n");
        Console.Write("--------------------------");
        Console.Write("\n\n");

        Console.Write("Input an octal number (using digit 0 - 7) :");
        n1 = Convert.ToInt32(Console.ReadLine());  // Taking user input for an octal number
        n5 = n1;  // Storing the original octal number for display at the end

        // Converting the octal number to its decimal equivalent
        for (j = n1; j > 0; j = j / 10)
        {  
            d = j % 10;
            if (i == 1)
                p = p * 1;
            else
                p = p * 8;

            dec = dec + (d * p);
            i++;
        }

        /* Converting the obtained decimal equivalent to its binary representation */
        i = 1;
        for (j = dec; j > 0; j = j / 2)
        {
            binno = binno + (dec % 2) * i;
            i = i * 10;
            dec = dec / 2;
        }

        // Displaying the original octal number and its equivalent binary number
        Console.Write("\nThe Octal Number : {0}\nThe equivalent Binary  Number : {1} \n\n", n5, binno);
    }
}

Sample Output:

Convert Octal to Binary:                                                                                    
--------------------------                                                                                  
Input an octal number (using digit 0 - 7) :45                                                               
The Octal Number : 45                                                                                       
The equivalent Binary  Number : 100101

Flowchart:

Flowchart : Convert octal number into binary

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to convert a binary number to octal.
Next: Write a program in C# Sharp to convert a decimal number to hexadecimal.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/csharp-exercises/for-loop/csharp-for-loop-exercise-54.php