Bird
0
0
DSA Cprogramming~3 mins

Why Modular Arithmetic Basics in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could make numbers loop perfectly like a clock without any mistakes?

The Scenario

Imagine you are trying to keep track of hours on a clock. When the hour hand passes 12, it starts again at 1. If you try to count hours by just adding numbers without resetting, you will get confusing results.

The Problem

Manually resetting numbers after reaching a limit is slow and error-prone. You might forget to reset, or do it inconsistently, leading to wrong answers and confusion.

The Solution

Modular arithmetic automatically wraps numbers around a fixed limit. It works like a clock, so after reaching the limit, it starts back at zero. This keeps calculations simple and correct.

Before vs After
Before
int hour = 0;
hour = hour + 5;
if (hour > 12) hour = hour - 12;
After
int hour = 0;
hour = (hour + 5) % 12;
if (hour == 0) hour = 12;
What It Enables

It allows easy handling of repeating cycles and keeps numbers within a fixed range automatically.

Real Life Example

Calculating the day of the week after adding days to a current day, where the week repeats every 7 days.

Key Takeaways

Modular arithmetic wraps numbers around a fixed limit.

It prevents errors from manual resetting.

It simplifies calculations involving cycles like clocks or calendars.