Program to Convert Decimal to Octal
- Write a program to Convert Decimal to Octal in C
- Write a program to Convert Decimal to Octal in C++
- Write a program to Convert Decimal to Octal in Python
- Write a program to Convert Decimal to Octal in PHP
- Write a program to Convert Decimal to Octal in Java
- Write a program to Convert Decimal to Octal in Java Script
- Write a program to Convert Decimal to Octal in C#
Explanation:
A decimal number (base 10) is converted to its octal equivalent (base 8) using the following logic: repeatedly divide the number by 8 and note the remainders. The octal digits in reverse order are represented by these remainders.
Steps for Decimal to Octal Conversion:
- Start with the decimal number.
- For example: n = 83
- Divide the number by 8.
- Record the remainder (it will be between 0 and 7). This remainder is an octal digit.
- Update the number as the quotient of the division.
- Repeat the division process until the quotient becomes 0.
- The octal number is the sequence of remainders read in reverse order.
Example Conversion:
Convert 83 to octal:
- 83 ÷ 8 = 10 remainder 3 → Octal digit: 3
- 10 ÷ 8 = 1 remainder 2 → Octal digit: 2
- 1 ÷ 8 = 0 remainder 1 → Octal digit: 1
Octal equivalent (reversed remainders): 123
Program to Convert Decimal to Octal
-
C
-
C++
-
Python
-
PHP
-
JAVA
-
Java Script
-
C#
#include <stdio.h> void decimalToOctal(int n) { int octalNum[32]; int i = 0; while (n > 0) { octalNum[i] = n % 8; n = n / 8; i++; } for (int j = i - 1; j >= 0; j--) printf("%d", octalNum[j]); } int main() { int n; printf("Enter a decimal number: "); scanf("%d", &n); printf("Octal: "); decimalToOctal(n); return 0; }
#include <iostream> using namespace std; void decimalToOctal(int n) { string octal = ""; while (n > 0) { octal = to_string(n % 8) + octal; n /= 8; } cout << octal; } int main() { int n; cout << "Enter a decimal number: "; cin >> n; cout << "Octal: "; decimalToOctal(n); return 0; }
def decimal_to_octal(n): return oct(n).replace("0o", "") n = int(input("Enter a decimal number: ")) print("Octal:", decimal_to_octal(n))
<?php function decimalToOctal($n) { echo decoct($n); } $n = (int)readline("Enter a decimal number: "); echo "Octal: "; decimalToOctal($n); ?>
import java.util.Scanner; public class DecimalToOctal { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a decimal number: "); int n = sc.nextInt(); System.out.println("Octal: " + Integer.toOctalString(n)); } }
function decimalToOctal(n) { return n.toString(8); } const n = parseInt(prompt("Enter a decimal number: ")); console.log("Octal:", decimalToOctal(n));
using System; class DecimalToOctal { static void Main() { Console.Write("Enter a decimal number: "); int n = int.Parse(Console.ReadLine()); Console.WriteLine("Octal: " + Convert.ToString(n, 8)); } }