Advertisement
cortez

Find Greatest Without Using "If-else"

Oct 19th, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.85 KB | None | 0 0
  1. using System;
  2.  
  3. class greaterOfTwo
  4. {
  5.     static void Main(string[] args)
  6.     {
  7.         Console.WriteLine("Please enter the first number:");
  8.         int a;
  9.         int.TryParse(Console.ReadLine(), out a);
  10.         Console.WriteLine("Please enter the second number:");
  11.         int b;
  12.         int.TryParse(Console.ReadLine(), out b);
  13.  
  14.         int c = a - b;// We calculate the difference of the to numbers.
  15.         int k = (c >> 31) & 1;// Using the bitwise operator to move the senior bit to the first position and then we & it with 1(which first bit is also 1) to make k 1 or 0;
  16.         int max = a - k * c;// here if a < b, k is 1 --> a - 1 * c = a - c(but c = a - b, remember?), so a - (a - b) = b!!! Then we give that value to MAX.
  17.  
  18.         Console.WriteLine("The greatest of " + a + " and " + b + " is: " + max);// And in the end we print MAX
  19.     }
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement