C Program To Convert Decimal Number To Octal Number, using While Loop


Lets write a C program to convert a number from Decimal number system(base 10) to Octal number system(base 8), using while loop.

Number Systems

number systems

1. Binary Number System uses base 2 and digits 01.
2. Octal Number System uses base 8 and digits 01234567.
3. Decimal Number System uses base 10 and digits 0123456789.
4. Hexadecimal Number System uses base 16 and digits 0123456789ABCDEF.

Related Read:
while loop in C programming
Calculate Sum of Digits: C Program
C Program To Reverse a Number

Note: Octal number system can be derived by base 8 to the power of whole numbers.

Example:
etc .. 84, 83, 82, 81, 80

etc .. 84 = ‭4,096‬, 83 = 512, 82 = 64, 81 = 8, 80 = 1.

octal number system

Expected Output for the Input

User Input:
Enter a decimal number
20

Output:
Octal equivalent of 20 is 24.

Explanation:
If user enters num = 20

We keep on dividing the number 20 by 8.

20 / 8 = 2, reminder 4.
02 / 8 = 0, reminder 2.

Decimal to binary

So Octal equivalent of decimal number 20 is 24.

OR

(83 x 0) + (82 x 0) + (81 x 2) + (80 x 4 )
= 0 + 0 + (8 x 2) + (1 x 4)
= 16 + 4
= 20

Video Tutorial: C Program To Convert Decimal Number To Octal Number, using While Loop


[youtube https://www.youtube.com/watch?v=zd_rO67U-Gw]

YouTube Link: https://www.youtube.com/watch?v=zd_rO67U-Gw [Watch the Video In Full Screen.]

Logic To Convert Decimal Number To Octal Number, using While Loop

In this C program we ask the user to enter / input a decimal number. Using while loop we calculate the reminder and add it to previous value of variable oct. We make use of variable place to position the reminder based on number system – unit, ten, hundred, thousand, ten thousand etc.

Source Code: C Program To Convert Decimal Number To Octal Number, using While Loop

#include < stdio.h >

int main()
{
    int num, oct = 0, rem = 0, place = 1;

    printf("Enter a decimal number\n");
    scanf("%d", &num);

    printf("\nOctal Equivalent of %d is ", num);
    while(num)
    {
        rem = num % 8;
        oct = oct + rem * place;
        num = num / 8;
        place = place * 10;
    }
    printf("%d\n", oct);

    return 0;
}

Output 1:
Enter a decimal number
16

Octal Equivalent of 16 is 20

Output 2:
Enter a decimal number
41

Octal Equivalent of 41 is 51

Output 3:
Enter a decimal number
90

Octal Equivalent of 90 is 132

Output 4:
Enter a decimal number
14

Octal Equivalent of 14 is 16

Output 5:
Enter a decimal number
32

Octal Equivalent of 32 is 40

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *