How to Set Int Function from Class equal to Int in Main - c++

I have designed functions for getLength, getWidth, and getArea and I need to assign them to int values in my main function but I do not know how.
I have posted my header, implementation, and main.cpp files below.
Please adivse.
Ty.
Header File
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle
{
Rectangle();
public:
int getLength;
int getWidth();
int getArea(int x, int y)
};
#endif
Implementation File
#include "Rectangle.h"
#include <iostream>
using namespace std;
int Rectangle::getLength()
{
int x = 0;
cout << "Enter Length: ";
cin >> x;
return x;
}
int Rectangle::getWidth()
{
int x = 0;
cout << "Enter Width: ";
cin >> x;
return x;
}
int Rectangle::getArea(int x, int y)
{
int area = x * y;
return area;
}
This is where I begin running into issues. The functions return an integer, but I do not know how to be able to assign the return integer to an int value.
#include "Rectangle.h"
#include "Rectangle.cpp"
#include <iostream>
#include <vector>
using namespace std;
int main() {
int area, length, width = 0;
vector <int> myVector;
cout << "Lets Make Some Rectangles: " << endl;
for (int i = 0; i < 5; i++) {
length = Rectangle::getLength();
width = Rectangle::getWidth();
area = Rectangle::getArea(length,width);
myVector.push_back(area);
}
int largest = 0;
for (int i = 0; i < 5; i++) {
if (myVector[i] >= myVector[i + 1]) {
largest = myVector[i];
}
}
cout << "The Largest Rectangle Has an Area of: " << largest;
system("pause");
return 0;
}

One can call the member function in this way Rectangle::getLength(); only when getLength(); is declared static inside class Rectangle.
If member functions are not declared static then they can be accessed via object of the class.
Rectangle obj;
length = obj.getLength();
Also, you are crossing the valid bounds of vector myVector. You have inserted 5 elements in vector (from index 0 to 4) and trying to access 6th element myVector[5] via myVector[i] >= myVector[i + 1] when i = 4.
Correct way to find largest:
int largest = myVector[0];
for (int i = 1; i < myVector.size(); i++) {
if (largest > myVector[i]) {
largest = myVector[i];
}
}

As far as my knowledge with C++ goes, you need to create member variables which will hold the data(width, length), if you need create constructor which will take parameters for those memeber variables:
Rectangle(int width, int length){
m_width = width;
m_length = length;
}
notice member variables m_width and m_length
and create object, which will hold the data using constructor. ie
Rectangle myRectangle = Rectangle(5,5)

Related

Array not producing correct output

I have a problem with assigning variables to an array from different functions. I have two functions that produce different numbers. I then want to assign those numbers to a private array in the same class. When I do this the array returns large negative numbers.
// Array.h
class Array {
private:
int W = A;
int Q = B;
int sum[2] = {W, Q};
public:
int A;
int B;
int num1();
int num2();
int add();
};
// Array.cpp
#include<iostream>
using namespace std;
#include "Array.h"
int Array::num1()
{
int x = 3;
int y = 4;
A = x + y;
cout << A << endl;
return A;
}
int Array::num2()
{
int x = 2;
int y = 5;
B = x + y;
cout << B << endl;
return B;
}
int Array::add()
{
for(int i = 0; i < 2; i++)
{
cout << sum[i] << endl;
}
return 0;
}
// main.cpp
#include <iostream>
#include "Array.h"
int main() {
Array sumTotal;
sumTotal.num1();
sumTotal.num2();
sumTotal.add();
return 0;
}
Problem is here:
int W = A;
int Q = B;
int sum[2] = { W, Q };
You are just coping value from A and B to W and Q.
And later when you set A and B, those changes are not reflected to W or Q.
Thus leaving W and Q uninitialized.
Note: consider researching more about C++ topic in field of arrays, pointers and references.
This is modified code that works ok:
#include <iostream>
using namespace std;
class Array {
private:
int sum[2];
public:
int num1();
int num2();
int add();
};
int Array::num1()
{
int x = 3;
int y = 4;
sum[0] = x + y;
cout << sum[0] << endl;
return sum[0];
}
int Array::num2()
{
int x = 2;
int y = 5;
sum[1] = x + y;
cout << sum[1] << endl;
return sum[1];
}
int Array::add()
{
for (int i = 0; i < 2; i++)
{
cout << sum[i] << endl;
}
return 0;
}
int main(int argc, char** argv)
{
Array sumTotal;
sumTotal.num1();
sumTotal.num2();
sumTotal.add();
return 0;
}
The reason you are getting garbage values (large negative numbers, in your case) is that you are not initializing A or B to any meaningful values, and then you are not updating sum when you call num1, or num2.
You should initialize A and B to something meaningful in the class, or at least default initialize it.
Then you need to update sum in num1, like this:
int Array::num1()
{
int x = 3;
int y = 4;
A = x + y;
sum[0] = A; // <- add this
cout << A << endl;
return A;
}
and do a similar thing inside num2.
You also have 2 variables W, and Q inside your class which don't seem to serve any purpose. Apart from the issue with initializing them incorrectly with garbage values, you don't even need them; you could just use A, and B instead.

