Stack-decimal to octal

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

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef int Status;
typedef int Boolean;
typedef int SElemType;

#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10

//Sequential stack
struct SqStack
{
	SElemType *base;
	SElemType *top;
	int stacksize;
};

//Constructing an empty stack S
Status InitStack(SqStack &S)
{
	S.base = (int*)malloc(STACK_INIT_SIZE*sizeof(int));
	if (!S.base)
		exit(OVERFLOW);
	S.top = S.base;
	S.stacksize = STACK_INIT_SIZE;
	return OK;
}

//Check if the s stack is empty
Boolean StackEmpty(SqStack S)
{
	if (S.top == S.base)
		return TRUE;
	else 
		return FALSE;
}

//Insert element e as the new stack top element 
Status Push(SqStack &S,int e)
{
	if (S.top-S.base >= S.stacksize)  //Stack full, additional storage space 
	{
		S.base = (SElemType*)realloc(S.base,(S.stacksize+STACK_INCREMENT)*sizeof(SElemType));
		if (!S.base)
			exit (OVERFLOW);
		S.top = S.base + S.stacksize;
		S.stacksize += STACK_INCREMENT;
	}
	*(S.top)++=e;
	return OK;
}

//If the stack is not empty, delete the top element of S and return its value with e 
Status Pop(SqStack &S,int &e)
{
	if (S.top == S.base)
		return ERROR;
	e = *--S.top;
	return OK;
}

// For input non-negative decimal integers, print out octal numbers equivalent to them
void conversion(SqStack S)
{    
    int N,e; 
    InitStack(S);
    printf("Please enter a decimal integer:");
    scanf("%d",&N); 
    while(N){
        Push(S,N%8);
        N=N/8;  
    } 
    printf("Convert to octal:"); 
    while(!StackEmpty(S)){
        Pop(S,e);
        printf("%d",e); 
    } 
   printf("\n"); 
} 

int main()
{
	SqStack S;
    conversion(S); 
}

The conversion between decimal N and other d base numbers is based on the following principles:

N=(N/d)*d+N%d;

 

For the above calculation process, each digit of octal number is generated in order from low to high, and the printing output should generally be carried out from high to low, just contrary to the calculation process. Therefore, if the octal bits obtained in the calculation process are put on the stack, the octal number corresponding to the input will be printed out according to the out-stack sequence.

Posted on Mon, 07 Oct 2019 18:06:41 -0700 by whmeeske