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.
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.
Output:
Enter an integer: 200 The octal of 200 is 310.
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;
}