Segmentation Fault When Trying to Interact with a 2D Array C++

I'm attempting to interact with a 2D array thorough the Board class. However, I'm getting a segmentation fault when running the main file containing this code:
#include "Board.h"
int main(int argc, char** argv)
{
int height = 0;
int width = 0;
int pop_density = 0.8;
Board* c = new Board(height,width);
c->print();
c->populate(pop_density);
c->print();
//for (i )
cout << c->read_char_at_index(1,2) << endl;
delete c;
return 0;
}
This is the Board.cpp Code:
#include "Board.h"
//in board: make a fucntion that pulls from file
Board::Board(int h, int w)
{
m_height = h;
m_width = w;
m_array = new char* [m_height];
for (int i = 0; i < m_height; ++i)
{
m_array[i] = new char[m_width];
for (int j = 0; j < m_width; ++j)
{
m_array[i][j] = '-';
}
}
cout << "Made board" << endl;
}
Board::~Board()
{
for (int i = 0; i < this->m_height; ++i)
{
delete[] this->m_array[i];
}
delete[] this->m_array;
cout << "Destructed Board" << endl;
}
void Board::print()
{
for (int i = 0; i < this->m_height; ++i)
{
for (int j = 0; j < this->m_width; ++j)
{
cout << this->m_array[i][j] << " ";
}
cout << endl;
}
}
void Board:: populate(double density)
{
//seeding rand with time
srand(time(NULL));
int totalCells = this->m_height * this->m_width;
int cellsToFill = round(totalCells * density);
int cellsFilled = 0;
for (int i = 0; i < cellsToFill; ++i)
{
int randomRow = rand() % this->m_height;
int randomColumn = rand() % this->m_width;
this->m_array[randomRow][randomColumn] = 'X';
}
}
void Board:: write_char_at_index(int height, int width, char z)
{
cout << "pre" << endl;
cout << height << " " << width << endl;
m_array[height][width] = z;
cout << "Wrote" << endl;
}
char Board:: read_char_at_index(int height, int width)
{
return m_array[height][width];
cout << "read" << endl;
}
And the Board.h Code:
#ifndef BOARD_H
#define BOARD_H
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//This class is used to make a Board object
class Board
{
public:
Board(int h, int w);
~Board();
void print(); // Prints the board to cout
void populate(double density); // Populates board based on density input
void write_char_at_index(int height, int width, char z);
char read_char_at_index(int height, int width);
private:
char** m_array; // 2D array dynamically allocated during runtime
int m_height;
int m_width;
};
#endif
Any help or advice would be great, as I've already asked two classmates and they're not sure what the problem is. I know for sure the index I'm trying to assign the char value to is not out of bounds.
The input parameters of read_char_at_index are (1,2) in the main function. However, The Board object c is with height = 0 and width = 0. You can modify the value of height and width to large enough values, such as 10, 10.
int height = 10;
int width = 10;
int pop_density = 0.8;
Board* c = new Board(height, width);
c->print();
c->populate(pop_density);
c->print();
cout << c->read_char_at_index(1, 2) << endl;
The program may run without Segmentation Fault.
Note: The functions "write_char_at_index" and "read_char_at_index" may check the input values (height and width) to ensure the access to m_array member is safe.
if (height >= this->m_height || width >= this->m_width)
{
return;
}

How to build an array of vectors, which can rotate, using C++

