Paul wrote:

Trying to write a function that does the following:

Joe gets 100 points for every 30 widgets he sells.

So if he sells less than thirty he gets nothing. If he gets between 30 and

59 he gets 100, 60-89 he gets 200, 90-119 he gets 300 etc.....

How can I display the points joe gets depending on then number of widgets

entered.

Many people solving this problem or similar problems use a cascade

set of "if" statements:

unsigned int widgets_sold;

unsigned int points_earned;

//...

if (widgets_sold < 30)

{

points_earned = 0;

}

if ((widgets_sold >= 30) && (widgets_sold < 60))

{

points_earned = 100;

}

// Und so weite.

A switch statement is not an efficient approach since the case

statement requires an integral constant and doesn't handle

ranges. All the values within the ranges would have to be

listed with cases:

switch (widgets_sold)

{

case 0:

case 1:

// ...

case 29:

points_earned = 0;

break;

// Und so weite.

}

Another, maybe more proper method, is to use a range, value

table. The table contains records of

<range start, range end, value>

struct Range_Record

{

unsigned int start;

unsigned int end;

unsigned int points;

};

Then create the table:

const Range_Record Price_Table[] =

{

// start end points

{ 0, 29, 0},

{ 30, 59, 100},

{ 60, 89, 200},

// Und so weite.

};

const unsigned int NUM_PRICE_RECORDS =

sizeof (Price_Table) / sizeof (Price_Table[0]);

The above methods are usually applied when there is no

mathematical expression to the data and the range

of values is finite.

The big advantage to using the table, is that you can

add entries without having to retest the code that

searches the table. In many situations, modifying

executable code causes many problems and much regression

testing.

Just showing alternatives.

--

Thomas Matthews

C++ newsgroup welcome message:

http://www.slack.net/~shiva/welcome.txt
C++ Faq:

http://www.parashift.com/c++-faq-lite
C Faq:

http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:

http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:

http://www.josuttis.com -- C++ STL Library book