Q8 Write a program to receive an integer and find its octal equivalent. Hint: To obtain octal equivalent of an integer, divide it continuously by 8 till dividend doesn’t become zero, then write the remainders obtained in reverse direction.

Write a program to receive an integer and find its octal equivalent. Hint: To obtain octal equivalent of an integer, divide it continuously by 8 till dividend doesn't become zero, then write the remainders obtained in reverse direction.

Program: 101

Write a c program to receive an integer and find its octal equivalent.

Hint: To obtain octal equivalent of an integer, divide it continuously by 8 till dividend doesn’t become zero, then write the remainders obtained in reverse direction.

#include<stdio.h>
#include<conio.h>
int main()
{
    int num, r, res=0, oct=0, flag=0;

    printf("Enter an integer: ");
    scanf("%d", &num);
    r = num;

    //get the remainder
    while(r!=0)
    {
        res = res*10 + r%8;

        //check for zero at first position
        if(res == 0)
        {
            flag=1;
        }

        r = r/8;
    }

    //reverse the number
    while(res!=0)
    {
        oct = oct*10 + res%10;
        res = res/10;
    }

    //if first position contain zero then multiply the number with 10
    if (flag == 1)
    {
        oct = oct*10;
    }

    printf("The octal of %d is %d.",num, oct);

}

Output:

Enter an integer: 200
The octal of 200 is 310.

Lokesh Kumar: Being EASTER SCIENCE's founder, Lokesh Kumar wants to share his knowledge and ideas. His motive is "We assist you to choose the best", He believes in different thinking.

View Comments (1)

  • Share solution was quite helpful but, there are is the case that it doesn't cover if we receive two consecutive zero as a reminder, which will lead to a produce wrong vice versa conversation.

    Eg: Input - 1792
    ouput - 340(where as expected output is 3400)

    Below is a small change in same code done to get the desire output

    #include <stdio.h>

    int main()
    {
    int num, r, res=0, oct=0, flag=0,x=1;

    printf("Enter an integer: ");
    scanf("%d", &num);
    r = num;

    //get the remainder
    while(r!=0)
    {
    res = res*10 + r%8;

    //check for zero at first position
    if(res == 0)
    {
    x=x*10;
    }

    r = r/8;
    }

    //reverse the number
    while(res!=0)
    {
    oct = oct*10 + res%10;
    res = res/10;
    }

    oct = oct*x;

    printf("The octal of %d is %d.",num, oct);
    return 0;

    }

Related Post
Leave a Comment

This website uses cookies.