×

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of 10 to a number with a base value of 8. The number of digits used to represent a numeric value is determined by the base value of a number system.

Example of a program to convert decimal to octal in C++:

// C++ program to convert a decimal
// number to octal number
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ; 
// function to convert decimal to octal
void decimalToOctal ( int n )
{
	// array to store octal number
	int octalNumber [ 100 ] ; 
	// counter for octal number array
	int i = 0 ;
	while ( n != 0 ) {
		// storing remainder in octal array
		octalNumber [ i ] = n % 8 ;
		n = n / 8 ;
		i++ ;
	}
	// printing octal number array in reverse order
	for ( int j = i - 1 ; j >= 0 ; j-- )
		cout << octalNumber [ j ] ;
}
// Driver Code
int main ( )
{
	int n = 16 ; 
	// Function Call
	decimalToOctal ( n ) ; 
	return 0;
}

OUTPUT:

20
…..
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

  • When 16 is divided by 8, the remainder is 0. As a result, arr [ 0 ] = 0.
  • 16 divided by 8 equals 16 / 8 = 2 is the new number.
  • When 2 is divided by 8, the remainder is 2. As a result, arr [ 1 ] = 2.
  • 2 divided by 8, 2 / 8 = 0 is the new number.
  • Since the number is equal to zero,
  • Stop repeating the steps and print the array backwards. As a result, the octal number equivalent is 20.
  • Time Complexity will be 0 ( logn ).

Let us see another example of a code with 0 ( 1 ) space complexity in C++:

Let us see another example of a code with 0 ( 1 ) space complexity in C++:
// C++ program to convert decimal
// number to octal number
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ; 
// function to calculate the octal value of the given
// decimal number
void decimaltoOctal ( int decimalNumber )
{
	// initializations
	int octalNumber = 0 , countvalue = 1 ;
	int dNo = decimalNumber ;
	while ( decimalNumber != 0 ) {
		// decimals remainder is calculated
		int remainder = decimalNumber % 8 ; 
		// storing the octalvalue
		octalNumber += remainder * countval ; 
		// storing exponential value
		countvalue = countvalue * 10 ;
		decimalNumber /= 8 ;
	}
	cout << octalNumber << endl ;
}
// Driver Code
int main ( )
{
	int n = 16 ; 
	// Function Call
	decimaltoOctal ( n ) ;
	return 0 ;
}

OUTPUT:

20
….
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

  • Set the octal num to 0 and the countValue to 1, as well as the decimal number to n.
  • When a decimal number is divided by 8, get the remaining.
  • Updating by octalNumber + (remainder * countvalue)
  • Countvalue should be multiplied by countvalue * 10.
  • 8 times a decimal number
  • Continue from step 2 until the decimal number reaches zero.

Let us look at another example of a program in C++ using pre defined function:

#include < bits/stdc++.h >
#include < iostream >
#include < stdlib >
using namespace std ; 
string intToOctalnum ( int n )
{
	stringstream st ;
	st << octn << n ;
	return st.str ( ) ;
}
int main ( )
{
	int n = 16 ;
	cout << intToOctalnum ( n ) ;
	return 0 ;
}

OUTPUT:

20
….
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

In the above program, we have made a string function and named it as intToOctalnum and passing the decimal number as the parameter and in the main function we are making a call to function intToOctalnum.

Another example of pre defined function without using string:

#include <iostream>
using namespace std; 
long decimalToOctalnum ( long n );
int main ( ) {
    long decimalnum ;
    cout << "enter a decimal number\n";
    cin >> decimalnum;
    cout << "Octal number : " << decimalToOctalnum ( decimalnum ) ; 
    return 0;
}
long decimalToOctalnum ( long n ) {
    int remainder ; 
    long octal = 0 , i = 1 ;
   
    while ( n != 0 ) {
        remainder = n % 8 ;
        n = n / 8 ;
        octal = octal + (remainder*i);
        i = i*10;
    }
    return octal;
}

OUTPUT:

Enter a decimal number 16
Octal number: 20
………………………………………
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

In the C++ program above, we accept an integer from the user and store it in the variable decimalnum. Then, using the above-mentioned procedure, we call the decimalToOctalnum function to convert the decimal function to an octal number.


Related Topics

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Size_t Data Type in C++

In C++, the type to express the object size in bytes is defined as Size_t, an unsigned integer type offered by the standard library for describing the object's size and...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that...

4 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Bitwise Operator vs Logical Operator

Bitwise Operator  Bitwise operators perform operations bit by bit on bits.The value is converted to abinary during operations like addition, subtraction, division, and so on. These operations are carried out at the...

3 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.