What does modulus do in this line?

Viewed 52

I just need to understand why does minutes%60 works. this code is supposed to get minutes input and tell you how many days,hours,minutes can fit into it (there are 1440 minutes in a day).

     using System;

 public class Time
 {
     public static void Main()
     {
         int minutes = int.Parse(Console.ReadLine());
         int days = (minutes/1440);
         int hours = (minutes%1440)/60;
         Console.WriteLine("days: " + days + " hours: " + hours + " minutes: " + minutes%60);

     }
 }
2 Answers

% is the modulo operator:

In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).

minutes % 60

You can think of this as repeatedly removing 60 from minutes until a total of less than 60 is left. When the snippet is evaluated it will remove all extra minutes leaving a total of less than 1 hour (60 minutes) of remaining minutes.

Think of y = minutes%1440 this way

int x = (minutes/1440);
int y = minutes - 1440*x

The value of y holds the remainder of the division minutes/1440

Related