C# program to accept two integers and return the remainder


Firstly, set the two numbers.

int one = 250;
int two = 200;

Now pass those numbers to the following function.

public int RemainderFunc(int val1, int val2) {
   if (val2 == 0)
   throw new Exception("Second number cannot be zero! Cannot divide by zero!");
   if (val1 < val2)
   throw new Exception("Number cannot be less than the divisor!");
   else
   return (val1 % val2);
}

Above we have checked for two conditions i.e.

  • If the second number is zero, an exception occurs.
  • If the first number is less than the second number, an exception occurs.

To return remainder of two numbers, the following is the complete code.

Example

 Live Demo

using System;
namespace Program {
   class Demo {
      public int RemainderFunc(int val1, int val2) {
         if (val2 == 0)
         throw new Exception("Second number cannot be zero! Cannot divide by zero!");
         if (val1 < val2)
         throw new Exception("Number cannot be less than the divisor!");
         else
         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 );
         Console.ReadLine();
      }
   }
}

Output

Number One: 250
Number Two: 200
Remainder: 50

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 23-Jun-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements