The best way to learn something is to teach it. I will try to do that here. The question is:

I want to ensure that a division of integers is always rounded up if necessary. Is there a better way than this? There is a lot of casting going on. :-)

(int)Math.Ceiling((double)myInt1 / myInt2)

Eric Lippert, an excellent writer and a developer at Microsoft

Getting integer arithmetic correct is hard. As has been demonstrated amply thus far, the moment you try to do a "clever" trick, odds are good that you’ve made a mistake. And when a flaw is found, changing the code to fix the flaw without considering whether the fix breaks something else is not a good problem-solving technique. So far we’ve had I think five different incorrect integer arithmetic solutions to this completely not-particularly-difficult problem posted.

The right way to approach integer arithmetic problems — that is, the way that increases the likelihood of getting the answer right the first time – is to approach the problem carefully, solve it one step at a time, and use good engineering principles in doing so.

Start by reading the specification for what you’re trying to replace. The specification for integer division clearly states:

The division rounds the result towards zero

The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs

If the left operand is the smallest representable int and the right operand is –1, an overflow occurs. […] it is implementation-defined as to whether [an ArithmeticException] is thrown or the overflow goes unreported with the resulting value being that of the left operand.

If the value of the right operand is zero, a System.DivideByZeroException is thrown.

What we want is an integer division function which computes the quotient but rounds the result always upwards, not always towards zero.

So write a specification for that function. Our function int DivRoundUp(int dividend, int divisor) must have behaviour defined for every possible input. That undefined behaviour is deeply worrying, so let’s eliminate it. We’ll say that our operation has this specification:

operation throws if divisor is zero

operation throws if dividend is int.minval and divisor is -1

if there is no remainder — division is ‘even’ — then the return value is the integral quotient

Otherwise it returns the smallest integer that is greater than the quotient, that is, it always rounds up.

Now we have a specification, so we know we can come up with a testable design. Suppose we add an additional design criterion that the problem be solved solely with integer arithmetic, rather than computing the quotient as a double, since the "double" solution has been explicitly rejected in the problem statement.

So what must we compute? Clearly, to meet our spec while remaining solely in integer arithmetic, we need to know three facts. First, what was the integer quotient? Second, was the division free of remainder? And third, if not, was the integer quotient computed by rounding up or down?

Now that we have a specification and a design, we can start writing code.

publicstaticint DivRoundUp(int dividend, int divisor)
{
if (divisor == 0 ) throw ...
if (divisor == -1 &amp;&amp; dividend == Int32.MinValue) throw ...
int roundedTowardsZeroQuotient = dividend / divisor;
bool dividedEvenly = (dividend % divisor) == 0;
if (dividedEvenly)
return roundedTowardsZeroQuotient;
// At this point we know that divisor was not zero // (because we would have thrown) and we know that // dividend was not zero (because there would have been no remainder)// Therefore both are non-zero. Either they are of the same sign, // or opposite signs. If they're of opposite sign then we rounded // UP towards zero so we're done. If they're of the same sign then // we rounded DOWN towards zero, so we need to add one.bool wasRoundedDown = ((divisor &gt; 0) == (dividend &gt; 0));
if (wasRoundedDown)
return roundedTowardsZeroQuotient + 1;
elsereturn roundedTowardsZeroQuotient;
}

Is this clever? No. Beautiful? No. Short? No. Correct according to the specification? I believe so, but I have not fully tested it. It looks pretty good though.

We’re professionals here; use good engineering practices. Research your tools, specify the desired behaviour, consider error cases first, and write the code to emphasize its obvious correctness.And when you find a bug, consider whether your algorithm is deeply flawed to begin with before you just randomly start swapping the directions of comparisons around and break stuff that already works.

So typical. A hello world App. Except my assignment was to create two text fields, a label, and a button.

The two text fields allow a user to type in their first name and last name. The label will display the concatenated full name after the user presses the button. Lets do this.

Coming from C++ and C#, I was confident of my programming prowess. I was unfortunately unprepared for the beast that is Xcode. Coming from the full featured Visual Studios and its rival, Eclipse, I was a culture shock to move to Xcode.

