Converting Decimal Number to Binary Number using stack - c++

I am trying to convert a decimal number to binary number using stacks and I have to use structs.
Now from my understanding of structs, we can have member functions in them. And stack follows a LIFO strategy.
We can create a stack by making a struct, declaring some members, and have some functions to initialize and work on these members.
So, I tried declaring a struct with above mentioned things and my understanding, but I still do not seem to get the concept right. I believe it is an error on my part. But reading forums still does not help as we have not been taught classes yet and on every forum, structs and classes are intermixed.
Here is my code so far, any help and guidance regarding the concept and logic would be much appreciated.
#include<iostream>
using namespace std;
struct bin{
int num[15];
int ci;
void init()
{
ci = 0;
for (int i = 0;i < 15;i++)
num[i] = -1;
}
void push(int n)
{
num[ci] = n;
ci++;
}
int pop()
{
int temp = num[--ci];
num[ci] = -1;
return temp;
}
};
int main()
{
int inp, count = 0;
bin var;
cout << "Enter a decimal number to convert into binary: ";
cin >> inp;
while (inp != 0)
{
int rem = inp % 2;
cout << "rem= " << rem << endl;
inp /= 2;
cout << "inp= " << inp << endl;
var.push(rem);
count++;
}
cout << "\nYour binary is: ";
while (count != 0)
{
cout << var.pop();
count--;
}
return 0;
}
I tried my best to find the mistakes but couldn't. So,in the end I simply used arrays and implemented the code as follows
#include<iostream>
using namespace std;
void push(int bin[], int n, int &ci);
void init(int bin[], int &count, int &ci);
int pop(int bin[], int &ci);
void display(int bin[], int &count, int &ci);
void findBinary(int bin[], int &count, int&ci, int &inp);
int main()
{
int inp, count, ci;
int bin[20];
char c = '\0';
init(bin,count,ci);
cout << "Enter a decimal number to convert into binary: ";
cin >> inp;
findBinary(bin, count, ci, inp);
display(bin, count, ci);
return 0;
}
void init(int bin[], int &count, int &ci)
{
count = 0;
ci = 0;
for (int i = 0;i < 20;i++)
bin[i] = -1;
}
int pop(int bin[], int &ci)
{
int temp = bin[--ci];
return temp;
}
void push(int bin[], int n, int &ci)
{
bin[ci] = n;
ci++;
}
void display(int bin[], int &count, int &ci)
{
cout << "\nYour binary is: ";
while (count != 0)
{
cout << pop(bin, ci);
count--;
}
cout << endl;
}
void findBinary(int bin[], int &count, int&ci, int &inp)
{
while (inp != 0)
{
int rem = inp % 2;
inp /= 2;
push(bin, rem, ci);
count++;
}
}
So my questions are:
1. When we write a function within a struct, does the function runs when we create a struct type object?
2. Is the method I used to implement stack using struct in the first example correct?

When you first create an object from a struct or class, the constructor runs - but no other function (so not your init function). If you want that to run, you need to call it explicitly:
bin var;
var.init();
In terms of the implementation of your functions: you should use bounds-checking to ensure that you don't push more items than you can handle, or pop more than are in the queue. Besides that I can't see much wrong with them. Consider using a std::vector instead of an array, but as you're just starting to learn about C++, you'll likely cover that later in your course.
By the time you're adding constructors to a struct though, you may as well switch to using a class. In C++, structs and classes are equivalent (with the minor tweak that the default access modifier in a struct is public, whereas in classes it's private), so don't let that put you off.

why don't you do the problem in this way ,I fixed it just like this .
#include
using namespace std;
#define MAX_STACK 10
int top=-1;
struct bin
{
int num[MAX_STACK];
bool isEmpty()
{
return (top < 0);
}
void push(int newItem)
{
// if stack has no more room for
// another item
if (top >= MAX_STACK-1)
cout<<"Stack Overflow!";
else{
++top;
num[top] = newItem;
}
}
int pop()
{
if(top < 0)
{
//top points to nothing i.e stack is empty
cout << "Stack Underflow \n";
return 0;
}
else
{
/*decrement the top pointer and it
points to the next top element in the stack*/
int d = num[top--];
return d;
}
}
};
int main()
{
int value, count = 0;
bin var;
int rem;
cout << "Enter a decimal number to convert into binary: ";
cin >> value;
while (value != 0)
{
rem = value % 2;
cout << "rem= " << rem << endl;
var.push(rem);
count++;
value /= 2;
}
cout << "\nYour binary is: ";
while (count != 0)
{
cout << var.pop();
count--;
}
return 0;
}

