The C programming language (second edition,KR) exercise(CHAPTER 4)

      E x c e r c i s e 4 − 1 Excercise\quad 4-1 Excercise41

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int strindex(char s[],char t[]);
int strrindex(char s[],char t[]);


int main(void) 
{
    char s[100]="qwoulddfsdfdsgdsgdsgdsouldasdasdasd";
    char t[100]="ould";	
    int l_index=strindex(s,t);
    int r_index=strrindex(s,t);	
	printf("l_index=%d\n",l_index);	
	printf("r_index=%d\n",r_index);		
    return 0;
}

int strindex(char s[],char t[])
{
    int i,j,k;
    for(i=0;s[i]!='\0' ;i++)
	{
		for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
			;
		if((k>0)&&(t[k]=='\0'))
			return i;
		
	}		
	return -1;
}

int strrindex(char s[],char t[])
{
    int i,j,k;
	int t_len=strlen(t);
	int s_len=strlen(s);
	if(t_len>s_len)
	{
	    return -1;				
	}
	else
	{
        for(i=s_len-t_len;i>=0 ;i--)
	    {
	    	for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++)
	    		;
	    	if((k>0)&&(t[k]=='\0'))
	    		return i;	    	
	    }		
	    return -1;
	}
}

      E x c e r c i s e 4 − 2 Excercise\quad 4-2 Excercise42:输出如图1所示。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

double atof_myself(char s[]);


int main(void) 
{
    char s1[100]="123.789e1";
    char s2[100]="123456123456.789e-10";	
    char s3[100]="123.789";		
    double d1=atof_myself(s1);
    double d2=atof_myself(s2);
    double d3=atof_myself(s3);	
	printf("d1=%lf\n",d1);
	printf("d2=%lf\n",d2);	
	printf("d3=%lf\n",d3);		
    return 0;
}

double atof_myself(char s[])
{
	double val,power,power_more;
    int i,sign,sign_more,power_more_index;
    for(i=0;isspace(s[i]);i++);
	sign=(s[i]=='-')? -1:1;
	if((s[i]=='-')||(s[i]=='+'))
	{
		i++;
	}	
    for(val=0.0;isdigit(s[i]);i++)
	{
		val=10.0*val+(s[i]-'0');		
	}	
	if(s[i]=='.')
	{
		i++;
	}
    for(power=1.0;isdigit(s[i]);i++)
	{
		val=10.0*val+(s[i]-'0');
        power *=10.0;		
	}	
	if((s[i]=='e') ||(s[i]=='E'))
	{
		i++;
	    sign_more=(s[i]=='-')? -1:1;
	    if((s[i]=='-')||(s[i]=='+'))
	    {
	    	i++;
	    }	
        for(power_more_index=0;isdigit(s[i]);i++)
	    {
	    	power_more_index=10*power_more_index+(s[i]-'0');	
	    }
		power_more=1.0;
        for(i=0;i<power_more_index;i++)
		{
			power_more=power_more*10.0;			
		}	
	    if(sign_more==-1)
	    {
	        return ((sign * val/power)/power_more);    	    		    	
	    }
	    else
	    {
	        return ((sign * val/power)*power_more);  	
	    }		
	}
    else
    {
	    return (sign * val/power); 	   	
    }	
}
 
图1.

      E x c e r c i s e 4 − 3 Excercise\quad 4-3 Excercise43

#include <stdio.h>
#include <stdlib.h>   /* for atof() */
#include <math.h>     /* for fmod() */

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);


/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}


#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 4 Excercise\quad 4-4 Excercise44

#include <stdio.h>
#include <stdlib.h>   /* for atof() */
#include <math.h>     /* for fmod() */

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/				 
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if(sp > 0)
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 5 Excercise\quad 4-5 Excercise45

#include <stdio.h>
#include <stdlib.h>  
#include <math.h>   

#define MAXOP 100     /* max size of operand or operator */
#define NUMBER '0'    /* signal that a number was found */

int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
/****************************************************/				 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                 op2 = pop();
                 push(pow(pop(),op2));
                break;				
