C program to convert Decimal to Octal number system

Write a C program to input decimal number from user and convert decimal to octal number system. How to convert from decimal number system to octal number system in C.

Example:
Input decimal number: (22)10
Output octal number: (26)8

Required knowledge:

Basic C programming, For loop

Decimal number system:

Decimal number system is a base 10 number system. Decimal number system uses 10 symbols to represent all numbers i.e. 0 1 2 3 4 5 6 7 8 9.

Octal number system:

Octal number system is a base 8 number system. Octal number system uses 8 symbols to represent all numbers i.e. 0 1 2 3 4 5 6 7

Algorithm to convert Decimal to Octal:

Algorithm Decimal to Octal conversion
    begin:
        read(DECIMAL);
        OCTAL ← 0; PLACE ← 1; REM ← 0;
        While (DECIMAL !=0) do
            begin:
                REMDECIMAL % 8;
                OCTAL ← (REM * PLACE) + OCTAL;
                PLACEPLACE * 10;
                DECIMALDECIMAL / 8;
            end;
        print('Octal number' OCTAL);
    end;


Program:

/**
 * C program to convert from Decimal to Octal number system
 */

#include <stdio.h>

int main()
{
    long long decimal, tempDecimal, octal;
    int i, rem, digit = 1;

    octal = 0;

    /*
     * Reads decimal number from user
     */
    printf("Enter any decimal number: ");
    scanf("%lld", &decimal);
    tempDecimal = decimal;

    /*
     * Converts the decimal number to octal number
     */
    while(tempDecimal!=0)
    {
        rem = tempDecimal % 8;

        octal = (rem * digit) + octal;

        tempDecimal /= 8;
        digit *= 10;
    }

    printf("\nDecimal number = %lld\n", decimal);
    printf("Octal number = %lld", octal);

    return 0;
} 


Output
Enter any decimal number: 20

Decimal number = 20
Octal number = 24

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment