To convert a number from the decimal system to the octal system in C++ programming language, the following code example can be used.
#include <iostream>
using namespace std;
int main() {
int num, remainder, oct = 0, i = 1;
cout << "Please enter a number: ";
cin >> num;
while (num != 0) {
remainder = num % 8;
num = num / 8;
oct = oct + (remainder * i);
i = i * 10;
}
cout << "Octal number : " << oct << endl;
return 0;
}
Please enter a number: 44
Octal number : 54
This code converts a given decimal number to its octal equivalent. Here is a step-by-step explanation:
cout << "Please enter a number: ";
cin >> num;
while
loop, which runs until the num
becomes 0. In each iteration of the loop, the remainder when num
is divided by 8 is calculated and stored in the remainder
variable. The value of num
is then updated to be num
divided by 8. The value of oct
is then updated as oct = oct + (remainder * i)
, where i
is initially 1 and is multiplied by 10 in each iteration. This effectively adds the new remainder to the right side of the existing value of oct
.oct
is the octal equivalent of the input decimal number. This value is displayed on the console using the following line of code:cout << "Octal number : " << oct << endl;