Coming Soon

This lesson is currently being developed

Remainder and Exponentiation

Understand modulo operations and power calculations.

Operators
Chapter
Beginner
Difficulty
30min
Estimated Time

What to Expect

Comprehensive explanations with practical examples

Interactive coding exercises to practice concepts

Knowledge quiz to test your understanding

Step-by-step guidance for beginners

Development Status

In Progress

Content is being carefully crafted to provide the best learning experience

Preview

Early Preview Content

This content is still being developed and may change before publication.

6.3 — Remainder and Exponentiation

In this lesson, you'll learn about the remainder (modulo) operator for finding the remainder of division operations, explore practical applications, and discover how to perform exponentiation (power operations) in C++.

The remainder operator (%)

The remainder operator (%), also called the modulo operator, returns the remainder left over after integer division. It only works with integer types, not floating-point numbers.

Think of it this way: when you divide 10 by 3, you get 3 with a remainder of 1. The remainder operator gives you that leftover part.

Basic remainder operations

#include <iostream>

int main()
{
    // Basic remainder examples
    int a = 10;
    int b = 3;
    int remainder = a % b;      // 10 ÷ 3 = 3 remainder 1
    
    std::cout << a << " % " << b << " = " << remainder << std::endl;
    
    // More examples
    std::cout << "Division and remainder examples:" << std::endl;
    std::cout << "10 / 3 = " << (10 / 3) << ", remainder = " << (10 % 3) << std::endl;
    std::cout << "17 / 5 = " << (17 / 5) << ", remainder = " << (17 % 5) << std::endl;
    std::cout << "20 / 4 = " << (20 / 4) << ", remainder = " << (20 % 4) << std::endl;
    std::cout << "7 / 7 = " << (7 / 7) << ", remainder = " << (7 % 7) << std::endl;
    
    return 0;
}

Output:

10 % 3 = 1
Division and remainder examples:
10 / 3 = 3, remainder = 1
17 / 5 = 3, remainder = 2
20 / 4 = 5, remainder = 0
7 / 7 = 1, remainder = 0

Remainder with different values

#include <iostream>

int main()
{
    // When remainder is zero - divisible numbers
    std::cout << "Divisible numbers (remainder 0):" << std::endl;
    std::cout << "12 % 4 = " << (12 % 4) << std::endl;    // 0
    std::cout << "15 % 5 = " << (15 % 5) << std::endl;    // 0
    std::cout << "100 % 10 = " << (100 % 10) << std::endl; // 0
    
    // When remainder is not zero
    std::cout << "\nNumbers with remainders:" << std::endl;
    std::cout << "13 % 4 = " << (13 % 4) << std::endl;    // 1
    std::cout << "16 % 5 = " << (16 % 5) << std::endl;    // 1
    std::cout << "23 % 7 = " << (23 % 7) << std::endl;    // 2
    
    // Remainder with small divisors
    std::cout << "\nRemainder patterns with small divisors:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        std::cout << i << " % 3 = " << (i % 3) << std::endl;
    }
    
    return 0;
}

Output:

Divisible numbers (remainder 0):
12 % 4 = 0
15 % 5 = 0
100 % 10 = 0

Numbers with remainders:
13 % 4 = 1
16 % 5 = 1
23 % 7 = 2

Remainder patterns with small divisors:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
7 % 3 = 1
8 % 3 = 2
9 % 3 = 0

Remainder with negative numbers

The remainder operator with negative numbers can be tricky. The result depends on the sign of the dividend (first operand):

Negative number remainder behavior

#include <iostream>

int main()
{
    // Positive dividend
    std::cout << "Positive dividend:" << std::endl;
    std::cout << "10 % 3 = " << (10 % 3) << std::endl;   // 1
    std::cout << "10 % -3 = " << (10 % -3) << std::endl; // 1
    
    // Negative dividend  
    std::cout << "\nNegative dividend:" << std::endl;
    std::cout << "-10 % 3 = " << (-10 % 3) << std::endl;   // -1
    std::cout << "-10 % -3 = " << (-10 % -3) << std::endl; // -1
    
    // Rule: result has same sign as dividend (first operand)
    std::cout << "\nMore examples:" << std::endl;
    std::cout << "17 % 5 = " << (17 % 5) << std::endl;    // 2
    std::cout << "-17 % 5 = " << (-17 % 5) << std::endl;  // -2
    std::cout << "17 % -5 = " << (17 % -5) << std::endl;  // 2
    std::cout << "-17 % -5 = " << (-17 % -5) << std::endl; // -2
    
    return 0;
}

Output:

Positive dividend:
10 % 3 = 1
10 % -3 = 1

Negative dividend:
-10 % 3 = -1
-10 % -3 = -1

More examples:
17 % 5 = 2
-17 % 5 = -2
17 % -5 = 2
-17 % -5 = -2

