Simple Calculator

April 25th, 2009 by Chris Leave a reply »

You can already build a Hello World application (I hope so). Now, let’s try to build something more interesting with more user functionality.

Start Xcode, create new project Window-Based Application, name it Calculator, create a View Controller, name it Calc, create a view name it Calculator.

You have to create one object, few variables and methods in Calc.h file:

#import <UIKit/UIKit.h>
@interface Calc : UIViewController {
	float result;
	IBOutlet UILabel *calculatorScreen;
	int currentOperation;
	float currentNumber;
}
-(IBAction)buttonDigitPressed:(id)sender;
-(IBAction)buttonOperationPressed:(id)sender;
-(IBAction)cancelInput;
-(IBAction)cancelOperation;
@end
  • result of type float is a number in memory – result of the last operation
  • calculatorScreen of type UILabel shows the result of the operation or a number user is entering
  • currentOperation of type int is and ID of operation (1 – addition, 2 – subtraction, 3 – multiplication, 4 – division, 0 – equals)
  • currentNumber of type float is the number user is entering for every next operation (displayed on calculatorScreen)
  • buttonDigitPressed:(id)sender method is called whenever user press one of 0-9 buttons, as you see I use only one method for all of ten buttons. Of course I could implement ten methods like: -(IBAction)button6Pressed, but I will show you how to detect, which button called the method using (id)sender
  • buttonOperationPressed:(id)sender the same as above, one method for 5 operations: addition, subtraction, multiplicationdivision and equals
  • cancelInput and cancelOperation when user presses “C” or “AC”

Now open Calculator.xib and drag’n'drop 17 buttons and one label and do with them the same what I did below:

calculatorview

Remember to resize the Label so the bigger numbers fit there without difficulties. Open the Inspector, click on each 0-9 buttons and in Button Attributes set 0, 1, 2, 3, 4… as a Tag [Tag = 5 for 5 Button, Tag = 7 for 7 Button]… Do the same with operation buttons: Tag = 1 for addition, 2 for subtraction, 3 for multiplication, 4 for division, 0 for equals but as zero is a default tag you don’t have to enter it manually.

tagbutton1

tagbuttonx

Now, select File’s Owner from Calculator.xib and Object Identity enter Calc as Class. Now in Calc Connections connect in the same way you did in Hello Worldview to the view, calculatorScreen to the label. And now connect actions to the buttons. Connect buttonDigitPressed: to the 0 Button’s Touch up inside. Although now this method is called by 0 Button, you can connect more buttons to it. Press again on the circle next to buttonDigitPressed: and connect it to 1 Button this time. If it worked, connect it to the next 2-9 Buttons. Do the same with buttonOperationPressed: and connect it with equals, addition, subtraction, multiplication, division, later connect cancelInput with “C”, and cancelOperation with “AC”.

calcconnections

That’s all you have to do in Interface Builder. Save Calculator.xib and go back to Xcode.

You have to put these standard lines of code in CalculatorAppDelegate.h/.m files:

#import "Calc.h"

@class Calc;
	Calc *viewController = [[Calc alloc] initWithNibName:@"Calculator" bundle:[NSBundle mainBundle]];
	[window addSubview:[viewController view]];

just like in Hello World example (did you read it?).

If you press Build and Go you should see your project in iPhone Simulator, but it won’t do any calculations because you provided so far only methods names in the header of class Calc (in Calc.h file). Now you have to implement them in Calc.m.

-(IBAction)buttonDigitPressed:(id)sender

-(IBAction)buttonDigitPressed:(id)sender {
	currentNumber = currentNumber*10 + (float)[sender tag];
	calculatorScreen.text = [NSString stringWithFormat:@"%.2f",currentNumber];
}

Each time above method is called the currentNumber value is changed. [sender tag] is giving you the number you entered as a tag of each of 0-9 buttons. Below is the example how currentNumber looks like after pressing digits:

  1. 0 (original value)
  2. user presses “5″: 0*10 + 5 = 5
  3. user presses “9″: 5*10 + 9 = 59
  4. user presses 2: 59*10 + 2 = 592

calculatorScreen text is also changed showing the user the number he is entering right now. If you can’t figure out what this line exactly do, go here: http://www.cplusplus.com/reference/clibrary/cstdio/printf/ .

-(IBaction)buttonOperationPressed:(id)sender

-(IBAction)buttonOperationPressed:(id)sender {
	if (currentOperation == 0) result = currentNumber;
	else {
		switch (currentOperation) {
			case 1:
				result = result + currentNumber;
				break;
			case 2:
				result = result - currentNumber;
				break;
			case 3:
				result = result * currentNumber;
				break;
			case 4:
				result = result / currentNumber;
				break;
			case 5:
				break;
		}
	}
	currentNumber = 0;
	calculatorScreen.text = [NSString stringWithFormat:@"%.2f",result];
	currentOperation = [sender tag];
}

