Prevent a division by zero using the ? operator : Ternary Operator : Operator C# Examples


C# Examples » Operator » Ternary Operator »

 

Prevent a division by zero using the ? operator









    
using  System;  
  
class  Example  {  
    public  static  void  Main()  {  
        int  result;  
  
        for(int  i  =  -5;  i  <  6;  i++)  {  
            result  =  i  !=  0  ?  100  /  i  :  0;  
            if(i  !=  0)    
                Console.WriteLine("100  /  "  +  i  +  "  is  "  +  result);  
        }  
    }  
}
    
   
  
   



Output

100 / -5 is -20
100 / -4 is -25
100 / -3 is -33
100 / -2 is -50
100 / -1 is -100
100 / 1 is 100
100 / 2 is 50
100 / 3 is 33
100 / 4 is 25
100 / 5 is 20


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Operator
» Ternary Operator