Exercise 4-6 (varscalc - Single-letter variable names)
Chapter_4 Exercise_4-5 | Exercise_4-7 |
Exercise 4-6 K&R, p. 79
Exercise 4-6. Add commands for handling variables. (It's easy to provide twenty-six variables with single-letter names.) Add a variable for the most recently printed value.
Notes:
We use two arrays, char variables[26] and
char descriptions[26][100], to map
single-letter variable names and their corresponding descriptions.
Thus, variables[i] contains
a variable name (a lowercase letter) and
descriptions[i] contains
a string describing the variable (up to 100 chars).
See Chapter_5,
Sec. 5.5 for strcpy,
and Sections 5.6 — 5.9, for multidimensional arrays.
We added the commands
`L' and `P'
(uppercase letters) to list, respectively print the variables (lowercase letters)
along with their corresponding descriptions.
varscalc.c download
#include <stdio.h> // for getchar(), putchar(), printf(), EOF
#include <stdlib.h> // for atof()
#include <string.h> // for strcpy()
#define MAXOP 100 // max size of operand or operator
#define NUMBER '0' // signal that a number has been found
#define VARS 26 // single-letter variable names
#define DESCRIPTION 100 // max description length for variables
int getop(char []); // get the next operand or operator
void push(double); // push operand on stack
double pop(void); // pop operand from stack
int main()
{
int type, i1, i2;
double op2; // operand
double last = 0.0; // last printed value
char s[MAXOP]; // operand or operator
extern int sp; // stack pointer
extern double val[]; // stack
char variables[VARS] = {'\0'}; // single-letter variable names
char descriptions[VARS][DESCRIPTION]; // 2D array
variables['l'-'a'] = 'l';
strcpy(descriptions['l'-'a'], "last printed value");
variables['p'-'a'] = 'p';
strcpy(descriptions['p'-'a'], "print stack");
variables['s'-'a'] = 's';
strcpy(descriptions['s'-'a'], "stack size");
while((type = getop(s)) != EOF && type != '\0')
{ // nonempty line ending with EOF will not be executed
switch(type)
{
case NUMBER :
push(atof(s));
break;
case '+' :
push(pop() + pop());
break;
case '-' :
op2 = pop();
push(pop() - op2);
break;
case '*' :
push(pop() * pop());
break;
case '/' :
op2 = pop();
if (op2 != 0.0)
{push(pop() / op2);}
else {printf("Error: zero divisor\n");}
break;
case '%' :
i2 = pop(); // automatic conversions
i1 = pop(); // from double to int
if (i2 != 0.0) // automatic conversions from int to double,
{push(i1 % i2);} // here argument of push()
else {printf("Error: zero divisor\n");}
break;
case 'l' : // last printed value
printf("Last printed value: %.8g\n", last);
break;
case 's' : // stack size
printf("Stack size: %d\n", sp);
break;
case 'p' : // print stack
for (i1 = 0; i1 < sp; i1++)
{
printf("%g ", val[i1]);
}
putchar('\n');
break;
case 'L' : // list variables
for (i1 = 0; i1 < VARS; i1++)
{
if (variables[i1] != '\0') // non-null
{printf("%c, ", variables[i1]);}
}
putchar('\n');
break;
case 'P' : // print variables and descriptions
for (i1 = 0; i1 < VARS; i1++)
{
if (variables[i1] != '\0') // non-null
{ // print non-null variables and their descriptions:
printf("%c - %s\n", variables[i1], descriptions[i1]);
}
}
break;
case '\n' :
last = pop(); // top of stack
printf("\t%.8g\n", last); // last printed value
break;
default :
printf("Unknown command: %s\n", s);
break;
}
}
return 0;
}
#define MAXVAL 100 // stack size
// stack pointer (0 is top of stack):
int sp = 0; // next free stack position
double val[MAXVAL]; // value stack
void push(double f) // push f on (top of) stack
{
if (sp < MAXVAL) {val[sp++] = f;}
else {printf("Error: stack full, can't push %g\n", f);}
}
double pop(void) // pop and return top value from stack
{
if (sp > 0) {return val[--sp];}
else
{
printf("Error: stack empty\n");
return 0.0;
}
}
#include <ctype.h> // for isdigit()
int getch(void);
void ungetch(int);
int getop(char s[]) // get next operator or numeric operand
{
int c, i;
while ((s[0] = c = getch()) == ' ' || c == '\t') // skip beginning ' ', '\t'
{} // last value read in s[0] is not ' ' or '\t', but could be '\n' or EOF
s[1] = '\0'; // end string
if (!isdigit(c) && c != '.' && c != '+' && c != '-')
{return c;} // not a number, probably an operator (or '\n' or '\0' or EOF)
// here c is digit or '.' or '+' or '-'
i = 0;
if (c == '+' || c == '-') // unary or binary sign
{
c = getch();
if (!isdigit(c) && c != '.')
{
ungetch(c);
return s[0]; // binary '+' or '-'
}
else // c is digit or '.'
{
if (s[i] == '-') {i++;} // s[0]
// if (s[i] == '+') {} // skip adding '+' to s[]
s[i] = c; // digit or '.'
}
}
if (isdigit(c)) // collect integer part
{ // s[i] contains c (digit)
while (isdigit(s[++i] = c = getch()))
{}
} // here s[i] is not a digit
if (c == '.') // collect fraction part
{ // s[i] contains c (s[i] == '.')
while (isdigit(s[++i] = c = getch()))
{}
} // here s[i] is not a digit
s[i] = '\0'; // end string containing number (operand)
if (c != EOF) {ungetch(c);} // cannot ungetch(EOF) as EOF is not a char
else {ungetch('\0');} // EOF or '\0' returned by getop() will end the program
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE]; // buffer for ungetch()
// buf[] pointer (0 is top of buf):
int bufp = 0; // next free position in buf[]
int getch(void) // get a (possibly pushed-back) character
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
// push character back on input (make it available for the next getch()):
void ungetch(int c)
{
if (bufp >= BUFSIZE)
{printf("ungetch(): too many characters\n");}
else {buf[bufp++] = c;}
}
/*
gcc varscalc.c -o varscalc
./varscalc
L
l, p, s,
Error: stack empty
0 // pop() called by '\n'
P
l - last printed value
p - print stack
s - stack size
Error: stack empty
0 // pop() called by '\n'
s
Stack size: 0
Error: stack empty
0
1 2 3 s
Stack size: 3
3 // pop() called by '\n'
+
3
p
Error: stack empty
0
1 2 3 p // print stack
1 2 3
3 // pop() called by '\n'
p
1 2
2 // pop() called by '\n'
p
1
1 // pop() called by '\n'
p
Error: stack empty // pop() called by '\n'
0 // value returned by pop() for empty stack
1 2 3 l
Last printed value: 0
3
l
Last printed value: 3
2
l
Last printed value: 2
1
l
Last printed value: 1
Error: stack empty
0
l
Last printed value: 0
Error: stack empty
0
1 2 +
3
1 2 + 3 * 4 /
2.25
-1 2 +
1
1 2 -
-1 // 1-2
-1 -2 +
-3
-1 2 + 3 *
3
2 0 /
Error: zero divisor
2 // pop() called by '\n' returns first operand, still on stack
1 2 /
0.5
2 3 %
2
4 2 %
0
4 1 %
0
4 3 %
1
4 0 %
Error: zero divisor
Error: stack empty // nothing pushed, '\n' calls pop():
0 // value returned by pop() for an empty stack
a b +
Unknown command: a
Unknown command: b
Error: stack empty // nothing pushed, pop() called by +
Error: stack empty // pop() called by '\n'
0 // value returned by pop() for an empty stack
1 2 9
9 // pop() called by '\n'
+
3 // 1 + 2
1 2 c
Unknown command: c
2 // pop() called by '\n'
3 +
4 // 1 + 3
CTRL^D (EOF) or CTRL^C in Linux, CTRL^Z + Enter in Windows
./varscalc < compute.txt
3 // 1 2 +
0 // 1 2 * 3 + 5 -
1 // -1 2 +
1 // -1 -2 -
1 // 4 3 %
Error: zero divisor // 2 0 %
Error: stack empty // nothing pushed, '\n' calls pop():
0 // value returned by pop() for an empty stack
0.33333333 // 1 3 /
Error: zero divisor // 1 0 /
1 // pop() called by '\n' returns first operand, still on stack
*/
Notes:
See Exercise_4-3
for the file compute.txt.
If you add new variables, don't forget to add corresponding descriptions.
You should follow the same convention we used here: commands for handling variables
are uppercase letters, while variables are lowercase letters.
Chapter_4 Exercise_4-5 | BACK_TO_TOP | Exercise_4-7 |
Comments
Post a Comment