Monday 30 March 2009

Chapter 4 - Data Types and Expressions

Comment

Another valuable operation of Objective-C I have found so far is the 'Type Cast Operator'. This operator converts the value of a variable to a different variable type for evaluation. This method can also be used to turn a generic object into an object of a particular class which seems like it could be a very valuable operation.


However, I am unsure as to the exact purpose of the 'Bitwise Operators'. The book did not make it clear as to their purpose in aiding programming.


I think I made a mess of most of this, plus there is quite a lot to read. So I apologize for not having this posted nice and early for you to read through.


Questions 8, 9 and 10 involve modifying the same Program which I will bring on a memory stick for you to see as I have had some troubles with it. As a result, the included evidence for these questions on here may not make much sense


Exercises


1. Which of the following are invalid constants. Why?

Valid:

123.456 - a float


2. Write a program that converts 27 degrees from degrees Fahrenheit (F) to degrees Celsius (C) using the following formula:

C = (F - 32) / 1.8


ANS - Copy and Paste of program and console below


#import


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


int F = 27;

float C;

NSLog(@"The value of 27F in Degrees C is: %f", C = (F - 32) / 1.8);

[pool drain];

return 0;

}


[Session started at 2009-03-30 00:38:30 +0100.]

2009-03-30 00:38:30.549 Chap4_Ex2_tempConverter[632:10b] The value of 27F in Degrees C is: -2.777778


The Debugger has exited with status 0.


3. What output would you expect from the following program?

#import


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

char c, d;

c = 'd';

d = c;

NSLog(@"d = %c", d);

[pool drain];

return 0;

}


ANS - Expected Output: d = d


4. Write a program to evaluate the polynomial shown here:

3x^3 - 5x^2 + 6

for x = 2.55


ANS - Copy and Paste of Program and Console below.


#import


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


float x1 = 2.55, x2 = 2.55; //This isn't right since it equates to 2.55x10^3 instead of 2.55^3

float ans;

x1 *= x1 * x1;

x2 *= x2;

ans = 3 * x1 - 5 * x2 + 6;

NSLog(@"For x equal to 2.55 the answer is: %f", ans);

[pool drain];

return 0;

}


[Session started at 2009-03-30 02:46:36 +0100.]

2009-03-30 02:46:36.787 Chap4_Ex4_polynomial[1264:10b] For x equal to 2.55 the answer is: 23.231621


The Debugger has exited with status 0.


5. Write a program that evaluates the following expression and displays the results (remember to use the exponential format to display the result):

(3.31 x 10^-8 x 2.01 x 10^-7) / (7.16 x 10^-6 + 2.01 x 10^-8)


ANS - I couldn't get this to work correctly, I am unsure as to why however. Copy and Paste of program and console below.


#import


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


long double expression;

expression = 1 + (3.31e-8 * 2.01e-7) / (7.16e-6 + 2.01e-8);

NSLog(@"Result of expression is: %f", expression);

[pool drain];

return 0;

}


The Debugger has exited with status 0.

[Session started at 2009-03-30 01:20:21 +0100.]

2009-03-30 01:20:21.294 Chap4_Ex5_Expo[899:10b] Result of expression is: -0.000000


The Debugger has exited with status 0.


6. Complex numbers are numbers that contain two components: a real part and an imaginary part. If a is the real component and b is the imaginary component, this is the notation used to represent the number:

a + b i

Write an Objective-C program that defines a new class called Complex. Following the paradigm established for the Fraction class, define the following method for your new class:


-(void) setReal: (double) a;

-(void) setImaginary: (double) b;

-(void) print; // display as a + bi

-(double) real;

-(double) imaginary;


Write a test program to test your new class and methods.


ANS - Copy and Paste of Program and Console below


#import


@interface Complex: NSObject

{

int real;

int imaginary;

}


-(void) setReal: (double) a;

-(void) setImaginary: (double) b;

-(void) print; // display as a + bi

-(double) real;

-(double) imaginary;


@end


@implementation Complex


-(void) setReal: (double) a;

{

real = a;

}


-(void) setImaginary: (double) b;

{

imaginary = b;

}


-(void) print;

{

NSLog(@"Complex number equals: %d + %di", real, imaginary);

}


-(double) real;

{

return real;

}


-(double) imaginary;

{

return imaginary;

}


@end


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Complex *comp1 = [[Complex alloc] init];

[comp1 setReal: 3];

[comp1 setImaginary: 2];

[comp1 print];

[comp1 release];

[pool drain];

return 0;

}


[Session started at 2009-03-30 01:46:05 +0100.]

2009-03-30 01:46:05.091 Chap4_Ex6_Complex[1021:10b] Complex number equals: 3 + 2i


The Debugger has exited with status 0.