So I have written the a code for the lattice that does:
const int Lx = 5, Ly = 5;
const int L = Lx*Ly;
inline void vector_lattice(){
for (int i = 0; i < L+1; i++){
s[i]=0.0;
}
for (int i = 0; i < L; i++){
s[i] =1;
}
}
This was fine for what I was doing, but now I want to have an actual lattice of vectors begin gin at x1,y1 and stoping at x2,y2. But I want to ultimately rotate those vectors 'sin(theta)' or something like that, so I need to have positions like x1,y1,x2 and y2 to plot arrows that represent the directions of all the vector in the lattice, in this case 25 arrows in a lattice 5x5.
Any one knows what I'd need to change to achieve that?
It sounds like you know the physics, but not the programming. I would make a 2-dimensional array, so you can access it like s[x][y] = whatever; However you are asking how to iterate over a 2d array represented in a 1d array, and I can help you there.
All you need is a 1 to 1 mapping of x,y coordinates to the array's index. It doesn't really matter what that mapping is, as long as it is 1to1, but here's an example:
#include <iostream>
#include <vector>
typedef std::pair<double, double> physics_vector;
const int Lx = 5, Ly = 5;
const int L = Lx*Ly;
int get_index(int x, int y) { return y * Ly + x; }
// almost forgot
int get_x(int index) { return index % Lx; }
int get_y(int index) { return index / Lx; }
class lattice : public std::vector< physics_vector >{
public:
lattice() { resize(L); }
};
void iterate_over_lattice(std::vector<physics_vector> &s){
for (int y = 0; y < Ly; y++){
for (int x = 0; x < Lx; x++){
int index = get_index(x, y);
s[index] = physics_vector(1, 0);
std::cout << index << ", ";
}
std::cout << std::endl;
}
}
int main(){
lattice s;
iterate_over_lattice(s);
return 0;
}
You could write a wrapper around a std::vector<std::pair<std::pair<int,int>, std::pair<double,double>>> which represents a lattice site - its co-ordinates and direction respectively in each std::pair. Something similar to below could work well,
#include <iostream>
#include <utility>
#include <vector>
class lattice_sites {
typedef std::vector<std::pair<
std::pair<int,int>,
std::pair<double,double>
>> lattice_vector;
public:
lattice_sites() : _lat_vec() {}
// create a lattice site with given position and direction
void create_site(const std::pair<int,int>& _coords,
const std::pair<double,double>& _drctn) {
_lat_vec.push_back(std::make_pair(_coords, _drctn));
}
// rotate all lattice sites
void rotate_all(const double& _rot_angle) {
for (auto& x : _lat_vec) {
x.second.first = std::cos(_rot_angle); // rotate x-direction
x.second.second = std::sin(_rot_angle); // rotate y-direction
}
}
// write to stream
std::ostream& write(std::ostream& _os) {
for (const auto& x : _lat_vec) {
_os << x.first.first << " " << x.first.second << "\t" // coords
<< x.second.first << " " << x.second.second << "\n"; // direction
}
return _os;
}
private:
lattice_vector _lat_vec;
};
Then you can manipulate instances of this class as follows,
int main(void) {
lattice_sites sites;
const int n = 100;
for (int i = 0; i < n; ++i) {
sites.create_site(std::make_pair(i,i), std::make_pair(0.0,0.0));
}
double rotation_angle = 0.5; // radians
sites.rotate_all(rotation_angle);
sites.write(std::cout);
}
This may require some tweaking (and optimisations such as using resize in the constructor if you already know the size of the lattice), but you should get the gist of it.

C++ How to create two seperate objects that display random numbers 10 times?

