Array not producing correct output - c++

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.

Related

Passing by reference in C++ function

I am writing a simple program to calculate 6^5 using a function. Here's my code
#include <iostream>
using namespace std;
int raiseToPower(int &base, int exponent){
for (int i = 1; i < exponent; i = i + 1){
base= base * base;
}
return base;
}
int main() {
int base = 6;
cout << "6^5 is " << raiseToPower(base, 5)<< endl;
return 0;
}
The result is
6^5 is -683606016
instead of 7776
Can you guys explain to me why I got this result?
I am not looking for another way to write this code. I know there are simpler ways but I am trying to understand what went wrong
Why are you using pass by reference. Setting as much const as possible reduces the odd of making mistakes:
#include <iostream>
using namespace std;
int raiseToPower(const int base, const int exponent) {
int result = base;
for (int i = 1; i < exponent; i = i + 1){
result = result * base;
}
return result;
}
int main() {
int base = 6;
cout << "6^5 is " << raiseToPower(base, 5)<< endl;
return 0;
}
If it has to be pass by reference you could do this:
#include <iostream>
using namespace std;
void raiseToPower(const int base,
const int exponent,
int &result)
{
result = base;
for (int i = 1; i < exponent; i = i + 1){
result = result * base;
}
}
int main() {
int base = 6;
int result;
raiseToPower(base, 5, result);
cout << "6^5 is " << result << endl;
return 0;
}
Your calculation is incorrect. The value of variable base should not change. Try this:
int raiseToPower(int &base, int exponent){
int result = 1;
for (int i = 1; i <= exponent; i = i + 1){
result = result * base;
}
return result;
}
You probably want your loop like this:
int result = 1;
for (int i = 0; i < exponent; i = i + 1) {
result = result * base;
}
return result;
Also, you are taking your base parameter to raiseToPower by reference - which means you are changing the base variable in main - probably not what you want to do.
Let's consider this loop
for (int i = 1; i < exponent; i = i + 1){
base= base * base;
}
After the first iteration when i is equal to 1 you have
base= base * base;
that is the result is base ^ 2.
When i = 2 you have
base= base^2 * base^2;
that is the result is base^4.
When i is equal to 3 you have
base= base^4 * base^4;
that is the result is base^8.
When i is equal to 4 you have
base= base^8 * base^8;
that is the result is base^16.
It seems the resulted value is too big to be accomodated in an object of the type int.
Also it is not a good idea when an argument is passed by reference. And the second parameter should have the type unsigned int.
Here is a demonstrative program that shows how the function can be implemented.
#include <iostream>
long long int raiseToPower( int base, unsigned int exponent )
{
long long int result = 1;
while ( exponent-- )
{
result *= base;
}
return result;
}
int main()
{
int base = 6;
std::cout << "6^5 is " << raiseToPower(base, 5) << std::endl;
return 0;
}
Its output is
6^5 is 7776

I cant seem to assign a pointer an array and then change the contents of the array

I couldn't figure out how to make a function return an array so instead I decided to try and pass an empty array (of the correct size) into my function and than reassign the address to a different array of the same size. Is this at all a way to do things??? Can someone show me what to do? if this is wrong can you fill me in on how to do this?
here is my code:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray,int s, int f){
int *ptrarray = &earray;
int prenum_size = std::abs(s) + f - 1;
int pre_num[prenum_size];
for(int x=s;x<f;x++){
pre_num[x+std::abs(s)] = x;
}
*ptrarray = pre_num;
}
int Main(){
int first = -10;
int second = 15;
int temp[abs(first) + abs(second)];
ArrayFiller(temp, first, second);
int n = sizeof(temp)/sizeof(temp[0]);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
return 0;
}
I think you're looking for something like this:
#include <iostream>
#include <cmath>
using namespace std;
void ArrayFiller(int earray[],int s, int f){
for(int x=s;x<f;x++){
earray[x+(std::abs(s))] = x;
}
}
int main(){
int first = -10;
int second = 15;
int n = abs(first)+abs(second);
int* temp = new int[n];
ArrayFiller(temp, first, second);
for (int i = 0; i < n; i++) {
cout << temp[i] << ' ';
}
delete [] temp;
return 0;
}

Get array from object in c++