7. Suppose you are developing a library of routines to manipulate graphical objects. Start by defining a new class called Rectangle. For now, just keep track of the rectangle's width and height. Develop methods to set the rectangle's width and height, retrieve these values, and calculate the rectangle's area and perimeter. Assume that these rectangle objects describe rectangles on an integral grid, such as a computer screen. In that case, assume that the width and height of the rectangle are integer values.


Here is the @interface section for the rectangle class:

@interface Rectangle: NSObject

{

int width;

int height;

}


-(void) setWidth: (int) w;

-(void) setHeight: (int) h;

-(int) width;

-(int) height;

-(int) area;

-(int) perimeter;

@end


Write the @implementation section and a test program to test your new class and methods.


ANS - Copy and Paste of the Program and Console below.


#import


@interface Rectangle: NSObject


{

int width;

int height;

}


-(void) setWidth: (int) w;

-(void) setHeight: (int) h;

-(int) width;

-(int) height;

-(int) area;

-(int) perimeter;


@end


@implementation Rectangle


-(void) setWidth: (int) w;

{

width = w;

}


-(void) setHeight: (int) h;

{

height = h;

}


-(int) width;

{

return width;

}


-(int) height;

{

return height;

}


-(int) area;

{

return height * width;

}


-(int) perimeter;

{

return 2 * height + 2 * width;

}


@end


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Rectangle *aRectangle = [[Rectangle alloc] init];


[aRectangle setWidth: 6];

[aRectangle setHeight: 4];

NSLog(@"The dimensions of the rectangle are: %i in width, %i in height", [aRectangle width], [aRectangle height]);

NSLog(@"The area of the rectangle is: %i", [aRectangle area]);

NSLog(@"The perimeter of the rectangle is: %i", [aRectangle perimeter]);

[aRectangle release];

[pool drain];

return 0;

}


[Session started at 2009-03-30 02:12:09 +0100.]

2009-03-30 02:12:09.249 Ex7_Rectangle[1123:10b] The dimensions of the rectangle are: 6 in width, 4 in height

2009-03-30 02:12:09.250 Ex7_Rectangle[1123:10b] The area of the rectangle is: 24

2009-03-30 02:12:09.251 Ex7_Rectangle[1123:10b] The perimeter of the rectangle is: 20


The Debugger has exited with status 0.


8. Modify the add:, subtract:, multiply:, and divide: methods from Program 4.6 to return the resulting value of the accumulator. Test the new methods.


ANS - Copy and Paste of the Program and Console below.


#import


@interface Calculator: NSObject

{

double accumulator;

}


-(void) setAccumulator: (double) value;

-(void) clear;

-(double) accumulator;


-(void) add: (double) value;

-(void) subtract: (double) value;

-(void) multiply: (double) value;

-(void) divide: (double) value;


@end


@implementation Calculator


-(void) setAccumulator: (double) value;

{

accumulator = value;

}


-(void) clear;

{

accumulator = 0;

}


-(double) accumulator;

{

return accumulator;

}


-(void) add: (double) value;

