Obj-C: How to do basic math

MathTestMath has not been one of my strong points – even with the computer helping me throughout the years.  So, when I had to learn how to format a math problem using languages such as Objective-C, I was not a happy camper.

But formulating a math problem for the computer to see, figure out, and spit the answer out is easier then I thought it would be, especially for a math dunce like myself.

This article will cover the basics of how to give the computer a problem so it can give you a result.

For those of you who are using Xcode, this will be a simple program that will output the result to a NSLOG and print the answer to the console and everything will be done in the .m file.  Create a new single screen application and name it MATHTEST or something like that.

Here is the entire code.  I’ll explain what’s going on after….

    int x = 15;

    int y = 23;

    int answer = 0;

    answer = (x + y);

    NSLog(@”%d”,answer);

 Okay, let’s run down what’s going on here:

1.  We initialize the “X” variable to hold the number “15”.
2.  We initialize the “Y” variable to hold the number “23”.
3.  We initialize the “answer” variable with the value of “0”  *
4.  Let the value of answer add the
 and values (in this case, X = 15 and Y = 23).
5.  Now print the value of answer to the console (which should be 38).

That’s it….Happy coding.

2 Responses to Obj-C: How to do basic math

  1. Pingback: Obj-C: How to spell out Numbers as Text | The Programming Assistant

  2. Pingback: Obj-C: How to do basic math (Part II) | The Programming Assistant

Leave a comment