/****************************************************/				 
            case '\n':
                 printf("\t%.8g\n", pop());
                 break;				 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if(sp > 0)
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

	if(c == '-')
	{
        i = 0;			
        c = getch();	
        s[++i] = c;			
	}
	else
	{
        i = 0;				
	}
	
    if (isdigit(c)) /* collect integer part */
        while (isdigit(s[++i] = c = getch()));
    if (c == '.') /* collect fraction part */
        while (isdigit(s[++i] = c = getch()));
    s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
    if (i == 1 && s[0] == '-') // if s[0] == '-' && s[1] == '\0', return minus operator
        return '-';	
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 6 Excercise\quad 4-6 Excercise46:其实这一题的意图似乎还是很模糊的,我这里的做法是提供26个变量(分别对应26个小写英文字母),然后再提供一个数组用来存储这26个变量的值。如果要对某个变量赋值可以类似 x = n n n . n n n x=nnn.nnn x=nnn.nnn来操作,其中 x x x表示26个小写英文字母中的任何一个, n n n . n n n nnn.nnn nnn.nnn表示即将赋值给变量的值,这个值可以为负数,负数的话在最前面需要加上 − - ,比如 − n n n . n n n -nnn.nnn nnn.nnn。某个变量在参与运算之前需要先进行赋值操作,否则可能拿到的是默认值 0.0 0.0 0.0,变量参加运算的一个例子为 a 8 + a8+ a8+实际是变量 a a a的值和8进行加法运算。这里还记录了最近赋值或参与运算的是那个变量,并且 _ \_ _符号对应的命令操作会将这个最近赋值或参与运算的变量以及对应的值打印出来。

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

      E x c e r c i s e 4 − 7 Excercise\quad 4-7 Excercise47

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


#define BUFSIZE 100

char buf[BUFSIZE];   /* buffer for ungetch */
int bufp = 0;        /* next free position in buf */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (bufp >= BUFSIZE)
        printf("ungetch: too many characters\n");
    else
        buf[bufp++] = c;
}

/*
   ungets() actually takes a little bit of thought.  Should the
   first character in "s" be sent to ungetch() first, or should
   it be sent last?  I assumed that most code calling getch()
   would be of this form:

     char array[...];
     int i;   

     while (...) {
       array[i++] = getch();
     }                  

   In such cases, the same code might call ungets() as:

     ungets(array);

   and expect to repeat the while loop to get the same string
   back.  This requires that the last character be sent first
   to ungetch() first, because getch() and ungetch() work with 
   a stack.     

   To answer K&R2's additional question for this problem,
   it's usually preferable for something like ungets() to just
   build itself on top of ungetch().  This allows us to change 
   ungetch() and getch() in the future, perhaps to use a linked 
   list instead, without affecting ungets().
*/ 
void ungets(const char *s)
{    
	int i, len;
	len = strlen(s);
	if(BUFSIZE - bufp >= len)  // ungets() must do its own bounds checking
	{
		for(i = strlen(s) - 1; i >= 0; i--)
			ungetch(s[i]);
	}
	else
		printf("error: insufficient space in buffer, can't execute ungets()\n");
}

      E x c e r c i s e 4 − 8 Excercise\quad 4-8 Excercise48

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = getch()) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getch()) == '=')
		{			
            setVar = TRUE;
			c = getch();
			s[++i] = c;		
		}
        else
        {
		    if (c != EOF)
	        {		
                   ungetch(c);
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getch();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getch()));
	}
    s[i] = '\0';
    if (c != EOF)
	{		
        ungetch(c);
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


char buf=EOF;   /* buffer for ungetch */

int getch(void)      /* get a (possibly pushed-back) character */
{
    return (buf!=EOF) ? buf : getchar();
}

void ungetch(int c) /* push character back on input */
{
    if (buf!=EOF)
        printf("ungetch: too many characters\n");
    else
        buf = c;
}

      E x c e r c i s e 4 − 9 Excercise\quad 4-9 Excercise49

      E x c e r c i s e 4 − 10 Excercise\quad 4-10 Excercise410

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */
#define MAXLINE 1000        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	
int getline(char s[], int lim);

/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/*********************************/
char line[MAXLINE];
int line_i;
/*********************************/
/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
	
    while (getline(line, MAXLINE) != 0)
    {
    	line_i=0;
        while ((type = getop(s)) != '\0') 
    	{
            switch (type) 
    		{
                case NUMBER:
                     push(atof(s));
                     break;
    /****************************************************/				 
                case SETVARIABLE:
                     if (strlen(s) > 2 && s[1] == '=')
                     {
                         int v = s[0];           /* stores variable */
                         int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                         while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                             s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                         s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                         varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                     }
                     else
                         printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                     break;
                case GETVARIABLE:
                     push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                     break;	
    /****************************************************/				 
                case '+':
                     push(pop() + pop());
                     break;
                case '*':
                     push(pop() * pop());
                     break;
                case '-':
                     op2 = pop();
                     push(pop() - op2);
                     break;
                case '/':
                     op2 = pop();
                     if (op2 != 0.0)
                         push(pop() / op2);
                     else
                         printf("error: zero divisor\n");
                     break;
                case '%':
                     op2 = pop();
                     if (op2 != 0.0)
                         push(fmod(pop(),op2));
                     else
                         printf("error: zero divisor\n");
                     break;
    /****************************************************/				 
                case '?':
                    showTop();
                    break;
                case '#':
                    duplicate();
                    break;
                case '~':
                    swapItems();
                    break;
                case '!':
                    clearStack();	
                    break;				
    /****************************************************/
    			 
                case '$':
                    push(sin(pop()));
                    break;
                case '@':
                    push(exp(pop()));
                    break;
                case '^':
                    op2 = pop();
                    push(pow(pop(),op2));
                    break;									
                // case '\n':
                     // printf("\t%.8g\n", pop());
                     // break;
                case '\n':
                     view_stack();
                     break;	
                case '_':
                     printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                     break;					 
                default:
                     printf("error: unknown command %s\n", s);
                     break;
            }
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>
int getch(void);
void ungetch(int);

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i, c;
    char setVar = FALSE;
    i = 0;
    while ((s[0] = c = line[line_i++]) == ' ' || c == '\t');
    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = line[line_i++]) == '=')
		{			
            setVar = TRUE;
			c = line[line_i++];
			s[++i] = c;		
		}
        else
        {
		    if (c != '\0')
	        {		
                line_i=line_i-1;
	        }
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = line[line_i++];	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = line[line_i++]));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = line[line_i++]));
	}
    s[i] = '\0';
    if (c != '\0')
	{		
        line_i=line_i-1;
	}
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}


