w3resource

C#: Convert binary number to octal

C# Sharp For Loop: Exercise-53 with Solution

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

C# Sharp: Convert binary number to octal

Sample Solution:-

C# Sharp Code:

using System;  // Importing necessary namespace

public class Exercise53  // Declaration of the Exercise53 class
{  
    public static void Main()  // Main method, entry point of the program
    {       
        int n1, n, p = 1;  // Declaration of variables
        int dec = 0, i = 1, j, d;
        int ocno = 0;
		
        Console.Write("\n\n");
        Console.Write("Convert binary number into octal:\n");
        Console.Write("-----------------------------------");
        Console.Write("\n\n");		

        Console.Write("Input a binary number :");
        n = Convert.ToInt32(Console.ReadLine());  // Taking user input for a binary number	
        n1 = n;  // Storing the original binary number for display at the end

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

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

        // Converting the decimal equivalent to its octal representation
        i = 1;
        for (j = dec; j > 0; j = j / 8)
        {
            ocno = ocno + (j % 8) * i;
            i = i * 10;
            n = n / 8;
        }

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

Sample Output:

Convert binary number into octal:                                                                           
-----------------------------------                                                                            
Input a binary number :110101                                                                                  
The Binary Number : 110101                                                                                  
The equivalent Octal  Number : 65 

Flowchart:

Flowchart: Convert binary number into octal

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to find the Sum of GP series.
Next: Write a program in C# Sharp to convert an octal number into binary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.