{

accumulator += value;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(void) subtract: (double) value;

{

accumulator -= value;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(void) multiply: (double) value;

{

accumulator *= value;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(void) divide: (double) value;

{

accumulator /= value;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


@end



int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Calculator *deskCalc = [[Calculator alloc] init];

[deskCalc clear];

[deskCalc setAccumulator: 100.0];

[deskCalc add: 200.];

[deskCalc divide: 15.0];

[deskCalc subtract: 10.0];

[deskCalc multiply: 5];

NSLog(@"The final result is: %f", [deskCalc accumulator]);

[deskCalc release];

[pool drain];

return 0;

}


[Session started at 2009-03-30 02:35:26 +0100.]

2009-03-30 02:35:26.990 Ex8_Calculator[1185:10b] The resulting value of accumulator is: 300.000000

2009-03-30 02:35:26.992 Ex8_Calculator[1185:10b] The resulting value of accumulator is: 20.000000

2009-03-30 02:35:26.992 Ex8_Calculator[1185:10b] The resulting value of accumulator is: 10.000000

2009-03-30 02:35:26.992 Ex8_Calculator[1185:10b] The resulting value of accumulator is: 50.000000

2009-03-30 02:35:26.993 Ex8_Calculator[1185:10b] The final result is: 50.000000


The Debugger has exited with status 0.


9. After completing exercise 8, add the following methods to the calculator and test them:

-(double) changeSign; // change sign of accumulator

-(double) reciprocal; // 1/accumulator

-(double) xSquared; // accumulator squared


ANS - Copy and Paste of @implementation, program and console of the above methods


@implementation Calculator


-(double) changeSign;

{

return -accumulator;

}


-(double) reciprocal;

{

return 1 / accumulator;

}


-(double) xSquared;

{

return accumulator * accumulator

@end



int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Calculator *deskCalc = [[Calculator alloc] init];

[deskCalc changeSign];

[deskCalc reciprocal];

[deskCalc xSquared];

NSLog(@"The final result is: %f", [deskCalc accumulator]);

[deskCalc release];

[pool drain];

return 0;

}


>>I was unable to get these methods to work and I am unsure as to why


10. Add a memory capability to the Calculator class from Program 4.6. Implement the following method declarations and test them:


-(double) memoryClear; // clear memory

-(double) memoryStore; // set memory to accumulator

-(double) memoryRecall; // set accumulator to memory

-(double) memoryAdd; // add accumulator to memory

-(double) memorySubtract; // subtract accumulator from memory


Have each method return the value of the accumulator.


ANS - Copy and Paste of @implementation, program and console of the above methods


@implementation Calculator


-(double) memoryClear;

{

memory = 0;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(double) memoryStore;

{

memory = accumulator;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(double) memoryRecall;

{

accumulator = memory;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(double) memoryAdd;

{

memory += accumulator;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


-(double) memorySubtract;

{

memory -= accumulator;

return NSLog(@"The resulting value of accumulator is: %f", accumulator);

}


@end


I have included the interface and implementation for this question but I have not included any methods in the main program as I could not resolve the problem in the previous question.


Sunday 22 March 2009

Chapter 3 - Classes, Objects and Methods

Comment

So far this chapter has been conceptually difficult to understand but as the author moved on to coded examples and began to explain them it became much easier to pick up. Another neat feature of objective-c is the ability to allocate an order in which events are executed - in a similar way you would use brackets on your calculator.

The following exercises are quite theoretical and so as a result there is little example of code or syntax.


Exercises

1. Which of the following are invalid names? Why?

ANS- Int - reserved by the objective-c compiler

6_05 - cannot begin with a number (only underscore or letter)

A$ - '$' is an invalid character


_ - unsure if this is invalid but does not contain any letters or numbers so I reckon that it is


Valid names include;

_calloc,

Xx,

playNextSong,

alphaBetaRoutine,

clearScreen,

_1312,

z,

ReIntialise.


2. [...]Think of an object you use everyday. Identify a class for that object and write five actions you do with that object.


ANS - An object I use everyday is my mobile phone

A class for this could be 'Phone'

Actions:

Text

Call

Browse the web

Recharge

Take a picture


3. Given the list in exercise 2, use the following syntax to rewrite your list in this format: [instance method] ;


ANS - [myPhone text] ;

[myPhone call] ;

[myPhone browse] ;

[myPhone recharge] ;

[myPhone picture];


4. Imagine you owned a boat and a motorcycle in addition to a car. List the actions you would perform with each of these. Do you have any overlap between these actions?


ANS- actions Boat;

prepare it for use

sail it

clean it

get it serviced

dock it


actions Motorcycle

prepare to drive it

drive it

clean it

get it serviced

park it


actions Car

prepare to drive it

drive it

clean it

get it serviced

park it


There is a lot of overlap between the three sections, particularly;

prepare, clean, service and arguably sail/drive, dock/park


5. Based on question 4, imagine that you had a class called Vehicle and an object called myVehicle that could be either Car, Motorcycle, or Boat. Imagine that you wrote the following:


[myVehicle prep];

[myVehicle getGas];

[myVehicle service];


Do you see any advantage of being able to apply an action to an object that could be from one of several classes?


ANS - Yes, as no matter which vehicle is selected, they all can perform the same action which would make it simpler to compare different objects or apply the same action to all of these objects.


6. In a procedural language such as C, you think about actions and then write code to perform the action on various objects. Referring to the car example, you might write a procedure in C to wash a vehicle and then inside that procedure write code to handle washing a car, washing a boat, washing a motorcycle, and so on. If you took that approach and then wanted to add a new vehicle type (see the previous exercise), do you see advantages or disadvantages to using this procedural approach over an object-oriented approach?


ANS- An advantage would be the ability to slightly modify the procedure for washing the new vehicle type without affecting the others in place.

A disadvantage would be that the new vehicle type would not inherit the instances and methods of the previous ones and all of these would also need to be added to the new vehicle type which would be time-consuming.


7. Define a class called XYPoint that will hold a Cartesian coordinate (x, y), where x and y are integers. Define methods to individually set the x and y coordinates of a point and retrieve their values. Write an Objective-C program to implement your new class and test it.


ANS - When writing this program, I learnt a valuable lesson about invalid names. At first I tried to use the '-' character in between X or Y and 'coordinate' which threw up a multitude of errors from the compiler. After resolving this issue, the program compiled and ran error free. The program has been copied and pasted from Xcode and the Console output;


#import


@interface XYPoint: NSObject

{

int Xcoordinate;

int Ycoordinate;

}


-(void) setX: (int) X;

-(void) setY: (int) Y;

-(int) Xcoordinate;

-(int) Ycoordinate;


@end


@implementation XYPoint


-(void) setX: (int) X

{

Xcoordinate = X;

}


-(void) setY: (int) Y

{

Ycoordinate = Y;

}


-(int) Xcoordinate;

{

return Xcoordinate;

}


-(int) Ycoordinate;

{

return Ycoordinate;

}


@end



int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

XYPoint *cartCoord = [[XYPoint alloc] init];

[cartCoord setX: 1];

[cartCoord setY: 2];

NSLog (@"The value of cartCoord is: (%i,%i)", [cartCoord Xcoordinate], [cartCoord Ycoordinate]);

[cartCoord release];

[pool drain];

return 0;

}


[Session started at 2009-03-23 00:16:12 +0000.]

2009-03-23 00:16:12.857 Chap3_Ex7_XYPoint[472:10b] The value of cartCoord is: (1,2)


The Debugger has exited with status 0.

Wednesday 11 March 2009

Chapter 2 - Programming in Objective-C

Comment

So far I have found the 'NSLog' sub-routine of particular interest. The concept of a 'format string' is so much simpler and intuitive to the likes of VisualBasic for a simpler way to output the value of certain variables.


Exercises


1. Type in and run the five programs presented in this chapter. Compare the output produced by each program with the output presented after each program [written in the book].


ANS - In all cases the output of my programs matched those in the book. Xcode pointed out some syntax errors I had made but these were easily corrected.


2. Write a program that displays the following text:

"In Objective-C, lowercase letters are significant.

main is where program execution begins.

Open and closed braces enclose program statements in a routine

All program statements must be terminated by a semicolon."


ANS - Below is the code and output from the debugger


#import


int main (int argc, const char * argv[]) {

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


NSLog(@"In Objective-C, lowercase letters are significant.\nmain is where program execution begins.\nOpen and closed braces enclose program statements in a routine.\nAll program statements must be terminated by a semicolon.");

[pool drain];

return 0;

}


[Session started at 2009-03-11 20:39:43 +0000.]

2009-03-11 20:39:43.912 progEx2[386:10b] In Objective-C, lowercase letters are significant.

main is where program execution begins.

Open and closed braces enclose program statements in a routine.

All program statements must be terminated by a semicolon.


The Debugger has exited with status 0.


3. What output would you expect from the following program?


#import


int main (int argc, const char *argv[])

{

NSAutoreleasePool * pool = [ [NSAutoreleasePool alloc] init;

int i;


i = 1

NSLog (@"Testing...");

NSLog (@"....%i", i);

NSLog (@"...%i", i + 1);

NSLog (@"..%i", 1 + 2);


[pool drain];

return 0;

}


ANS - Expected Output:

Testing

....1

...2

..3


The value of the variable "i" is incremented by an additional one in each following NSLog which would produce the output above.


4. Write a program that subtracts the value 15 from 87 and displays the result, together with an appropriate message.


ANS - See the code below;


#import


int main (int argc, const char *argv[])

{

NSAutoreleasePool * pool = [ [NSAutoreleasePool alloc] init;


int sum;


sum = 87 - 14;

NSLog (@"The sum of 87 minus 15 is equal to %i", sum);


[pool drain];

return 0;

}


5. Identify the syntactic errors in the following program. Then type in and run the corrected program to make sure you have identified all the mistakes:


#import


int main (int argc, const char *argv[])

{

NSAutoreleasePool * pool = [ [NSAutoreleasePool alloc] init;


INT sum;

/* COMPUTE RESULT //

sum = 25 + 37 - 19

/ DISPLAY RESULTS /

NSLog (@'The answer is %i' sum);

[pool drain];

return 0;

}



ANS - I have separated the code line by line and commented on each one


1. int is not lower case

2. comment opened but not ended properly

3. statement not ended with semicolon

4. comment slashes not used in correct format

5. ' used instead of " and arguments not separated by comma


6. What output would you expect from the following program?


#import


int main (int argc, const char *argv[])

{

NSAutoreleasePool * pool = [ [NSAutoreleasePool alloc] init;


int answer, result;


answer = 100;

result = answer - 10;


NSLog(@"The result is &i\n", result + 5);


[pool drain];

return 0;

}


ANS - output = "The result is 95"

EDIT:

Error in example 6 - the line of code should read:

"NSLog(@"The result is %i\n", result + 5);"

The output should read:

"The result is 95

"


EDIT 2: Changed the title of this post to suit the format of my later post