DEV Community

Sana Khan
Sana Khan

Posted on

✨Fixing Integer Overflow in C++ with Circular Indexing

🌀 I Didn't Know Circular Indexing — Here's What Went Wrong (and How I Fixed It)

When I first saw a simple problem — “Find the sum of every 4 consecutive elements in an array of 5 elements, wrapping around circularly” — I thought, "Easy!"

So I wrote my usual loops, added the elements, and printed the results.

It worked… until it didn’t.

That’s when I learned about circular indexing, and even more importantly, integer overflow. Here's how it all unfolded.


🧪 The Problem

Given 5 integers, I needed to calculate 5 sums. Each sum should include 4 consecutive elements from the array, but with wrapping.

For example, given:

The sums should be:

  • 1+2+3+4 = 10
  • 2+3+4+5 = 14
  • 3+4+5+1 = 13 ← wrapped
  • 4+5+1+2 = 12 ← wrapped
  • 5+1+2+3 = 11 ← wrapped

🔨 My First (Flawed) Approach

I began writing the logic like this:

int sum1 = a[0] + a[1] + a[2] + a[3];
int sum2 = a[1] + a[2] + a[3] + a[4];
int sum3 = a[2] + a[3] + a[4] + a[5]; // 🚨 Oops!

That last line? Totally wrong  a[5] doesnt even exist!
I was trying to access indices beyond the array.


Enter fullscreen mode Exit fullscreen mode

🧭 Discovery: Circular Indexing

After some searching and trial & error, I discovered modulo indexing.
Using % (modulo operator), I could wrap around to index 0 when I go beyond 4.

for (int i = 0; i < 5; i++) {
    for (int j = i; j < i + 4; j++) {
        sum[i] += a[j % 5];  // this wraps around the array
    }
}
Enter fullscreen mode Exit fullscreen mode

🚧 The Next Bug: It Still Broke for Big Inputs

📛 Integer Overflow — I was using int, which can only store up to ~2.1 billion.
So I changed everything to long long.

✅ The Final Code (Bug-Free and Clean)

#include <iostream>
using namespace std;

int main() {
    long long a[5];
    for (int i = 0; i < 5; i++) cin >> a[i];

    long long sum[5] = {0};

    for (int i = 0; i < 5; i++) {
        for (int j = i; j < i + 4; j++) {
            sum[i] += a[j % 5];  // circular indexing
        }
    }

    for (int i = 0; i < 5; i++) {
        cout << sum[i] << endl;
    }

    long long max = sum[0], min = sum[0];
    for (int i = 0; i < 5; i++) {
        if (sum[i] > max) max = sum[i];
        if (sum[i] < min) min = sum[i];
    }

    cout << min << " " << max;
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)