// /* getop: get next character or numeric operand */
// int getop(char s[])
// {
    // int i, c;
    // char setVar = FALSE;
    // i = 0;
    // while ((s[0] = c = getch()) == ' ' || c == '\t');
    // s[1] = '\0';
    // if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	// {	
        // return c; /* not a number */
	// }

    // if (c >= 'a' && c <= 'z')
    // {
	    // last_recent=c;
// /* get next char and check if it was an equal symbol.*/ 		
        // if ((s[++i] = c = getch()) == '=')
		// {			
            // setVar = TRUE;
			// c = getch();
			// s[++i] = c;		
		// }
        // else
        // {
		    // if (c != EOF)
	        // {		
                   // ungetch(c);
	        // }
            // return GETVARIABLE;
        // }
    // }

	// if(c == '-')
	// {		
        // c = getch();	
        // s[++i] = c;			
	// }
	
    // if (isdigit(c)) /* collect integer part */
	// {	
        // while (isdigit(s[++i] = c = getch()));
	// }
    // if (c == '.') /* collect fraction part */
	// {	
        // while (isdigit(s[++i] = c = getch()));
	// }
    // s[i] = '\0';
    // if (c != EOF)
	// {		
        // ungetch(c);
	// }
// /* if s[0] == '-' && s[1] == '\0', return minus operator */	
    // if (i == 1 && s[0] == '-') 
        // return '-';	
    // if (setVar)
	// {	
        // return SETVARIABLE;	
	// }		
    // return NUMBER;
// }

/* getline:  get line into s, return length */
int getline(char s[], int lim)
{
    int c, i;

    i = 0;
    while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
        s[i++] = c;
    if (c == '\n')
        s[i++] = c;
    s[i] = '\0';

    return i;
}

      E x c e r c i s e 4 − 11 Excercise\quad 4-11 Excercise411

#include <stdio.h>
#include <stdlib.h> 
#include <ctype.h>
#include <math.h>
#include <string.h> 

#define MAXOP     100     /* max size of operand or operator */
#define NUMBER    '0'     /* signal that a number was found */
#define SETVARIABLE 's'   /* signal that a variable is being assigned */
#define GETVARIABLE 'g'   /* signal that a variable is being retrieved */
#define NUMVARS 26        /* number of variables supported (a-z) */

