C Program to Convert Decimal to Octal

C Program to Convert Decimal to Octal

Write C Program to Convert Decimal to Octal

// Write C Program to Convert Decimal to Octal

#include <stdio.h>
#include <math.h>

int main()
{
	int n ;
	long ans = 0;

	printf("Enter the Decimal number :--> ");
	scanf("%d", &n);

	printf("The Octal Number is :--> %o", n);   //Easiest approach to find the octal number from the decimal

	int i = 0;
	while(n != 0)
	{
		int digit = n % 8;  //here we take the last digit

			ans = (digit * pow(10,i)) + ans;	  //formula for the conversion

			n = n / 8;	// reducing the number
		i++;
	}
	printf("\nThe Octal Number is :--> %d", ans);
    return 0;
}

Output:

Enter the Decimal number :--> 56
The Octal Number is :--> 70
The Octal Number is :--> 70