0% found this document useful (0 votes)
12 views

Assignment 4

Uploaded by

np111664
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Assignment 4

Uploaded by

np111664
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Problem 2.

Write a program that converts an integer number n to a binary number by


using stack. For example, 1101 is the binary number of 13.

Problem 3. Write a program to reverse a string using two different techniques: stack and
recursion. For example, “hello” is converted to “olleh”.

#include <bits/stdc++.h>
using namespace std;
class Stack
{
public:
int top;
unsigned capacity;
char* array;
};

Stack* createStack(unsigned capacity)


{
Stack* stack = new Stack();
stack->capacity = capacity;
stack->top = -1;
stack->array = new char[(stack->capacity * sizeof(char))];
return stack;
}
int isFull(Stack* stack)
{ return stack->top == stack->capacity - 1; }
int isEmpty(Stack* stack)
{ return stack->top == -1; }

void push(Stack* stack, char item)


{
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}

char pop(Stack* stack)


{
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
}

void reverse(char str[])


{

int n = strlen(str);
Stack* stack = createStack(n);

int i;
for (i = 0; i < n; i++)
push(stack, str[i]);

for (i = 0; i < n; i++)


str[i] = pop(stack);
}

int main()
{
char str[51];
cout<<"Enter a string :";
gets(str);

reverse(str);
cout << "Reversed string is " << str;
return 0;
}

You might also like