Related

error in the window getting the number -172492288 at the end of the while loop

#include<iostream>
#include<fstream>
using namespace std;
int *elementShifter(int[], int);
int main()
{
int SIZE = 50;
int array[SIZE];
ifstream infile("Gradelist.txt");
if (!infile)
{
cout << "File not found" << endl;
return -1;
}
int count = -1,data=0;
while (!infile.eof())
{
count++;
if (count < 0 || count > 50)
return -1;
else
{
infile >> array[count];
}
cout << array[count] << endl;
}
cout << endl;
int *s=elementShifter(array, count);
for (int i = 0; i <=count; i++)
{
cout << *s << endl;
s++;
}
return 1;
}
int *elementShifter(int arr[], int size)
{
int *newArr = new int[size + 1];
newArr[0] = 0;
for (int i = 0; i < size; i++)
{
newArr[i+1]=arr[i];
}
return newArr;
}
I just cannot figure out why i am getting this number here
This is reworked into slightly more idiomatic C++, but there's stuff here that might not fly in whatever course you're in, so adapt accordingly:
#include<iostream>
#include<fstream>
// using namespace std; is a bad habit to get into, that prefix
// exists for an important reason: Code separation
// Tip: If you define before you reference a function in your code,
// there is no need for a separate declaration.
// Note use of const on arguments that are not mutated
void unshift(int*& array, size_t& size, const int elem) {
int *resized = new int[++size];
// Insert at the start of the array
resized[0] = elem;
// Copy the remainder
for (int i = 1; i < size; ++i) {
resized[i] = array[i-1];
}
// Don't forget to release the old memory or you have a leak
delete[] array;
// Since the pointer is passed in as a reference, easy to swap it
array = resized;
}
int main() {
size_t size = 1; // size_t is often used for "size"-type args
int *array = new int[size];
std::ifstream infile("Gradelist.txt");
if (!infile) {
// Use std::cerr for errors.
std::cerr << "File not found" << std::endl;
return -1;
}
// infile evaluates as true so long as it has data to read.
while (infile) {
// You already have a count, it's "size"
if (size> 50) {
return -1;
}
int input;
infile >> input;
// This function takes mutable arguments, so they change via
// references.
unshift(array, size, input);
}
std::cout << std::endl;
for (int i = 0; i < size; ++i) {
std::cout << array[i] << std::endl;
}
// Take out the trash
delete[] array;
// Return zero on success, non-zero on failure.
return 0;
}
Of course a lot of this code goes away if you can use std::vector<int> and push_back(), but if you need to learn how to do this at a low-level, here you are with pointers and all the mess they create.
The goal in modern C++ is to avoid using pointers and instead lean heavily on the Standard Library to help you out.