Common uses of the remainder operator

1. Checking if numbers are even or odd

#include <iostream>

int main()
{
    // Function to check if number is even
    auto isEven = [](int number) -> bool {
        return (number % 2) == 0;
    };
    
    // Test numbers
    for (int i = 1; i <= 10; ++i) {
        std::cout << i << " is " << (isEven(i) ? "even" : "odd") << std::endl;
    }
    
    // Using remainder to separate even and odd
    std::cout << "\nProcessing even and odd numbers separately:" << std::endl;
    for (int i = 1; i <= 10; ++i) {
        if (i % 2 == 0) {
            std::cout << i << " (even): doubled = " << (i * 2) << std::endl;
        } else {
            std::cout << i << " (odd): squared = " << (i * i) << std::endl;
        }
    }
    
    return 0;
}

Output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even

Processing even and odd numbers separately:
1 (odd): squared = 1
2 (even): doubled = 4
3 (odd): squared = 9
4 (even): doubled = 8
5 (odd): squared = 25
6 (even): doubled = 12
7 (odd): squared = 49
8 (even): doubled = 16
9 (odd): squared = 81
10 (even): doubled = 20

2. Circular array indexing

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::string> colors = {"red", "green", "blue", "yellow", "purple"};
    int arraySize = colors.size();
    
    std::cout << "Circular array access using remainder operator:" << std::endl;
    
    // Access elements in circular fashion
    for (int i = 0; i < 15; ++i) {
        int index = i % arraySize;  // Keeps index within bounds
        std::cout << "Index " << i << " -> colors[" << index << "] = " 
                  << colors[index] << std::endl;
    }
    
    return 0;
}

Output:

Circular array access using remainder operator:
Index 0 -> colors[0] = red
Index 1 -> colors[1] = green
Index 2 -> colors[2] = blue
Index 3 -> colors[3] = yellow
Index 4 -> colors[4] = purple
Index 5 -> colors[0] = red
Index 6 -> colors[1] = green
Index 7 -> colors[2] = blue
Index 8 -> colors[3] = yellow
Index 9 -> colors[4] = purple
Index 10 -> colors[0] = red
Index 11 -> colors[1] = green
Index 12 -> colors[2] = blue
Index 13 -> colors[3] = yellow
Index 14 -> colors[4] = purple

3. Converting time units

#include <iostream>

int main()
{
    int totalSeconds = 3725;  // Some number of seconds
    
    // Convert to hours, minutes, and seconds
    int hours = totalSeconds / 3600;           // 3600 seconds per hour
    int remainingSeconds = totalSeconds % 3600; // Remaining after hours
    int minutes = remainingSeconds / 60;       // 60 seconds per minute
    int seconds = remainingSeconds % 60;       // Final remaining seconds
    
    std::cout << totalSeconds << " seconds equals:" << std::endl;
    std::cout << hours << " hours, " << minutes << " minutes, " 
              << seconds << " seconds" << std::endl;
              
    // Alternative one-liner approach
    std::cout << "\nAlternative calculation:" << std::endl;
    std::cout << (totalSeconds / 3600) << ":" 
              << ((totalSeconds % 3600) / 60) << ":" 
              << (totalSeconds % 60) << std::endl;
              
    // More examples
    std::cout << "\nMore time conversions:" << std::endl;
    int times[] = {90, 3661, 7265, 86400};
    for (int time : times) {
        int h = time / 3600;
        int m = (time % 3600) / 60;
        int s = time % 60;
        std::cout << time << " seconds = " << h << "h " << m << "m " << s << "s" << std::endl;
    }
    
    return 0;
}

Output:

3725 seconds equals:
1 hours, 2 minutes, 5 seconds

Alternative calculation:
1:2:5

More time conversions:
90 seconds = 0h 1m 30s
3661 seconds = 1h 1m 1s
7265 seconds = 2h 1m 5s
86400 seconds = 24h 0m 0s

4. Finding multiples and divisibility

#include <iostream>

int main()
{
    // Check if numbers are multiples of 3
    std::cout << "Multiples of 3 from 1 to 20:" << std::endl;
    for (int i = 1; i <= 20; ++i) {
        if (i % 3 == 0) {
            std::cout << i << " ";
        }
    }
    std::cout << std::endl;
    
    // Check divisibility by multiple numbers
    int testNumber = 60;
    std::cout << "\nDivisibility test for " << testNumber << ":" << std::endl;
    int divisors[] = {2, 3, 4, 5, 6, 10, 12, 15, 20};
    
    for (int divisor : divisors) {
        if (testNumber % divisor == 0) {
            std::cout << testNumber << " is divisible by " << divisor 
                      << " (quotient: " << (testNumber / divisor) << ")" << std::endl;
        }
    }
    
    return 0;
}

Output:

