I wrote a simple command line program to help my daughter practice addition and subtraction. It compiles under NeXTSTEP 3.3 with some warnings, but works fine.
You can compile it using the command:
cc -Wall -o quiz quiz.m -lNeXT_s -lsys_s
I am posting the code here for any recommendations for improvement. I could improve it to use the AppKit, but for now I just wanted to do something quick and dirty on the command line. I am a mechanical engineer, not a programmer, so there's probably a better way of doing this. But it is a good example of some basic Objective-C code, (pre-Foundation for those who care).
My daughter loves using my NeXT for drawing with WetPaint. Now she can practice her addition and subtraction too. So she's becoming a new NeXT fan. :D
Here's the code:
// This program is to teach basic addition
// and subtraction.
#import <objc/Object.h>
#import <stdio.h>
#import <time.h>
@interface Quiz:Object
{
int value1, value2, answer, score;
char operation;
}
-setOperation:(char *)anOp;
-generateExpression;
-displayExpression;
-checkAnswer;
-(int)score;
@end
@implementation Quiz
-setOperation:(char *)anOp
{
operation = anOp;
score = 0;
}
-generateExpression
{
srandom(time(NULL));
value1 = random() % 10 + 1;
value2 = random() % 10 + 1;
// my daughter is not familiar with negative numbers.
if(operation == '-' && value2>value1) {
answer = value1;
value1 = value2;
value2 = answer;
}
}
-displayExpression
{
printf("%i %c %i = ?\n",value1, operation, value2);
}
-checkAnswer
{
scanf("%i", &answer);
switch(operation) {
case '+':
if(answer == value1+value2) {
printf("Correct!\n");
score++;
}
else { printf("Wrong: %i %c %i = %i\n", value1, operation,
value2, value1+value2);
}
break;
case '-':
if(answer == value1-value2) {
printf("Correct!\n");
score++;
}
else {
printf("Wrong: %i %c %i = %i\n", value1, operation,
value2, value1-value2);
}
break;
default:
printf("Unknown operator.\n");
break;
}
}
-(int)score
{
return score;
}
@end
int main (int argc, char *argv[])
{
int op, n;
Quiz *mathQuiz = [[Quiz alloc] init];
printf("Select an operation.\n");
printf("[1] For addition.\n");
printf("[2] For subtraction.\n");
scanf("%i", &op);
switch (op) {
case 1:
[mathQuiz setOperation: '+'];
break;
case 2:
[mathQuiz setOperation: '-'];
break;
default:
printf("Unknown Operation.\n");
return 0;
}
for(n=1; n<=10; n++) {
[mathQuiz generateExpression];
[mathQuiz displayExpression];
[mathQuiz checkAnswer];
}
printf("You have answered %i out of %i correctly.\n",[mathQuiz score], n-1);
[mathQuiz free];
return 0;
}
Brian Moore