Posts Tagged ‘program’

Simple Calculator

April 25th, 2009

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