enum boolean {FALSE, TRUE};


int getop(char []);
void push(double);
double pop(void);
void showTop(void);
void duplicate(void);
void swapItems(void);
void clearStack();
void view_stack();	


/* initially as space such that malformed use of '=' won't cause segfaults */
char last_recent = ' '; 
/* array to store the double values for variables. 
Supports variables a through z (lower case). Initial value is 0*/
double varVals[NUMVARS] = {0.0}; 

/* reverse Polish calculator */
int main()
{
    int type;
    double op2;
    char s[MAXOP];
    while ((type = getop(s)) != EOF) 
	{
        switch (type) 
		{
		
            case NUMBER:
                 push(atof(s));
                 break;
/****************************************************/				 
            case SETVARIABLE:
                 if (strlen(s) > 2 && s[1] == '=')
                 {
                     int v = s[0];           /* stores variable */
                     int i = 1;              /* start at 1 since while loop needed ++i for a few reasons */
                     while (s[++i] != '\0')  /* this removes the variable name= part of s e.g. if s == "a=123.45" after loop s == "123.45" */
                         s[i - 2] = s[i];    /* shifts chars two to the left by 2 */
                     s[i - 2] = '\0';        /* since '\0' isn't copied, terminate string manually */
                     varVals[v - 'a'] = atof(s); /* convert string to double and store it in array */
                 }
                 else
                     printf("error: set variable length too small or incorrectly formatted (%s)\n", s);
                 break;
            case GETVARIABLE:
                 push(varVals[s[0] - 'a']);  /* convert the variable name to stored value */
                 break;	
/****************************************************/				 
            case '+':
                 push(pop() + pop());
                 break;
            case '*':
                 push(pop() * pop());
                 break;
            case '-':
                 op2 = pop();
                 push(pop() - op2);
                 break;
            case '/':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(pop() / op2);
                 else
                     printf("error: zero divisor\n");
                 break;
            case '%':
                 op2 = pop();
                 if (op2 != 0.0)
                     push(fmod(pop(),op2));
                 else
                     printf("error: zero divisor\n");
                 break;
/****************************************************/				 
            case '?':
                showTop();
                break;
            case '#':
                duplicate();
                break;
            case '~':
                swapItems();
                break;
            case '!':
                clearStack();	
                break;				
/****************************************************/
			 
            case '$':
                push(sin(pop()));
                break;
            case '@':
                push(exp(pop()));
                break;
            case '^':
                op2 = pop();
                push(pow(pop(),op2));
                break;									
            // case '\n':
                 // printf("\t%.8g\n", pop());
                 // break;
            case '\n':
                 view_stack();
                 break;	
            case '_':
                 printf("The last recently used variable is %c=%8g\n",last_recent, varVals[last_recent-'a']);
                 break;					 
            default:
                 printf("error: unknown command %s\n", s);
                 break;
        }
    }
    return 0;
}

#define MAXVAL 100   /* maximum depth of val stack */
int sp = 0;          /* next free stack position */
double val[MAXVAL];  /* value stack */

/* push: push f onto value stack */
void push(double f)
{
    if (sp < MAXVAL)
        val[sp++] = f;
    else
        printf("error: stack full, can't push %g\n", f);
}

/* pop: pop and return top value from stack */
double pop(void)
{
    if (sp > 0)
        return val[--sp];
    else 
	{
        printf("error: stack empty\n");
        return 0.0;
    }
}

/* push: push f onto value stack */
void view_stack()
{
	int i=sp;
    if (sp >0)
	{
       while(i>0)
	   {
		   printf("view_stack:%8g\n",val[i-1]);
		   i=i-1;
	   }
		
	}
    else
        printf("view_stack:Stack is empty\n");
}

/**********************************************************/
void showTop(void)
{
    if(sp > 0)
        printf("Top of stack contains: %8g\n", val[sp-1]);
    else
        printf("The stack is empty!\n");
}


void duplicate(void)
{
    double temp = 0.0;	
    if((sp > 0) &&(sp < MAXVAL))
    {
        temp = pop();
        push(temp);
        push(temp);				
	}
    else
        printf("The stack is empty!\n");	

}