Next go into Interface builder. To get there, doubleclick your MainWindow.xib file in Xcode.

A Window should show up similar to this.

Start Dragging over the following:

Two Text Fields

One Label

One Rectangle

Edit the Attributes (Property Window for the rest of us)

Now change the Attributes of the elements you dragged over. If you don’t see the Attribute Window on the left, then just go to the Menu and click Tools then Attribute Inspector.

For the Text Fields:

Text - Make sure their Text Properties are cleared.

Placeholder field - You can place some helpful text like “First name” into the Placeholder property. The Placeholder property will be some faded text inside the text field that will give the user a visual cue of what to type into the Text field.

Return Key - Set it to Done. The user will see a “Done” key instead of a “Return” key

For the Label:

Text – Change the Text to something like “I will show your full name here!”

For the Round Rec Button

Text – Change the Text to something like “Say my name! Say my name!”

Connecting your instance variable to the objects in the Interface builder.

Remember the above code in the header file? Let’s look at it a bit more carefully.

IBOutlet UILabel *lblShowFullName; // Label to Show your Full Name

Unlike Visual Studios, you have to predefine the variables here in the code. The IBOutlet is technically a pointer to an GUI element. This allows the program to interact with it. It works the same way in Visual Studios, but Microsoft hid all the code or generated it for you.

-(IBAction)showFullName:(id)sender;

This is an method of type IBAction which takes an incoming parameter of sender which is type id. Now, type id is just a generic object. Sender will be the GUI element that sent the message (event for the rest of us). It is type IBAction so that the Interface Builder can find the cursed variable.

To create the connections, select the Round Rec Button and look at your Attribute Window. You should see a list of events. The one you want to look for is Touch Up Inside. Hold down Ctrl and drag a line from the Round Rec Button to the FileOwner. Your action showFullName should show up. Click it to create the connection.

You don’t need to hook up the other elements, since they aren’t sending events.

Implement your method

Now open up the implementation file (.m).

We are going to make the label display the full name by concatenating the strings.

Now the last part is an else statement. If either firstName or lastName has a length greater than zero(0), then we print their full name. The computer will fill in %@ with an arguement. Since we have two, separated by a space, we get the firstName followed by a space, followed by the lastName.

Now hit build. Weeeeeee

WAIT!!!!! MY KEYBOARD BLOCKS MY WHOLE SCREEN.

What we didn’t do was tell the TextFields what to do when the user hits “Done.”

To get rid of the keyboard after the user hits “Done”, we need to go back into Interface Builder. Hold Ctrl and Left-Click on each Text Field and drag them over to File’s Owner. Assign them to their appropriate delegates (txtFirstName, txtLastName).

Next we need to go into our implementation file (.m) and add in the following code:

Response: wait… fast? Hadn’t he been battling cancer since, what, 2004? fast implies you don’t have a long drawn out illness than kills you very slowly over 7 years…

True. But you know, he worked day to day up until the day he stepped down. I’d say that while, not fast as instantaneous. It was fast in the sense he went full throttle. It would come as no surprise if he was working 70 hour weeks up til the day he stepped down. We are all going to die sooner or later. So the cancer is a moot point. We might as well die doing what we love for 70 hours a week.

It makes me wonder though. Everyday, I feel I’m the only person that feels this way. Because of my live fast, die fast attitude, I wonder and ask everyone:

"Will our generation ever live up to the same measure?"

Last generation created Bill Gates and Steve Jobs. Darpa and the Internet. Military hardware like the Nimitz class aircraft carrier along with Top Gun’s F-14, a plane that has never been shot down in air combat. An Air Force that has never allowed an American force to come under air attack for over 50 years, well over half the time power flight has even existed.

The generation before that were hippies. But they walked on the Moon.

Before that generation, they stormed the sandy beaches of Normandy and fought the Battle of the Bulge.

Before that, over a million Europeans fought for family and country in the battle of Somme. A half a million young men on each side laid down their lives, not for money, not for retirement, but for a cause.

Crazy huh? People giving their lives for something you can’t touch. Our generation so far has pumped out Facebook and social media.

Seriously, we better cure cancer or something. Otherwise Nature will have no choice but to wipe us from the history books.