When the application runs each int value is set to zero so when the user press any operation button the current number displayed on “screen” is treated as the result and the ID of operation is saved to currentOperation. Every next time currentOperation remembers the pressed operation button and perform expected operation. Below is example how above method works:

  1. user enters 123 and presses the addition
  2. user enters 354 and presses the subtraction
  3. 123+354 = 477
  4. users enters 10 and press equals
  5. 477 – 10 = 467

-(IBAction)cancelInput & -(IBAction)cancelOperation

-(IBAction)cancelInput {
	currentNumber = 0;
	calculatorScreen.text = @"0.00";
}

-(IBAction)cancelOperation {
	currentNumber = 0;
	calculatorScreen.text = @"0.00";
	currentOperation = 0;
}

Above two methods look almost the same. Both of them set zero as currentNumber, changes the screen text so it shows 0.00. The only difference is that cancelOperation set also zero as currentOperation – just like user would reopen the application or hit the equals.

You can Build and Go to see your application running, your calculator should work now. It’s only a simple example, division by zero is accepted, you can’t enter fractions, but I hope you learn something from me today.

calculatorsimulator

And again one small thing. Memory management. In fact it’s a big thing. In dealloc method add [calculatorScreen release];. You have to release only objects you, or Interface Builder allocated for you, so the calculatorScreen needs to be released. You don’t have to worry about variables – ints, floats, booleans

xcodeproj

Download the project

Advertisement

24 comments

  1. Tomoko Cargill says:

    I do believe all the ideas you have introduced on your post. They are really convincing and can certainly work. Still, the posts are very quick for starters. Could you please lengthen them a bit from next time? Thank you for the post.Riester Rente recently posted..1

  2. Nick says:

    I simply had to appreciate you all over again. I am not sure the things that I might have sorted out without those opinions revealed by you directly on my situation. Completely was the intimidating dilemma in my circumstances, however , noticing your expert fashion you treated it took me to weep over gladness. I am thankful for your assistance as well as have high hopes you recognize what a great job you are accomplishing instructing others with the aid of your blog post. Most likely you haven’t come across any of us. http://www.handbagsdreams.com dsa

  3. Andrew says:

    In response to others who get garbage values after 10 or so digits are pressed, this is due to the fact that you are using float for currentNumber. Simply use long long instead of float. This will fix that problem.

    Header file:
    long long currentNumber;

    Implementation:
    calculatorScreen.text = [NSString stringWithFormat:@"%.2lld",currentNumber];

    • bensge says:

      hey guys! i tried to change the float to a long long, but now the calculator is completely not working… Any help?
      And why is the calculator not abled to handle point numbers?

  4. Jup R. says:

    Thank you SO much for this clear, simple calculator. What I would like to do is have my custom calculator slide up when a user taps in the text box on the app. I’d love to know how to disable xcode’s standard keypad and slide this in instead. Can you make a suggestion? Thanks again for the great tutorial!

  5. AK says:

    thanks, you really helped me :D

  6. In the end, that of a terrific web site along with enlightening discussions, I’ll post inward bound weblink ?§C take a note of this site? Respect, Visitor.

  7. Doug Uoy says:

    Anytime an individual reports the problem in front of you, i’ve got to agree with your closings. An individual not surprisingly clearly show is vital this kind of make a difference and that i have much to get after looking at your own posting.Considerably salutations and i will come back for just about any additionally improvements.

  8. T-Discs says:

    Appreciating the time and effort you put into your blog and in depth information you present. It’s awesome to come across a blog every once in a while that isn’t the same old rehashed material. Wonderful read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  9. In which have you find this theme?

  10. Banners says:

    cozen’t wait pending construe the series! me is continually unearthly up to gamble on more long since agency designer fair trade can come through confounding.

  11. lex says:

    change Float to Double

  12. Thanks for providing such a learning stuff!!
    Nice tutorial

  13. Mithun says:

    Hello, ive tried this calculator but theres an error, if i press any digit button without stopping i get junk values…
    if u know what is wrong plz let me no

    thanx

    • Dani A says:

      sry for the late reply but i’ve just read your comment.
      Well, this calculator will definitely have errors since it is adding float numbers.
      To make it simple, the TAG is an integer, let’s say “1″, when u use (float)[sender tag] u are casting or converting this 1 to a float number.
      The compiler simply converts it to 1.000***** where the stars represents different numbers not necessarily 0.

      This is a simple calculator with no exceptions handling.

  14. I’m behind you every step of the way. You have a legal entitlement to your own ideas, and you should never let anybody tell you anything different. Good on you!

  15. Faqt says:

    What if user push “dot”? ;-)
    A! Do not push dot, dot not present ;-)

    I now working with “dot”, next I change calc mode to my favorite RPN.

    Thank’s for great tutorials!

  16. mel says:

    I am just wondering why when you enter the ninth number, it’s adding value even you didn’t press any operation.

  17. Nasser says:

    mannnnnnnnn was it that simple?!!, ive been looking through tons of docs only to figure out how to do just that.
    thanks

Leave a Reply