void swapItems(void)
{
    double item1 = 0.0;
    double item2 = 0.0;	
    if(sp >= 2)
    {
        item1 = pop();
        item2 = pop();

        push(item1);
        push(item2);			
	}
    else
        printf("The stack is empty!\n");	
}

/* pop only returns a value if sp is greater than zero. So setting the
stack pointer to zero will cause pop to return its error */

void clearStack(void)
{
    sp = 0;
}

/**********************************************************/




#include <ctype.h>

/* getop: get next character or numeric operand */
int getop(char s[])
{
    int i;
    static int c=EOF;	
    static int unget_flag=0;		
    char setVar = FALSE;
    i = 0;
	if(unget_flag==1)
	{
		if((c== ' ') || (c == '\t'))
	    {
            while ((s[0] = c = getchar()) == ' ' || c == '\t');	    		    	
	    }	
		else
		{
			s[0] = c;			
		}
		unget_flag=0;
	}
	else
	{
        while ((s[0] = c = getchar()) == ' ' || c == '\t');				
	}

    s[1] = '\0';
    if (!isdigit(c) && !isalpha(c) && c != '.' && c != '-')
	{	
        return c; /* not a number */
	}

    if (c >= 'a' && c <= 'z')
    {
	    last_recent=c;
/* get next char and check if it was an equal symbol.*/ 		
        if ((s[++i] = c = getchar()) == '=')
		{			
            setVar = TRUE;
			c = getchar();
			s[++i] = c;		
		}
        else
        {
			if (c != EOF)
	        {		
                unget_flag=1;
	        }			
            return GETVARIABLE;
        }
    }

	if(c == '-')
	{		
        c = getchar();	
        s[++i] = c;			
	}
	
    if (isdigit(c)) /* collect integer part */
	{	
        while (isdigit(s[++i] = c = getchar()));
	}
    if (c == '.') /* collect fraction part */
	{	
        while (isdigit(s[++i] = c = getchar()));
	}	
    s[i] = '\0';
    if (c != EOF)
	{		
        unget_flag=1;
	}		
/* if s[0] == '-' && s[1] == '\0', return minus operator */	
    if (i == 1 && s[0] == '-') 
        return '-';	
    if (setVar)
	{	
        return SETVARIABLE;	
	}		
    return NUMBER;
}

      E x c e r c i s e 4 − 12 Excercise\quad 4-12 Excercise412

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[], int minmum);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer,25);
    printf("Buffer : %s\n", buffer);
    printf("\\*******************************\\\n");   
    printf("378\n");
    itoa_myself(378, buffer,25);
    printf("Buffer : %s\n", buffer);
    printf("\\*******************************\\\n");   
    printf("-873\n");
    itoa_myself(-873, buffer,25);
    printf("Buffer : %s\n", buffer);
   
    return 0;
}

void itoa_myself(int n, char s[],int minmum) 
{
    static int i=0;
    static int recur_num=0;	
	recur_num=recur_num+1;
    if(n<0)
	{
        s[i++] = '-';		
	}
    if(n/10)
	{
		itoa_myself(abs(n/10), s,minmum); 
	} 
	s[i++] = abs(n % 10) + '0';	
    if(i>minmum)
	{
		printf("Elements overflow\n");
	}
	recur_num=recur_num-1;
	if(recur_num==0)
	{	
	    s[i] = '\0';	
        i=0;
        recur_num=0;	    		
	}
}

      E x c e r c i s e 4 − 13 Excercise\quad 4-13 Excercise413

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[], int minmum);
void reverse(char s[]);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer,25);
    printf("Buffer : %s\n", buffer);
    
    return 0;
}

void itoa_myself(int n, char s[], int minmum) 
{
    int i, sign;
    sign = n;
    
    i = 0;
    do 
	{
        s[i++] = abs(n % 10) + '0';
    } while ( n /= 10 );
    if (sign < 0)
        s[i++] = '-';
	while(i<minmum)
	{
        s[i++] = ' ';		
	}	
    s[i] = '\0';
    reverse(s);
}

void reverse(char s[]) 
{
    int c;	
    static int first_flag=1;		
    static int i=0;	
    static int j=0;
	if(first_flag==1)
	{
		first_flag=0;
		j=strlen(s)-1;
	}
	
    if ( i < j ) 
	{
        c = s[i];
        s[i] = s[j];
        s[j] = c;
		i=i+1;
		j=j-1;
		reverse(s);
    }
}

      E x c e r c i s e 4 − 14 Excercise\quad 4-14 Excercise414