Multiples of 3 from 1 to 20:
3 6 9 12 15 18 

Divisibility test for 60:
60 is divisible by 2 (quotient: 30)
60 is divisible by 3 (quotient: 20)
60 is divisible by 4 (quotient: 15)
60 is divisible by 5 (quotient: 12)
60 is divisible by 6 (quotient: 10)
60 is divisible by 10 (quotient: 6)
60 is divisible by 12 (quotient: 5)
60 is divisible by 15 (quotient: 4)
60 is divisible by 20 (quotient: 3)

Exponentiation in C++

C++ doesn't have a built-in exponentiation operator (like ** in Python). Instead, you use the pow() function from <cmath> or implement your own:

Using the pow() function

#include <iostream>
#include <cmath>

int main()
{
    // Basic exponentiation using pow()
    double result1 = pow(2, 3);        // 2^3 = 8
    double result2 = pow(5, 2);        // 5^2 = 25
    double result3 = pow(3, 4);        // 3^4 = 81
    double result4 = pow(2, 0.5);      // 2^0.5 = sqrt(2) ≈ 1.414
    
    std::cout << "2^3 = " << result1 << std::endl;
    std::cout << "5^2 = " << result2 << std::endl;
    std::cout << "3^4 = " << result3 << std::endl;
    std::cout << "2^0.5 = " << result4 << std::endl;
    
    // Fractional and negative exponents
    double result5 = pow(8, 1.0/3.0);  // Cube root of 8
    double result6 = pow(2, -2);       // 2^-2 = 1/4
    double result7 = pow(16, 0.25);    // Fourth root of 16
    
    std::cout << "\nFractional and negative exponents:" << std::endl;
    std::cout << "8^(1/3) = " << result5 << std::endl;
    std::cout << "2^(-2) = " << result6 << std::endl;
    std::cout << "16^0.25 = " << result7 << std::endl;
    
    return 0;
}

Output:

2^3 = 8
5^2 = 25
3^4 = 81
2^0.5 = 1.41421

Fractional and negative exponents:
8^(1/3) = 2
2^(-2) = 0.25
16^0.25 = 2

Implementing integer exponentiation

For integer exponents, you can implement your own efficient function:

#include <iostream>

// Simple iterative exponentiation
long long power(int base, int exponent)
{
    if (exponent < 0) {
        throw std::invalid_argument("Negative exponents not supported for integer result");
    }
    
    long long result = 1;
    for (int i = 0; i < exponent; ++i) {
        result *= base;
    }
    return result;
}

// Optimized exponentiation using binary method
long long fastPower(long long base, int exponent)
{
    if (exponent < 0) {
        throw std::invalid_argument("Negative exponents not supported");
    }
    if (exponent == 0) {
        return 1;
    }
    
    long long result = 1;
    while (exponent > 0) {
        // If exponent is odd, multiply result by current base
        if (exponent % 2 == 1) {
            result *= base;
        }
        // Square the base and halve the exponent
        base *= base;
        exponent /= 2;
    }
    return result;
}

int main()
{
    // Test simple exponentiation
    std::cout << "Simple exponentiation:" << std::endl;
    std::cout << "2^8 = " << power(2, 8) << std::endl;
    std::cout << "3^5 = " << power(3, 5) << std::endl;
    std::cout << "5^3 = " << power(5, 3) << std::endl;
    
    // Test fast exponentiation
    std::cout << "\nFast exponentiation:" << std::endl;
    std::cout << "2^10 = " << fastPower(2, 10) << std::endl;
    std::cout << "3^7 = " << fastPower(3, 7) << std::endl;
    std::cout << "2^20 = " << fastPower(2, 20) << std::endl;
    
    // Compare performance for large exponents
    std::cout << "\nLarge exponents:" << std::endl;
    std::cout << "2^30 = " << fastPower(2, 30) << std::endl;
    std::cout << "3^15 = " << fastPower(3, 15) << std::endl;
    
    return 0;
}

Output:

Simple exponentiation:
2^8 = 256
3^5 = 243
5^3 = 125

Fast exponentiation:
2^10 = 1024
3^7 = 2187
2^20 = 1048576

Large exponents:
2^30 = 1073741824
3^15 = 14348907

Mathematical calculations with exponents

#include <iostream>
#include <cmath>
#include <iomanip>

