Find Quotient and Remainder in C++
Quotient and remainder in C++ using / and %. 7/2 is 3.
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}
Output
Enter dividend: 25 Enter divisor: 4 Quotient: 6 Remainder: 1
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.