#include <stdio.h>

#define swap(t,x,y) {              \
	                    t temp=x;  \
                        x=y;       \
					    y=temp;    \
					}

int main(void) 
{
    int a=6;
	int b=9;
	swap(int,a,b)
    printf("a=%d,b=%d\n", a,b);
    return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/561428.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Java | Leetcode Java题解之第41题缺失的第一个正数

题目&#xff1a; 题解&#xff1a; class Solution {public int firstMissingPositive(int[] nums) {int n nums.length;for (int i 0; i < n; i) {while (nums[i] > 0 && nums[i] < n && nums[nums[i] - 1] ! nums[i]) {int temp nums[nums[i] …

yolov8实战第七天——pyqt5-yolov8实现车牌识别系统(参考论文(约7000字)+环境配置+完整部署代码+代码使用说明+训练好的模型)

基于 pyqt5-yolov8实现车牌识别系统,包括图片车牌识别,视频车牌识别,视频流车牌识别。 效果展示(图片检测,检测到的内容添加到历史记录): 效果展示(视频检测,视频车辆只会添加一条记录,下文更多实际应用中的优化策略): 基于YOLOv8和PyQt5的车牌识别系统设计与…

存储竞赛,角逐未来

随着人工智能&#xff08;AI&#xff09;和大数据驱动的海量数据需求&#xff0c;对存储技术的要求也在不断提高。在此背景下&#xff0c;各大存储芯片巨头之间的技术竞赛日益激烈。 在NAND闪存领域&#xff0c;企业关注的重点在于层数的突破。近日&#xff0c;《韩国经济日报》…

linux下编译c++程序报错“undefined reference to `std::allocator<char>::allocator()‘”

问题 linux下编译c程序报错“undefined reference to std::allocator::allocator()”。 原因 找不到c标准库文件。 解决办法 开始尝试给gcc指令添加-L和-l选项指定库路径和库文件名&#xff0c;但是一直不成功&#xff0c;后来把gcc改为g就可以了。

Stylus精讲:网页设计新境界【写作AI一键生成】

首先&#xff0c;这篇文章是基于笔尖AI写作进行文章创作的&#xff0c;喜欢的宝子&#xff0c;也可以去体验下&#xff0c;解放双手&#xff0c;上班直接摸鱼~ 按照惯例&#xff0c;先介绍下这款笔尖AI写作&#xff0c;宝子也可以直接下滑跳过看正文~ 笔尖Ai写作&#xff1a;…

SWCTF

easy_php 源码 <?php// flag is in flag.php highlight_file(__FILE__); ini_set(display_errors, 0); error_reporting(0);if (isset($_GET[myon1]) && isset($_GET[myon2]) && isset($_GET[myon3])) {$myon1 $_GET[myon1];$myon2 $_GET[myon2];$myon…

# Win10 打不开【本地组策略编辑器】解决方案

Win10 打不开【本地组策略编辑器】解决方案 段子手168 问题描述&#xff1a; 当在 WIN R 打开【运行】输入&#xff1a;gpedit.msc 打开【本地组策略编辑器】时&#xff0c;出现错误时&#xff0c; 或者在【计算机管理】中 没有【本地用户和组】这一项。 可以试一下以下方…

Go 之 sync.Mutex 加锁失效现象

我先声明一下&#xff0c;并不是真的加锁失效&#xff0c;而是我之前的理解有误&#xff0c;导致看起来像是加锁失效一样。于是乎记录一下&#xff0c;加深一下印象。 我之前有个理解误区&#xff08;不知道大家有没有&#xff0c;有的话赶紧纠正一下——其实也是因为我这块的…

Spec-Gaussian:3D高斯溅射的各向异性视图相关外观

Spec-Gaussian: Anisotropic View-Dependent Appearance for 3D Gaussian Splatting Spec-Gaussian&#xff1a;3D高斯溅射的各向异性视图相关外观 Ziyi Yang1,3  Xinyu Gao1  Yangtian Sun2  Yihua Huang2  Xiaoyang Lyu2 杨子怡 1,3 高新宇 1 太阳扬天 2 黄宜华 2 吕晓阳…

【github主页】优化简历

【github主页】优化简历 写在最前面一、新建秘密仓库二、插件卡片配置1、仓库状态统计2、Most used languages&#xff08;GitHub 常用语言统计&#xff09;使用细则 3、Visitor Badge&#xff08;GitHub 访客徽章&#xff09;4、社交统计5、打字特效6、省略展示小猫 &#x1f…

Java+springboot开发的医院智能导诊服务系统源码 自动兼容小程序与H5版本

智能导诊系统 一、什么是智慧导诊系统&#xff1f; 智慧导诊系统是一种医院使用的引导患者自助就诊挂号、精准推荐科室、引导患者挂号就诊的系统。该系统结合医院挂号及就诊的HIS系统&#xff0c;为患者带来全流程的信息指引提醒&#xff0c;可以在全院区构建一个精细化、移动…

react 项目路由配置(react-router-dom 版本 v6.3、v6.4)

根据 react-router-dom 的版本&#xff0c;有不同的方式 一、react-router-dom v6.3 用到的主要 api: BrowserRouteruseRoutesOutlet 下面是详细步骤&#xff1a; 1、index.js BrowserRouter 用来实现 单页的客户端路由使用 BrowserRouter 包裹 App放在 顶级 位置&#x…

MATLAB初学者入门(7)—— 参数估计

参数估计是利用实验数据来推断模型参数的过程&#xff0c;这在科学和工程领域中非常常见。MATLAB提供了多种工具来进行参数估计&#xff0c;尤其是当模型表现为非线性时。以下是使用MATLAB进行参数估计的一种常见方法&#xff0c;我们将通过一个具体的案例——化学动力学模型的…

EI级 | Matlab实现VMD-TCN-LSTM-MATT变分模态分解卷积长短期记忆神经网络多头注意力多变量时间序列预测

EI级 | Matlab实现VMD-TCN-LSTM-MATT变分模态分解卷积长短期记忆神经网络多头注意力多变量时间序列预测 目录 EI级 | Matlab实现VMD-TCN-LSTM-MATT变分模态分解卷积长短期记忆神经网络多头注意力多变量时间序列预测预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.Matl…

手写一个Spring IOC框架

目录 一&#xff0c;Spring IOC 二&#xff0c;流程图设计 三&#xff0c;设计思路解析 三&#xff0c;开始写代码 1.准备工作: 2.扫描并加载类信息 3.初始化bean 4.测试一下 一&#xff0c;Spring IOC Spring IoC容器是Spring框架的核心&#xff0c;它通过读取配置信息…

【C语言】万字详讲操作符

目录 前言 一、操作符分类 二、算数操作符 三、移位操作符 四、位操作符 五、赋值操作符 六、单目操作符 6.1 逻辑反操作 6.2 负值与正值 6.3 取地址 6.4 sizeof 6.5 取反操作符 6.6 --和操作符 6.7 间接访问操作符&#xff08;解引用操作符&#xff09; 6.8 强…

java导出数据到excel表中

java导出数据到excel表中 环境说明项目结构1.controller层2.service层3.实现层4.工具类&#xff1a;ExcelUtil.java5.ProductModel.java类 使用的Maven依赖postman请求展示&#xff0c;返回内容需要前端接收浏览器接收说明&#xff08;如果下载下来的为zip类型&#xff0c;记得…

矽塔SA8321 单通道 2.7-12.0V 持续电流 3.0A H 桥驱动芯片

描述 SA8321是为消费类产品&#xff0c;玩具和其他低压或者电池供电的运动控制类应用提供了一个集成的电机驱动器解决方案。此器件能够驱动一个直流无刷电机&#xff0c;由一个内部电荷泵生成所需的栅极驱动电压电路和4个功率 NMOS组成H桥驱动&#xff0c;集成了电机正转/反…

polkit服务启动失败

使用systemctl 命令报错 Authorization not available. Check if polkit service is running or see debug message for more information. 查看polkit状态是失败的状态&#xff0c;报缺少libstdc.so.6 systemctl status polkit 需要安装libstdc.so.6库 先加载所有安装包 …

网络安全产品---堡垒机

what 在网上搜索 运维审计与风险控制系统就是是堡垒机 我认为的堡垒机就是提供高效运维、认证管理、访问控制、安全审计和报表分析功能的云服务设备 实现高效运维的同时最大程度控制运维风险。 how 能够对运维人员维护过程进行全面跟踪、控制、记录、回放 支持细粒度配置…