Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter, and display binary representation of number - c++11

Write a program using stack operations, which accepts a non-negative base 10 integer as a parameter, and display binary representation of number. I am getting error in my main that been trying to understand but no success so far , rest all the logic works but adding the remainder (node r) function is primarily the issue
and code is :
# include<iostream>
using namespace std;
class ListStack{
private:
struct node
{
int num;
node *next;
}*top;
public:
ListStack()
{
top= NULL;
}
void push(node n);
void pop();
void display();
};
void ListStack::push(node n)
{
node *newNode;
newNode= new node;
// cout<<"Enter number to add on stack";
// cin>>newNode->num;
newNode->num;
newNode->next=top;
top=newNode;
}
void ListStack::display()
{
node *n;
n= new node;
n=top;
while(n!=NULL){
cout << n->num<<" ";
n= n-> next;
}
}
int main(){
ListStack l;
int a;
cout<<"Enter a digit with base 10 : ";
cin>>a;
cout<<"\nbinary of entered num is : \n";
node *r;
r= new node;
while(a!=0){
a%2=r->num;
push(r);
cout<<r->num;
a/=2;
}
}

Related

What is segmentation fault. How to deal with it [duplicate]

This question already has answers here:
What is a segmentation fault?
(17 answers)
Closed 2 years ago.
Problem:
A student signed up for workshops and wants to attend the maximum
number of workshops where no two workshops overlap. You must do the
following: Implement structures:
struct Workshop having the following members: The workshop's start time. The workshop's duration. The workshop's end time.
struct Available_Workshops having the following members: An integer, (the number of workshops the student signed up for). An
array of type Workshop array having size . Implement functions:
Available_Workshops* initialize (int start_time[], int duration[], int n) Creates an Available_Workshops object and
initializes its elements using the elements in the and parameters
(both are of size ). Here, and are the respective start time and
duration for the workshop. This function must return a pointer to
an Available_Workshops object.
int CalculateMaxWorkshops(Available_Workshops* ptr) Returns the maximum number of workshops the student can attend—without overlap.
The next workshop cannot be attended until the previous workshop
ends. Note: An array of unkown size ( ) should be declared as
follows: DataType* arrayName = new DataType[n];
Your initialize function must return a pointer to an
Available_Workshops object. Your CalculateMaxWorkshops function
must return maximum number of non-overlapping workshops the student
can attend.
Sample Input
6
1 3 0 5 5 8
1 1 6 2 4 1
Sample Output
4
Explanation The first line denotes , the number of workshops. The next line contains space-separated integers where the integer
is the workshop's start time. The next line contains
space-separated integers where the integer is the workshop's
duration. The student can attend the workshops and without
overlap, so CalculateMaxWorkshops returns to main (which then
prints to stdout).
MY CODE:
#include <iostream>
using namespace std;
class Workshop{
public:
int start_time{},duration{},end_time{};};
class Available_Workshops
{
public:
int n{};
struct Workshop*arr=new struct Workshop[n];
~Available_Workshops()
{
delete [] arr;
}
void arr_sort();
void arr_delete(int i);
};
////////////////////////////////////////////////////////////////////////////////////////////
Available_Workshops * initialize(int start_time[],int duration[],int n)
{
Available_Workshops * x=new Available_Workshops{};
x->n=n;
for(int i=0;i<n;i++)
{
x->arr[i].start_time=start_time[i];
x->arr[i].duration=duration[i];
x->arr[i].end_time=start_time[i]+duration[i];
}
return x;
}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_delete(int i)
{
n-=1;
for(int j=i;j<n;j++)
{
arr[j]=arr[j+1];
}
}
///////////////////////////////////////////////////////////////////////////////////////////
void Available_Workshops:: arr_sort()
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[i].start_time>arr[j].start_time)
{
struct Workshop temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int CalculateMaxWorkshops(Available_Workshops * x)
{
x->arr_sort();
for(int i=0;i<x->n-1;i++)
{
for(int j=i+1;j<x->n;j++)
{
if(x->arr[i].end_time>x->arr[j].start_time)
{
if(x->arr[i].duration>=x->arr[j].duration)
x->arr_delete(i);
else x->arr_delete(j);
j--;
}
}
}
int y=x->n;
delete x;
return y;
}
int main(int argc, char *argv[]) {
int n; // number of workshops
cin >> n;
// create arrays of unknown size n
int* start_time = new int[n];
int* duration = new int[n];
for(int i=0; i < n; i++){
cin >> start_time[i];
}
for(int i = 0; i < n; i++){
cin >> duration[i];
}
Available_Workshops * ptr;
ptr = initialize(start_time,duration, n);
cout << CalculateMaxWorkshops(ptr) << endl;
return 0;
}
My code is not running. It has segmentation fault. Please help me find this error
You bug can be seen from the class declaration:
class Available_Workshops
{
public:
int n{};
struct Workshop* arr = new struct Workshop[n];
~Available_Workshops()
{
delete[] arr;
}
void arr_sort();
void arr_delete(int i);
};
Member n gets explicitly initialized to 0. Yet, your initialize function will happily fill in more elements into arr (an array of zero elements) and cause all kinds of undefined behavior.
You really, really want a proper constructor for your class instead of trying to inline initialize the members.
Available_Workshops(int size) :
n(size)
{
arr = new Workshop[n];
}
Another issue, although not related to your crash is inside your arr_delete function.
for (int j = i; j < n; j++)
{
arr[j] = arr[j + 1];
}
When j == n-1 on the last iteration of the loop, it will execute arr[n-1] = arr[n]. Accesing arr[n] is undefined behavior since the only valid indices in the array are from [0..n-1]

How to fix "segmentation fault (core dumped)" dependant on size

I created a class "config" that contains 12 bool values, organized in a std::array. The class has an "icing" function that returns a double value.
Trying to order a vector of 2^12 (4096) configs through a std:: sort (contained in #include ) using a predicate i have written, i get a segmentation fault error.
Shrinking the vector to 205 (not 1 more) eliminates the error, but I don't know why.
If i make the vector 4096 long, and try to sort only a little part, it works until the part is long 175+.
Shrinking the vector to for example around 1000, limits the partial sorting to around 20, before it gives the segmentation error.
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class config {
public:
config (){ //constructor, default
array<bool,12> t;
for (bool& b: t){
b=false;
}
val=t;
g=1;
}
config (const config& fro): val(fro.val){}; //copy constructor
array<bool,12> get_val(){ return val; } //returns the array
void set_tf(int n, bool tf){ val[n]=tf; } //sets a certain boolean in the array to false/true
void set_g(double d){ g=d; } //this sets the constant for calculation to a number
void print(){
cout<<"values: ";
for (auto b: val){ cout<<b<<" "; }
cout<<endl;
}
config & incr(int n=1){ //this increases the vector by 1 following the rules for binary numbers, but has the digits reversed
for(int j=0; j<n; j++){
int i=0;
bool out=false;
while(val[i]==true){
val[i]=false;
i++;
}
val[i]=true;
}
return *this;
}
double energy(){
int ct=0;
int cf=0;
for(auto b:val){ if(b==true){ ct++; } else { cf++; } }
return (abs(ct-cf));
}
double icing(){ //here is the "value" for ordering purposes
int n=0;
for(int i=0; i<11; i++){
if(val[i]!=val[i+1]){ n++; }
}
double temp=-g*n+this->energy();
return temp;
}
private:
array<bool,12> val;
double g;
};
bool pred (config c1, config c2){ return c1.icing()>c2.icing(); } //this sets the ordering predicate
template <typename T> //this orders the vector
void csort (vector <T>& in){
sort(in.begin(), in.end(), pred);
}
int main(){
vector<config> v;
for (int i=0; i<4096; i++){ //cicle that creates a vector of successive binaries
for(auto& c:v){
c.incr();
}
config t;
v.push_back(t);
}
sort(v.begin(), v.begin()+174, pred); //this gives seg.fault when 175+
csort(v); //this gives segmentation fault when the vec is 206 long or longer
}
I expected the code to order the vector, but it goes into segmentation fault.
Your program has undefined behaviour in sort function because your predicate takes config by value, so copies are made and in this place copy constructor is called which copies only array val, but not g.
bool pred (config c1, config c2){ return c1.icing()>c2.icing(); }
// takes by value, copy ctor is called
config (const config& fro): val(fro.val){}; // only val is copied, g HAS GARBAGE VALUE
// icing in pred uses g !! - stric weak ordering is violated because g has GARBAGE VALUE
Fix 1:
pass config by const config&:
bool pred (const config& c1, const config& c2){ return c1.icing()>c2.icing(); }
or fix 2:
g is initialized in copy constructor:
config (const config& fro): val(fro.val), g(fro.g){};

Initializing a doubly linked list from array parameters

C++ noob reporting in. I'm trying to write a function that will create and initialize a doubly linked list using values that are stored in two different arrays. Here's how my linked list class is set up:
class node {
public:
node *prev;
node *next;
int key;
char type;
};
and here's how my dList class (containing various functions to alter my linked list) is set up:
class dList {
private:
node *head; // dummy head
node *tail; // dummy tail
public:
dList() { // default constructor, creates empty list
head = tail = NULL;
}
~dList() { // deconstructor
node *ptr = head;
while (head != NULL) {
head = head->next;
delete ptr;
}
tail = NULL;
}
dList(int arrayNums[], char arrayChars[], int size); // parametrized constructor, initialize list w/ contents of arrays
void addFront(int k, char t); // creates new node at front of list
void addBack(int k, char t); // creates new node at back of list
node *search(int k); // searches list for occurence of int parameter and returns pointer to node containing key
void find(char t); // outputs all keys that have type equal to character parameter, front to back
void moveFront(node* ptr); // moves node pointed to by parameter to front of list
void moveBack(node* ptr); // moves node pointed to by parameter to back of list
void out(int num, char = 'f'); // outputs first int elements of list, starting at front or back depending on char parameter
void sort(); // peforms a quick or mergesort on items; list should be in increasing order based on integer key
};
I need help implementing my parametrized constructor. Could someone tell me if the function I have now is written correctly? I think it is, but when I run my program, it runs forever--a clear problem. Here's my function as-is:
dList::dList(int arrayNums[], char arrayChars[], int size) {
node *newNode = NULL;
for (int i = 0; i < size; i++) {
if (head == NULL) {
newNode = new node;
newNode->key = arrayNums[i];
newNode->type = arrayChars[i];
newNode->prev = NULL;
newNode->next = NULL;
head = newNode;
tail = newNode;
}
else { // needs work!
newNode = new node;
newNode->key = arrayNums[i];
newNode->type = arrayChars[i];
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
if (i == (size - 1)) {
tail->next = NULL;
}
}
}
Thank you very much!
EDIT: here is my main.cpp (code I'm using to test my dList.cpp file)
#include <iostream>
using namespace std;
#include "dList.cpp"
#define SMALL 200
#define MAX 100000
#define ROUNDS 100
int main(){
int i, x[MAX];
char ch[MAX];
for(i=0;i<SMALL;i++) {
x[i] = 2 * (SMALL - i);
ch[i] = 'a' + (i % 26);
}
dList A(x,ch,SMALL), B;
A.out(10);
node *tmp = A.search(2*SMALL-8);
A.moveFront(tmp);
A.out(10);
A.moveBack(tmp);
A.out(10);
A.find('b');
A.sort();
A.out(10);
A.out(10,'b');
A.addBack(500,'d');
A.addFront(501,'z');
A.out(10);
A.out(10,'b');
B.addFront(1,'a');
B.addBack(2,'b');
B.out(2);
for(int j=0; j<ROUNDS; j++){
cout << endl << "round " << j << endl;
for(i=0;i<MAX;i++) {x[i] = 2*MAX-i; ch[i] = 'a'+ (i%26);}
dList A(x,ch,MAX);
node *tmp = A.search(2*MAX-8);
A.moveFront(tmp);
A.moveBack(tmp);
A.sort();
A.out(10);
A.out(10,'b');
}
}

How to traverse a connected node network in a connected manner?

I have data structure that can be visualized as a connected network such as this:
I believe (without proof) that it should be possible to traverse all nodes, always moving from one node to a connected node (backtracking is of course required and allowed - as you would have done with a tree structure). How to do it?
The data structure may be written in pseudo-code as:
node[N] nodes; // the network as an array of N nodes
class node {
List<pt_to_node> friend_nodes; // a list of pointers to connected nodes
}
You can simply implement the graph with a stack for Depth First Search or a queue for Breadth First Search
e.g.
Assume that we're going to start with Node 1,
#include <vector>
#include <list>
#include <vector>
using namespace std;
class Graph
{
public:
int vert; //number of vertices
vector<list<int>> adj;
Graph(int _v)
{
adj.resize(_v);
vert = _v;
}
void addEdge(int v, int key)
{
adj[v].push_back(key);
adj[key].push_back(v); // comment out if undirected
}
void bfs(int start);
void dfs(int start);
};
void Graph::bfs(int start)
{
vector<bool> visited(vert,false);
list<int> queue;
visited[start] = true; // visit the first node
queue.push_back(start);
while (!queue.empty())
{
start = queue.front();
cout << start << " ";
queue.pop_front();
for (auto i = adj[start].begin(); i != adj[start].end(); ++i)
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
cout << endl;
}
void Graph::dfs(int start)
{
vector<bool> visited(vert,false);
vector<int> stack;
visited[start] = true;
stack.push_back(start);
while (!stack.empty())
{
start = stack.back();
cout << start << " ";
stack.pop_back();
for (auto i = adj[start].begin(); i != adj[start].end(); ++i)
if (!visited[*i])
{
visited[*i] = true;
stack.push_back(*i);
}
}
cout << endl;
}
int main()
{
Graph g(6); // number of vertices we need
g.addEdge(1, 4);
g.addEdge(4, 2);
g.addEdge(4, 5);
g.addEdge(2, 5);
g.addEdge(5, 3);
g.bfs(1); // start with 1
g.dfs(1);
}
The results are DFS : 1 4 2 5 3 and BFS 1 4 5 3 2.
However, in the real network, each edge has a weight value that means distance or speed of the edge.

how i can pass array argument to C++ function

I want to pass an array from one object, store reference and then work with this array inside my function, but...
I have a terrible misunderstanding of passing an array process: In the class TreeType.
I’m facing with an error and I have tried to resolve that for 3 days, but I couldn’t.
Function:
void AddElements(TreeType& tree, int info[], int fromIndex, int toIndex)
{
int midIndex;
if (fromIndex <= toIndex)
{
midIndex = (fromIndex + toIndex) / 2;
tree.PutItem(info[midIndex]);
AddElements(tree, info, fromIndex, midIndex - 1);
// Complete the left subtree.
AddElements(tree, info, midIndex+1, toIndex);
// Complete the right subtree.
}
}
void MakeTree(TreeType& tree, int info[], int length)
// Creates a binary tree from a sorted array.
{
tree.MakeEmpty();
int arrayb[length];
for(int i = 0; i < length; i++)
{
cout << "Enter Value to make tree:" << endl;
cin >> arrayb[i];
}
AddElements(tree, info, 0, length-1);
}
And invoked in main.cpp.
else if (command == "MakeTree")
{
int length=25;
//int arrayb[length];
int arrayb[]={-1000,-967,-923,-844,-669,-567,-455,-267,-209,-183,-59,-23,68,132,159,170,222,228,233,241,389,479,824,939,985};
tree.MakeTree(tree,arrayb,length);
Error capture

Resources