int main()
{
    // Compound interest: A = P(1 + r)^t
    double principal = 1000.0;     // $1000 initial
    double rate = 0.05;            // 5% annual interest
    int years = 10;
    
    double finalAmount = principal * pow(1 + rate, years);
    double interest = finalAmount - principal;
    
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "Compound Interest Calculation:" << std::endl;
    std::cout << "Principal: $" << principal << std::endl;
    std::cout << "Rate: " << (rate * 100) << "% per year" << std::endl;
    std::cout << "Time: " << years << " years" << std::endl;
    std::cout << "Final amount: $" << finalAmount << std::endl;
    std::cout << "Interest earned: $" << interest << std::endl;
    
    // Surface area and volume calculations
    double radius = 5.0;
    double pi = 3.14159;
    
    double circleArea = pi * pow(radius, 2);
    double sphereVolume = (4.0 / 3.0) * pi * pow(radius, 3);
    double sphereSurface = 4 * pi * pow(radius, 2);
    
    std::cout << "\nGeometry calculations (radius = " << radius << "):" << std::endl;
    std::cout << "Circle area: " << circleArea << std::endl;
    std::cout << "Sphere volume: " << sphereVolume << std::endl;
    std::cout << "Sphere surface area: " << sphereSurface << std::endl;
    
    return 0;
}

Output:

Compound Interest Calculation:
Principal: $1000.00
Rate: 5.00% per year
Time: 10 years
Final amount: $1628.89
Interest earned: $628.89

Geometry calculations (radius = 5):
Circle area: 78.54
Sphere volume: 523.60
Sphere surface area: 314.16

Common mistakes and best practices

1. Don't use remainder with floating-point numbers

#include <iostream>

int main()
{
    // ❌ This won't compile - remainder doesn't work with floating-point
    // double result = 5.5 % 2.0;  // Compiler error!
    
    // ✅ For floating-point remainder, use fmod() from <cmath>
    #include <cmath>
    double result = std::fmod(5.5, 2.0);  // 1.5
    std::cout << "5.5 fmod 2.0 = " << result << std::endl;
    
    return 0;
}

2. Be careful with negative numbers and remainder

#include <iostream>

int main()
{
    // Remember: result has same sign as dividend (first number)
    std::cout << "7 % 3 = " << (7 % 3) << std::endl;     // 1
    std::cout << "-7 % 3 = " << (-7 % 3) << std::endl;   // -1
    
    // For always-positive remainder, add divisor if result is negative
    auto positiveRemainder = [](int dividend, int divisor) {
        int result = dividend % divisor;
        return (result < 0) ? result + divisor : result;
    };
    
    std::cout << "Positive remainder of -7 % 3 = " << positiveRemainder(-7, 3) << std::endl; // 2
    
    return 0;
}

3. Check for division by zero with remainder

#include <iostream>

int main()
{
    int dividend = 10;
    int divisor = 0;
    
    // ❌ This would cause undefined behavior
    // int result = dividend % divisor;  
    
    // ✅ Always check for zero divisor
    if (divisor != 0) {
        int result = dividend % divisor;
        std::cout << "Remainder: " << result << std::endl;
    } else {
        std::cout << "Error: Division by zero!" << std::endl;
    }
    
    return 0;
}

Summary

The remainder operator and exponentiation are useful tools for various programming tasks:

Remainder operator (%):

  • Returns the remainder after integer division
  • Only works with integer types
  • Result has the same sign as the dividend (first operand)
  • Common uses: even/odd checking, circular indexing, time conversion, divisibility testing

Exponentiation:

  • No built-in operator in C++ (unlike some languages)
  • Use pow() from <cmath> for general exponentiation
  • Implement your own for integer-only exponentiation
  • Essential for mathematical calculations, compound interest, geometry

Key practices:

  • Always check for division/remainder by zero
  • Remember remainder only works with integers (use fmod() for floating-point)
  • Be aware of sign behavior with negative numbers
  • Choose the appropriate method for exponentiation based on your needs

These operators expand your ability to perform mathematical calculations and implement algorithms that require modular arithmetic or exponential operations.

Quiz

  1. What is the result of 17 % 5? a) 3 b) 2 c) 4 d) 12

  2. What is the result of -17 % 5? a) -2 b) 2 c) 3 d) -3

  3. Which function should you use for floating-point remainder operations? a) % operator b) fmod() c) pow() d) remainder()

  4. What does pow(2, 3) return? a) 6 b) 8 c) 9 d) 5

  5. How would you check if a number n is even? a) n % 2 == 1 b) n % 2 == 0 c) n / 2 == 0 d) n * 2 == 0

Practice exercises

Try these exercises to master remainder and exponentiation:

  1. Prime Number Checker: Write a program that uses the remainder operator to check if a number is prime.

  2. Digital Clock Display: Create a program that converts seconds to hours:minutes:seconds format using remainder operations.

  3. Power Calculator: Implement both iterative and optimized exponentiation functions and compare their performance.

  4. Modular Arithmetic: Build a calculator that performs operations in modular arithmetic (useful for cryptography basics).

Continue Learning

Explore other available lessons while this one is being prepared.

View Course

Explore More Courses

Discover other available courses while this lesson is being prepared.

Browse Courses

Lesson Discussion

Share your thoughts and questions

💬

No comments yet. Be the first to share your thoughts!

Sign in to join the discussion