C# program to accept two integers and return the remainder

The remainder operation in C# finds the leftover value after dividing one integer by another. The modulus operator (%) is used to calculate the remainder when the first number is divided by the second number.

Syntax

Following is the syntax for calculating remainder using the modulus operator −

int remainder = dividend % divisor;

Where dividend is the number being divided and divisor is the number by which we divide.

Using Basic Modulus Operation

The simplest way to find the remainder is using the modulus operator directly −

using System;

class Program {
   static void Main(string[] args) {
      int one = 250;
      int two = 200;
      
      Console.WriteLine("Number One: " + one);
      Console.WriteLine("Number Two: " + two);
      
      int remainder = one % two;
      Console.WriteLine("Remainder: " + remainder);
   }
}

The output of the above code is −

Number One: 250
Number Two: 200
Remainder: 50

Using a Method with Error Handling

For more robust code, you can create a method that handles edge cases like division by zero −

using System;

class Demo {
   public int RemainderFunc(int val1, int val2) {
      if (val2 == 0)
         throw new Exception("Second number cannot be zero! Cannot divide by zero!");
      return (val1 % val2);
   }
   
   static void Main(string[] args) {
      int one = 250;
      int two = 200;
      int remainder;
      
      Console.WriteLine("Number One: " + one);
      Console.WriteLine("Number Two: " + two);
      
      Demo d = new Demo();
      remainder = d.RemainderFunc(one, two);
      Console.WriteLine("Remainder: {0}", remainder);
   }
}

The output of the above code is −

Number One: 250
Number Two: 200
Remainder: 50

Handling Different Scenarios

The remainder operation works with different combinations of positive and negative numbers −

using System;

class Program {
   static void Main(string[] args) {
      // Different scenarios
      Console.WriteLine("17 % 5 = " + (17 % 5));
      Console.WriteLine("7 % 3 = " + (7 % 3));
      Console.WriteLine("10 % 4 = " + (10 % 4));
      Console.WriteLine("15 % 15 = " + (15 % 15));
      Console.WriteLine("5 % 10 = " + (5 % 10));
   }
}

The output of the above code is −

17 % 5 = 2
7 % 3 = 1
10 % 4 = 2
15 % 15 = 0
5 % 10 = 5

Common Use Cases

  • Checking even/odd numbers: number % 2 == 0 for even numbers

  • Circular array indexing: index % arrayLength to wrap around

  • Time calculations: Converting seconds to hours, minutes format

  • Hash table implementations: key % tableSize for bucket selection

Conclusion

The modulus operator (%) in C# provides an easy way to find the remainder of integer division. It's essential to handle division by zero scenarios when creating methods that accept user input or dynamic values.

Updated on: 2026-03-17T07:04:35+05:30

740 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements