Convert Decimal to Octal in C

In this source code example, we will write a code to convert the decimal number to an octal number in the C programming language.

Convert Decimal to Octal in C

In this C program, we will take input from the User or console and print the result to the output: 

#include <stdio.h>
void decimal2Octal(long decimalnum);

int main()
{
    long decimalnum;

    printf("Enter the decimal number: ");
    scanf("%ld", &decimalnum);

    decimal2Octal(decimalnum);

    return 0;
}

void decimal2Octal(long decimalnum)
{
    long remainder, quotient;

    int octalNumber[100], i = 1, j;
    quotient = decimalnum;

    while (quotient != 0)
    {
        octalNumber[i++] = quotient % 8;

        quotient = quotient / 8;
    }

    for (j = i - 1; j > 0; j--) printf("%d", octalNumber[j]);

    printf("\n");
}

Output:

Enter the decimal number: 25
31

Demo


Comments