Prevent a division by zero using the ? operator : Ternary Operator « Operator « C# / CSharp Tutorial






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); 
    } 
  } 
}
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








3.8.Ternary Operator
3.8.1.The ? Operator
3.8.2.The ternary operator
3.8.3.Use ternary operator in Console.WriteLine function
3.8.4.Prevent a division by zero using the ? operator
3.8.5.Simplest Data type cast operator