
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Division Without Using Operator in C++
In this tutorial, we are going to learn how to divide a number without using the division (/) operator.
We have given two numbers, the program should return the quotient of the division operation.
We are going to use the subtraction (-) operator for the division.
Let's see the steps to solve the problem.
Initialize the dividend and divisor.
If the number is zero, then return 0.
Store whether the result will be negative or not by checking the signs of dividend and divisor.
Initialize a count to 0.
-
Write a loop that runs until the number one is greater than or equals to the number two.
Subtract the number two from the number one and assign the result to the number one
Increment the counter.
Print the counter.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; int division(int num_one, int num_two) { if (num_one == 0) { return 0; } if (num_two == 0) { return INT_MAX; } bool negative_result = false; if (num_one < 0) { num_one = -num_one ; if (num_two < 0) { num_two = -num_two ; } else { negative_result = true; } } else if (num_two < 0) { num_two = -num_two; negative_result = true; } int quotient = 0; while (num_one >= num_two) { num_one = num_one - num_two; quotient++; } if (negative_result) { quotient = -quotient; } return quotient; } int main() { int num_one = 24, num_two = 5; cout << division(num_one, num_two) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
4
Conclusion
If you have any queries in the tutorial, mention them in the comment section.