C# Remainder operator

In this chapter you will learn:

  1. Use % operator to get remainder
  2. Example for C# Remainder operator
  3. How to use remainder operator to determine smallest single-digit factor

Description

In C# we can use % operator to get remainder.

Example

Example for C# Remainder operator


using System; /* w  w w . ja v a  2s .  c  o  m*/
 
class Example {    
  public static void Main() {    
    int iresult, irem; 
    double dresult, drem; 
 
    iresult = 10 / 3; 
    irem = 10 % 3; 
 
    dresult = 10.0 / 3.0; 
    drem = 10.0 % 3.0;  
 
    Console.WriteLine("Result and remainder of 10 / 3: " + 
                       iresult + " " + irem); 
    Console.WriteLine("Result and remainder of 10.0 / 3.0: " + 
                       dresult + " " + drem); 
  }    
}

The code above generates the following result.

Determine smallest single-digit factor

How to use remainder operator to determine smallest single-digit factor


 //from w ww  . j  a va2  s. co m
using System; 
 
class  MainClass {    
  public static void Main() {    
    int num; 
 
    for(num = 2; num < 12; num++) { 
      if((num % 2) == 0) 
        Console.WriteLine("Smallest factor of " + num + " is 2.");  
      else if((num % 3) == 0)  
        Console.WriteLine("Smallest factor of " + num + " is 3.");  
      else if((num % 5) == 0) 
        Console.WriteLine("Smallest factor of " + num + " is 5.");  
      else if((num % 7) == 0)  
        Console.WriteLine("Smallest factor of " + num + " is 7.");  
      else  
        Console.WriteLine(num + " is not divisible by 2, 3, 5, or 7.");  
    } 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Relational operators
  2. Example for Relational operators
  3. Combine relational operators and logic operators
Home »
  C# Tutorial »
    C# Language »
      C# Operators
C# Arithmetic Operators
C# Arithmetic Assignment Operator
C# Increment and Decrement Operators
C# Remainder operator
C# Relational operators
C# Conditional Operators
C# Ternary operator(The ? Operator)
C# Bitwise Operators
C# Bitwise Shift Operators
C# sizeof Operator
C# typeof Operator