Find Quotient and Remainder in C++
Find the quotient and remainder of two integers in C++ with / and %. Learn integer division, how negatives round toward zero, and why dividing by zero crashes.
1#include <iostream>2using namespace std;34int main() {5 int dividend, divisor;67 cout << "Enter dividend: ";8 cin >> dividend;910 cout << "Enter divisor: ";11 cin >> divisor;1213 // Method 1: Using division and modulus operators14 int quotient = dividend / divisor;15 int remainder = dividend % divisor;1617 cout << "Quotient: " << quotient << endl;18 cout << "Remainder: " << remainder << endl;1920 return 0;21}
Sample Output
Quotient: 6
25 / 4 without the fraction.
Remainder: 1
25 − 6 × 4.
In this one
- How integer / drops the fractional part
- How % gives the leftover after division
- The check quotient × divisor + remainder = dividend
- Why dividing by zero must be prevented
How it works
- 1
Read dividend (25) and divisor (4).
- 2
quotient = 25 / 4 = 6, because both are int.
- 3
remainder = 25 % 4 = 1.
- 4
Print both values.
Edge cases
Divisor is zero
Enter 0 for the divisor.
Integer division by zero is undefined behavior; on most systems the program crashes with a floating point exception. Check if (divisor == 0) before dividing.
Negative dividend
Enter -7 and 2.
C++ rounds toward zero, so the quotient is -3 and the remainder is -1. Check: -3 × 2 + (-1) = -7.
What's going on
This C++ program prints the quotient and remainder of integer division: dividend / divisor and dividend % divisor.
int dividend, divisor;
Dividend is the number being split. Divisor is how many pieces. Sample: 25 and 4.
int quotient = dividend / divisor;
Integer division. 25 / 4 is 6, not 6.25. The fraction is discarded toward zero for positive values. 7 / 2 is 3.
int remainder = dividend % divisor;
25 % 4 is 1. That's what's left after 4 goes into 25 six times.
Check: 6 * 4 + 1 == 25. For positives, quotient * divisor + remainder equals dividend. If it doesn't, you used float division somewhere.
divisor == 0 crashes (or raises a hardware exception) unless you check first. This program does not check. Don't type 0.
Negatives: C++11 truncates toward zero, so -7 / 2 is -3 and -7 % 2 is -1. Older compilers were messy. Stick to positives until that's a homework requirement.
Same idea as splitting 3665 seconds into hours and leftover seconds: divide, keep the remainder, repeat.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is 17 % 5?
Pick an answer to check it.
Question 2
What is -9 / 4 in C++11 and later?
Pick an answer to check it.
Questions people ask
Can % be used with double?
No. % works only on integer types. For doubles, use fmod from <cmath>.
How do I get the decimal result?
Cast one side: (double)dividend / divisor gives 6.25.
Where is % useful?
Even/odd checks, digit extraction (n % 10), and wrapping around, like converting seconds to minutes.