2 Replies - 498 Views - Last Post: 03 August 2010 - 11:50 AM Rate Topic: -----

#1 suganya.cbe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-August 10

c program

Posted 03 August 2010 - 08:10 AM

how to write a c program to find the greatest of 2 or 3 numbers without using if conditions?
Is This A Good Question/Topic? 0
  • +

Replies To: c program

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10807
  • View blog
  • Posts: 40,282
  • Joined: 27-December 08

Re: c program

Posted 03 August 2010 - 08:12 AM

You could use ternary operators, which are essentially shorthand if statements. So for example: int max = (a>b)?a:b;. So if a > b, then assign max a, otherwise assign max b.
Was This Post Helpful? 1
  • +
  • -

#3 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 308
  • View blog
  • Posts: 1,508
  • Joined: 16-May 09

Re: c program

Posted 03 August 2010 - 11:50 AM

Another way is using lookup tables. The key note here is that false has a value of 0 and true has a value other than 0(here 1). So, you create an array of the two numbers and put the condition inside it:
int larger(const int& num1, const int& num2) {
   int table[] = {num1, num2}; //num1 is at index 0, num2 is at index 1
   return table[num1<num2]; //if num1<num2 is true, then it is equal to 1, and num2 is returned, else, num1 is returned
}

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1