I can`t call the bool function in c++ (closed)

Hey guys please help me on this I have tried calling my bool function in my main func but it wont even show the first cout of program and the compiler terminates the program here is my code
#include <iostream>
using namespace std;
bool puzzle(int size, int array[], int start)
{
cout <<"how many blocks you want for the puzzle? \n";
cin >> size;
for (int i = 0; i < size; i++)
{
cout << "enter your numbers in order for the blocks:\n";
cin >> array[i];
if (array[0] > size) { return false; };
if (array[0] == size) { return true; };
}
}
int main()
{
puzzle;
return 0;
}
Your function has parameters so you need to call them to make it work. In this case (an example):
int size = 5;
int array[5];
int start = 0;
puzzle(size, array, start);

Trying to create lotto game, having problems with execution and compilation

im trying to set up a lottery game that asks for input from the user 3 times and compares this to numbers drawn by the random array. if any of these user numbers match a number in the array, the program should print out the numbers that matched.
ive tried to use while loops in my main function to control the flow but im still having issues with compilation
#include<iostream>
#include <ctime>
#include "array.h"
using std::cout; using std::cin; using std::endl;
const int sizeofArray = 20;
void assign(int wins[], int sizeofArray);
void draw(int sizeofArray, int wins[]);
bool check(int num1, int wins[], int sizeofArray);
void entry(int& userNum);
void printOut(int wins[], int num);
int main() {
srand(time(nullptr));
int user[sizeofArray];
cout << "Good luck with this weeks lotto drawing!" << endl;
int wins[sizeofArray];
assign(wins, sizeofArray);
draw(sizeofArray, wins);
int userInput;
entry(userInput);
bool win = check(userInput, wins, sizeofArray);
if (win)
cout << "you have won!" << endl;
printOut(wins, sizeofArray);
}
void assign(int wins[], int sizeofArray) {
for (int i = 0; i < sizeofArray; ++i)
wins[i] = 0;
}
void draw(int sizeofArray, int wins[]) {
int number = 0;
while (number < sizeofArray) {
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++;
}
}
}
bool check(int num1, int wins[], int sizeofArray) {
for (int j = 0; j < sizeofArray; j++) {
if (wins[j] == num1)
return true;
}
return false;
}
void entry(int& userNum) {
int j;
cout << "Enter your lottery number guess: ";
cin >> userNum;
cout << "Your number was " << userNum << endl;
}
void printOut(int wins[], int num) {
cout << "Winning numbers in lottery are" << endl;
for (int j = 0; j < num; ++j) {
cout << wins[j] << " ";
}
}
i
Your draw method is going to loop infinitely since you declared the condition variable twice which causes the ++ operator to be applied on the wrong variable
void draw(int sizeofArray, int wins[]) {
int number = 0; // <--- HERE
while (number < sizeofArray) {
int number = rand() % 100 + 1; // <--- AND HERE
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++; //This will increase the inner variable number not the outer one
}
}
}
to fix it just change the name of your variable
void draw(int sizeofArray, int wins[]) {
int counter = 0; <---
while (counter < sizeofArray) { <---
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
counter++; <---
}
}
}
Let's take a look at draw():
void draw(int sizeofArray, int wins[]) {
int number = 0; //First variable of name number
while (number < sizeofArray) {
//new variable with name number is introduced, it shadows the first one
int number = rand() % 100 + 1; //<-----------------------+
if (!check(number, wins, sizeofArray)) { // |
wins[number] = number; // |
number++; //Here you actually increase this variable-+
}
}
}
So called shadowing occurs here and the outer int number is never modified inside the loop. Just rename one of them and you should be fine.
If you want to read more about this, take a look here.

C++ Bin Packing Implementation using First Fit

I'm doing a project for university but I encountered an exception which I don't understand. I'm using S.Sahni algorithms, so mostly I've got the code from his book. What I'm trying to do is to implement the Bin Packing problem with First Fit while I'm using tournament trees (max winner).
Here is my header:
// file winner.h
#ifndef WinnerTree_
#define WinnerTree_
#include <iostream>
#include <stdlib.h>
#include "xcept.h"
using namespace std;
template<class T>
class WinnerTree {
public:
WinnerTree(int TreeSize = 10);
~WinnerTree() {delete [] t;}
void Initialize(T a[], int size, int (&winner)(T a[], int player1, int player2));
int Winner()
{return (n) ? t[1] : 0;}
int Winner(int i)
{return (i < n) ? t[i] : 0;}
void RePlay(int i, int (&winner)(T a[], int player1, int player2));
void Output();
private:
int MaxSize;
int n; // current size
int LowExt; // lowest-level external nodes
int offset; // 2^k - 1
int *t; // array for winner tree
T *e; // element array
void Play(int p, int lc, int rc, int (&winner)(T a[], int player1, int player2));
};
template<class T>
WinnerTree<T>::WinnerTree(int TreeSize)
{// Constructor for winner tree.
MaxSize = TreeSize;
t = new int[MaxSize];
n = 0;
}
template<class T>
void WinnerTree<T>::Initialize(T a[], int size, int (&winner)(T a[], int player1, int player2))
{// Initialize winner t for array a.
if (size > MaxSize || size < 2)
throw BadInput();
n = size;
e = a;
// compute s = 2^log (n-1)
int i, s;
for (s = 1; 2*s <= n-1; s += s);
LowExt = 2*(n-s);
offset = 2*s-1;
// play matches for lowest-level external nodes
for (i = 2; i <= LowExt; i += 2)
Play((offset+i)/2, i-1, i, winner);
// handle remaining external nodes
if (n % 2) {// special case for odd n, play
// internal and external node
Play(n/2, t[n-1], LowExt+1, winner);
i = LowExt+3;}
else
i = LowExt+2;
// i is left-most remaining external node
for (; i <= n; i += 2)
Play((i-LowExt+n-1)/2, i-1, i, winner);
}
template<class T>
void WinnerTree<T>::Play(int p, int lc, int rc, int (&winner)(T a[], int player1, int player2))
{// Play matches beginning at t[p].
// lc and rc are the children of t[p].
t[p] = winner(e, lc, rc);
// more matches possible if at right child
while (p > 1 && p % 2) {// at a right child
t[p/2] = winner(e, t[p-1], t[p]);
p /= 2; // go to parent
}
}
template<class T>
void WinnerTree<T>::RePlay(int i, int(&winner)(T a[], int player1, int player2))
{// Replay matches for element i.
if (i <= 0 || i > n)
throw OutOfBounds();
int p, // match node
lc, // left child of p
rc; // right child of p
// find first match node and its children
if (i <= LowExt) {// begin at lowest level
p = (offset + i)/2;
lc = 2*p - offset; // left child of p
rc = lc+1;}
else {
p = (i-LowExt+n-1)/2;
if (2*p == n-1) {
lc = t[2*p];
rc = i;}
else {
lc = 2*p - n + 1 + LowExt;
rc = lc+1;}
}
t[p] = winner(e, lc, rc);
// play remaining matches
p /= 2; // move to parent
for (; p >= 1; p /= 2)
t[p] = winner(e, t[2*p], t[2*p+1]);
}
template<class T>
void WinnerTree<T>::Output()
{
cout << "size = "<< n << " LowExt = " << LowExt
<< " Offset = " << offset << endl;
cout << "Winner tree pointers are" << endl;
for (int i = 1; i < n; i++)
cout << t[i] << ' ';
cout << endl;
}
#endif
This is my exception file:
#ifndef Xcept_
#define Xcept_
#include <exception>
#include <new.h>
// bad initializers
class BadInitializers {
public:
BadInitializers() {}
};
// insufficient memory
class NoMem {
public:
NoMem() {}
};
// change new to throw NoMem instead of xalloc
void my_new_handler()
{
throw NoMem();
};
new_handler Old_Handler_ = set_new_handler(my_new_handler);
// improper array, find, insert, or delete index
// or deletion from empty structure
class OutOfBounds {
public:
OutOfBounds() {}
};
// use when operands should have matching size
class SizeMismatch {
public:
SizeMismatch() {}
};
// use when zero was expected
class MustBeZero {
public:
MustBeZero() {}
};
// use when zero was expected
class BadInput {
public:
BadInput() {}
};
#endif
And this is my main function:
// First fit bin packing
#include "stdafx.h"
using namespace std;
#include <iostream>
#include "winner.h"
int winner(int a[], int player1, int player2)
{// For a max winner tree.
if (a[player1] >= a[player2])
return player1;
return player2;
}
void FirstFitPack(int s[], int n, int c)
{// Output first fit packing into bins of size c.
// n is the number of objects and s[] their size.
WinnerTree<int> *W = new WinnerTree<int>(n);
int *avail = new int[n + 1]; // bins
// initialize n bins and winner tree
for (int i = 1; i <= n; i++)
avail[i] = c; // initial available capacity
W->Initialize(avail, n, winner);
// put objects in bins
for (int i = 1; i <= n; i++) {// put s[i] in a bin
// find first bin with enough capacity
int p = 2; // start search at left child of root
while (p < n) {
int winp = W->Winner(p);
if (avail[winp] < s[i]) // first bin is in
p++; // right subtree
p *= 2; // move to left child
}
int b; // will be set to bin to use
p /= 2; // undo last left child move
if (p < n) {// at a tree node
b = W->Winner(p);
// if b is right child, need to check
// bin b-1. No harm done by checking
// bin b-1 even if b is left child.
if (b > 1 && avail[b - 1] >= s[i])
b--;
}
else // arises when n is odd
b = W->Winner(p / 2);
cout << "Pack object " << i << " in bin "
<< b << endl;
avail[b] -= s[i]; // update avail. capacity
W->RePlay(b, winner);
getchar();
}
}
int main(void)
{
int n, c; // number of objects and bin capacity
cout << "Enter number of objects" << endl;
cin >> n;
if (n < 2) {
cout << "Too few objects" << endl;
exit(1);
}
cout << "Enter bin capacity" << endl;
cin >> c;
int *s = new int[n + 1];
for (int i = 1; i <= n; i++) {
cout << "Enter space requirement of object " << i << endl;
cin >> s[i];
if (s[i] > c) {
cout << "Object too large to fit in a bin" << endl;
exit(1);
}
}
FirstFitPack(s, n, c);
return 0;
}
The exception that I get is:
First-chance exception at 0x0012668D in Bin Packing-FF.exe: 0xC0000005: Access violation reading location 0xF9039464.
I know that I'm getting this exception because of the winner. But I can't understand what I have to change here.
int winner(int a[], int player1, int player2)
{// For a max winner tree.
if (a[player1] >= a[player2])
return player1;
return player2;
}
Also, If I press space or enter after the last input (object) then I don't get the exception and everything is going smoothly. But still I want to know why I'm getting this exception.
Thank you in advance.

heapsort-code is not working

The following code is not working for heap sort. It looks ok to me. Can someone help me please? I have followed the pseudo code from CLRS, the sorted numbers are not being updated after the algorithm is traversed.
#include <iostream>
using namespace std;
void max_heapify(int *b, int i,int he_size)
{
int l,r,largest;
l=2*i;
r=(2*i+1);
if (l<=he_size && b[l]>b[i])
largest=l;
else largest=i;
if (r<=he_size && b[r]> b[largest])
largest=r;
if (largest!=i)
{
swap(b[i],b[largest]);
max_heapify(b,largest,he_size);
}
}
void build_max_heap(int *c,int h_size,int strlength)
{
for (int q=(strlength)/2;q==1;--q)
{
max_heapify(c,q,h_size);
}
}
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
int main()
{
int length;
int heap_size;
cout<<"Enter the number of numbers to be sorted by heap sort"<<endl;
cin>>length;
int* a=NULL;
a=new int[length-1];
int temp;
cout<<"Enter the numbers"<<endl;
for(int i=0;i<length;i++)
{
cin>>temp;
*(a+i)=temp;
}
cout<<"The given numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
heap_size= length;
build_max_heap(a,heap_size,length);
for (int l=length;l==2;--l)
{
swap(a[1],a[length]);
heap_size=heap_size-1;
max_heapify(a,1,heap_size);
}
cout<<"The sorted numbers are:"<<endl;
for(int j=0;j<length;j++)
cout<<*(a+j)<<" "<<endl;
system("pause");
return 0;
}
The number of mistakes in your code is enormous. Sorry to say it.
void swap(int a, int b)
{
int c=b;
b=a;
a=c;
}
does nothing - a and b should be passed by link, not by value:
void swap(int &a, int &b)
{
int c=b;
b=a;
a=c;
}
for (int q=(strlength)/2;q==1;--q) is wrong. You meant for (int q=(strlength)/2;q>1;--q). Your loop is running only when q==1.
a=new int[length-1]; The size of array should be length, not length-1. And even though swap(a[1],a[length]); is wrong, because a[length] is out of array.
Also there are some mistakes in algorithm. I tried to rewrite as less code as possible.
Right code is:
#include <iostream>
using namespace std;
void sift_down(int *a, int start, int end) {
int root = start;
while (root * 2 + 1 <= end) {
int child = root * 2 + 1;
int sw = root;
if (a[sw] < a[child])
sw = child;
if (child + 1 <= end and a[sw] < a[child + 1])
sw = child + 1;
if (sw == root)
return;
else
swap(a[root], a[sw]);
root = sw;
}
}
void max_heapify(int *b, int count) {
int start = (count - 2) / 2;
while (start >= 0) {
sift_down(b, start, count - 1);
--start;
}
}
void swap(int &a, int &b) {
int c = b;
b = a;
a = c;
}
int main() {
int length;
int heap_size;
cout << "Enter the number of numbers to be sorted by heap sort" << endl;
cin >> length;
int *a = new int[length];
cout << "Enter the numbers" << endl;
for (int i = 0; i < length; i++) {
cin >> a[i];
}
cout << "The given numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
heap_size = length;
max_heapify(a, heap_size);
--heap_size;
while (heap_size) {
swap(a[heap_size], a[0]);
--heap_size;
sift_down(a, 0, heap_size);
}
cout << "The sorted numbers are:" << endl;
for (int j = 0; j < length; j++)
cout << a[j] << " ";
cout << endl;
//system("pause");
return 0;
}