This question might be simple but I never use raw pointers or arrays in C++ so...
I need to use a library function which looks like this:
void f(double a[3][3], double b[3], double c[3]);
a and b are used for input and the result is stored in c.
The computation of a is a bit complex but does never change so it makes sense to calculate it only once and save the result. In my program, I can link it to an object of type X.
class X{
public:
X(){
a = {{1,2,3},
{4,5,6},
{7,8,9}};
}
private:
double a[3][3];
}
How can I write a getter for X::a which can be used in function f?
This is how I would like to call function f:
#include "X.h"
int main(int argc, char *argv[]){
X o = X(); //create object
double a[3][3] = o.getA(); // I want to get a somehow
double b[3] = {1,2,3}; // create dummy b
double c[3] = {}; // create empty c
f(a,b,c); // call funktion to populate c
for(int i=0; i<3; ++i){
std::cout << c[i] << endl;
}
}
You know std::vector is the way to go for 2D arrays in C++, but if you can't bypass the obstacle you are facing, then it would be possible to pass the matrix as a parameter to the getter function, like this:
#include <iostream>
class X {
public:
void getA(double (&array)[3][3]) {
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
array[i][j] = a[i][j];
}
private:
double a[3][3] = {{1,2,3},
{4,5,6},
{7,8,9}};
};
int main(void) {
X o = X();
double a[3][3];
o.getA(a);
for(int i = 0; i < 3; ++i)
for(int j = 0; j < 3; ++j)
std::cout << a[i][j] << std::endl;
return 0;
}
This snippet should serve your purpose.
#include <iostream>
#include <string>
using namespace std;
class X {
public:
X() {
}
typedef double (*ptr_matrix)[3];
ptr_matrix getA(){
return a;
}
private:
double a[3][3] = {{ 1,2,3},
{4,5,6},
{7,8,9}};
};
void f(double a[3][3], double b[3], double c[3])
{
cout<<"Inside f function";
for(auto i = 0; i < 3;i++) {
cout<<endl;
for(auto j = 0 ; j < 3;j++)
cout<<a[i][j];
}
}
int main()
{
X o = X(); //create object
double (*a)[3] = NULL;
a = o.getA(); // I want to get a somehow
double b[3] = {0};
double c[3] = {0};
f(a,b,c);
}

How to Set Int Function from Class equal to Int in Main

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)

Getter for dynamic array in c++ not working

I am using a dynamic array from boost in one of my classes and having trouble to write a proper getter function for it. Heres what I tried (I checked the size of the array within the class setter and with the getter from the main function):
#include <iostream>
#include "boost/multi_array.hpp"
using namespace std;
using namespace boost;
typedef multi_array<int, 3> array3i;
class Test {
private:
array3i test_array_;
void init(int x, int y, int z) {
array3i test_array_(extents[x][y][z]);
cout << "Size should be: " << test_array_.size() << endl;
for (int j=0; j<x; j++) {
for (int jj=0; jj<y; jj++) {
for (int jjj=0; jjj<z; jjj++) {
test_array_[j][jj][jjj] = j+jj+jjj;
}
}
}
};
public:
array3i test_array() {return test_array_;};
Test(int x, int y, int z) {
init(x, y, z);
};
};
int main(int argc, const char * argv[]) {
Test test(2,3,5);
cout << "Size from getter: " << test.test_array().size() << endl;
return 0;
}
The getter is working but you didn't initialize the member.
array3i test_array_(extents[x][y][z]);
initializes a local variable (that stops to exist after init() exits).
The problematic part was (likely) that you can't just assign a multi_array of different size/shape. So you need to use resize() (or initialize test_array_ shape in the constructor initializer list).
Live On Coliru
Fixed:
#include <iostream>
#include "boost/multi_array.hpp"
using namespace std;
using namespace boost;
typedef multi_array<int, 3> array3i;
class Test {
private:
array3i test_array_;
void init(int const x, int const y, int const z)
{
test_array_.resize(extents[x][y][z]);
cout << "Size should be: " << test_array_.size() << endl;
for (int j = 0; j < x; j++) {
for (int jj = 0; jj < y; jj++) {
for (int jjj = 0; jjj < z; jjj++) {
test_array_[j][jj][jjj] = j + jj + jjj;
}
}
}
};
public:
array3i test_array() { return test_array_; };
Test(int x, int y, int z) { init(x, y, z); };
};
int main()
{
Test test(2, 3, 5);
cout << "Size from getter: " << test.test_array().size() << endl;
}
The problem is probably that you have two test_array_ variables: One in the class as a class member, one local in the init function.
The local variables shadows, and overrides, the member variable.
In your init function you should be having:
void init(int const x, int const y, int const z)
{
//test_array_.resize(extents[x][y][z]);
test_array_ = array3i(extents[x][y][x]);
cout << "Size should be: " << test_array_.size() << endl;
for (int j = 0; j < x; j++) {
for (int jj = 0; jj < y; jj++) {
for (int jjj = 0; jjj < z; jjj++) {
test_array_[j][jj][jjj] = j + jj + jjj;
}
}
}
}