The program I am trying to write is to create two objects to display random numbers between 1000-9000 and 100-900 respectively.
I am trying to write my first C++ program that uses classes and multiple files but have issues. I get errors in the for loop in main() function; it says expected primary-expression before 'R' and '<<' for the second for loop too, with 'r'.
Any help or guidance is appreciated :)
main.cpp:
#include <iostream>
#include "Random.h"
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for(int i = 0; i < 10; ++i)
{
cout << RandomNum four(1000,9000); << endl;
}
for(int i = 0; i < 10; ++i)
{
cout << RandomNum three(100,900); << endl;
}
}
Random.h:
#ifndef RANDOM_H
#define RANDOM_H
class RandomNum
{
public:
RandomNum(int ix, int iy);
int operator ()();
int operator ()(int ny);
int operator ()(int nx, int ny);
int x,y;
};
#endif
randomNum.cpp:
#include <iostream>
#include "randomInt.h"
#include <cstdlib>
using namespace std;
RandomInt::RandomInt(int ix, int iy):x(ix), y(iy)
{}
int RandomInt::operator()()
{
return x + rand() % (y - x + 1);
}
int RandomInt::operator()(int ny)
{
return x + rand() % (ny - x + 1);
}
int RandomInt::operator()(int nx, int ny)
{
return nx + rand() % (ny - nx + 1);
}
THE PROBLEM
You cannot declare a variable in the middle of an expression, and the following is all sort of wrong.
cout << RandomNum four(1000,9000); << endl;
cout << RandomNum three(100,900); << endl;
THE SOLUTION
Change the contents of main to first declare four and three to be instances of type RandomNum and initialize them as you want, then later call their operator() inside the cout-expressions.
RandomNum four (1000,9000); // declaration of `four`
RandomNum three (100, 900); // declaration of `three`
cout << four () << endl;
cout << three () << endl;

Errors implementing a dynamic matrix class

Alright, I'm trying to implement a simple 2D matrix class right now. This is what it looks like so far:
template <typename Type>
class dyMatrix {
private:
Type *mat;
int width, height;
int length;
public:
dyMatrix (int _width, int _height)
: width(_width), height(_height), mat(0)
{
length = width * height;
mat = new Type[length];
};
// ---
int getWidth() {
return width;
};
int getHeight() {
return height;
};
int getLength() {
return length;
}
// ---
Type& operator() (int i, int j) {
return mat[j * width + i];
};
Type& operator() (int i) {
return mat[i];
};
// ---
~dyMatrix() {
delete[] mat;
};
};
To test it, and compare with static multi-dimensional arrays, I wrote the following snippet of code:
#include <iostream>
using namespace std;
/* matrix class goes here */
struct Coord {
int x, y;
Coord()
: x(0), y(0)
{};
Coord (int _x, int _y)
: x(_x), y(_y)
{};
void print() {
cout << x << ", " << y;
};
};
int main() {
dyMatrix<Coord> adabo(5, 7);
Coord inakos[5][7];
int i = 5, j = 0;
adabo(i, j) = *(new Coord(i, j));
inakos[i][j] = *(new Coord(i, j));
inakos[i][j].print();
adabo(i, j).print();
return 0;
}
"Adabo" and "Inakos" being arbitrarily chosen names. Upon execution, inakos prints its contents but the program crashes before adabo can do anything. Another interesting thing is that, if I give i and j values other than 5 and 0, like 5 and 1, respectively, it works fine.
I don't know what exact numbers work and which make the program go haywire, I only know that there's a irregularity here. What am I possibly doing wrong? I'm an amateur at C++, so I may or not have misused something in any of the structures.
If anyone also has the time, I'd very much like to know if there's any other error of notice in my matrix class. Anything that's not possibly related to the problem, but is a fallacy nevertheless.
I've also tested it with the following main(), but it still crashes after inakos prints its contents in [5][1]. Maybe it has to do not with dyMatrix, but a loosely-implemented Coord?
int main() {
dyMatrix<Coord> adabo(5, 7);
Coord inakos[5][7];
for (int i = 0; i < adabo.getHeight(); i++) {
for (int j = 0; j < adabo.getWidth(); j++) {
adabo(i, j) = *(new Coord(i, j));
inakos[i][j] = *(new Coord(i, j));
inakos[i][j].print();
cout << "; ";
}
cout << "\n\n";
}
cout << "\n\n\n";
Coord temp;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 5; j++) {
temp = adabo(i, j);
temp.print();
cout << "; ";
}
cout << "\n\n";
}
return 0;
}
edit: It hasn't to do with Coord. Just tested with a dyMatrix of ints and static matrix of ints, and it crashes after [5][0] nevertheless.
In your first example, you declared inakos[5][7] so the indices range from 0 to 4 and 0 to 6. inakos[5][0] and inakos[5][1] could therefore crash.
In your second example, you again declare inakos[5][7] yet you let the first index loop from 0 to 6. Again inakos[i][j] can crash. One fix is to switch your indices (ie, change to i<adabo.getWidth() and j<adabo.getHeight()).