Using pointers and arrays to solve linear system - c++

I've been assigned a problem that asks us to solve a 2 equation system using an array and a pointer to that array. It's sort of a linear algebra way of going about it, with x_1 = (DE-BF)/(AD - BC) and x_2 = (AF - CE)/(AD - BC). The system is Ax_1 + Bx_2 = C and Dx_1 + Ex_2 = F. My code compiles fine but spits out garbage. Can anyone help me? I'm sure it's an error with my pointers but I don't know how to correct it. Much thanks in advance.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(){
double A,B,C,D,E,F;
cout << "Please enter a value for A: " << endl;
cin >> A;
cout << "Please enter a value for B: " << endl;
cin >> B;
cout << "Please enter a value for C: " << endl;
cin >> C;
cout << "Please enter a value for D: " << endl;
cin >> D;
cout << "Please enter a value for E: " << endl;
cin >> E;
cout << "Please enter a value for F: " << endl;
cin >> F;
double paramarray[6] = {A,B,C,D,E,F};
double* p;
p = &paramarray[6];
double x1 = (p[3]*p[4] - p[1]*p[5])/(p[0]*p[3] - p[1]*p[2]);
double x2 = (p[0]*p[5] - p[2]*p[4])/(p[0]*p[3] - p[1]*p[2]);
cout << "X_1 = " << x1 << endl;
cout << "X_2 = " << x2 << endl;
int f;
cin >> f;
return 0;
}

p = &paramarray[6];
This is the problem. This means you are assigning the address of paramarray[6] to p. paramarray[6] is not defined and you are trying to access out of bounds array.
Try changing it to
p = paramarray;
Also, it will be better if you first check for zero denominator and update your equation accordingly.

Your pointer should be initialized with the base of the array which is the address of the first element. And in your program you are initializing it to a address out of bounds which is the index 6 where the last index of the array is 5 itself.
An array of size six means the first index is 0 and the last index is 5.
so change your line:
p = &paramarray[6];
to
p = paramarray; //or p=&paramarray[0].Both are same here
This above line will store the address of the first element in pointer p.

Related

C++ : How to use a pointer in an if statement condition

I am writing a program that takes in 3 user inputted values for a quadratic equation, does some calculation, and returns how many roots the quadratic has.
When I print *(point), it gives me the correct value from the function.
However, when I use *(point) in the If conditions, it does not seem to work the way I want it to - I believe that *(point)is always some positive number, hence why it always executing that specific if condition.
The user values: a = 9, b = -12, c = 4 should print out This quadratic has 1 root. and the values: a = 2, b = 16, c = 33 should print out This quadratic has 2 roots. BUT the program always prints out This quadratic has 0 roots. no matter what the values entered.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
float *quadratic(float a1[]);
int main()
{
float a1[3] = {};
float *point;
cout << "Enter a: ";
cin >> a1[0];
cout << "\nEnter b: ";
cin >> a1[1];
cout << "\nEnter c: ";
cin >> a1[2];
point = quadratic(a1);
cout << endl << "d = " << *(point) << endl;
if (*(point) < 0) {
cout << "\nThis quadratic has 2 roots.\n";
}
else if (*(point) > 0) {
cout << "\nThis quadratic has 0 roots.\n";
}
else { //else if *(point) is equal to 0
cout << "\nThis quadratic has 1 root.\n";
}
return 0;
}
float *quadratic(float a1[]) {
float d;
d = (a1[1] * a1[1]) - (4 * a1[0] * a1[2]);
float xyz[1] = { d };
return xyz;
}
Your function quadratic returns a pointer to a local array. After the function return that array doesn't exist anymore. The pointer is then a dangling pointer, a pointer pointing to a place in memory that has once held an object, but that now may hold anything or just rubbish.
Since the array that quadratic attempts to return is always one value there is no need for returning an array. Just return that value.
You don't even need to deal with arrays for the polynomial's coefficients, since they're always three, but if array seems better than individual a, b and c variables, then just use std::array, e.g. like this:
#include <iostream>
#include <array>
#include <vector>
using namespace std;
using Float = double;
auto square_of( Float const v ) -> Float { return v*v; }
auto determinant( array<Float, 3> const& a )
-> Float
{
return square_of( a[1] ) - 4*a[0]*a[2];
}
auto main()
-> int
{
array<Float, 3> a;
cout << "Enter A: "; cin >> a[0];
cout << "Enter B: "; cin >> a[1];
cout << "Enter C: "; cin >> a[2];
Float const d = determinant( a );
cout << "d = " << d << endl;
if( d < 0 )
{
cout << "This quadratic has 2 roots." << endl;
}
else if( d > 0 )
{
cout << "This quadratic has 0 roots." << endl;
}
else // d == 0
{
cout << "This quadratic has 1 root.";
}
}
The code above is equivalent to what I perceived as the intent of your code.
However, I'd check out the formula for roots of quadratic equations, and test the program, before handing in something.

Not able to figure out what is happening with the universal array

I have created a program which takes an equation. from the user by asking about the degree of the equation. and then taking the co-efficients from the user and then forming the function which results into an equation. and then I have used the bisection method to solve it.
The program is::
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
int stop=0,d,t[]={1};
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
int *t = new int[d+1];
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
return sum;
}
int main()
{
float a , b , c , i , j ;
A:
cout << " Enter the starting point of interval " <<endl;
cin >> a ;
cout << " Enter the end point of interval " << endl;
cin >> b ;
cout << " Enter the number of iterations to be done . ( More the iterations , accurate is the result ) " << endl;
cin >> i ;
for(j=0;j<i;j++)
{
if(f(a)*f(b)>0)
{
cout << " The root of the above polynomial does not lies in the given interval . TRY AGAIN " << endl;
goto A;
}
else
{
c = a + b ;
c = c / 2 ;
if (f(a)*f(c)>0) a = c ;
else b = c ;
cout <<"hello"<< a << "aa \t" << b << "\t" << c << endl;
}
}
cout << "Root = "<< c <<endl;
}
When the user gives the value of degree it creates an array of size one more than degree is created then there is a for loop which takes the value of co-efficients in that array . The problem is the value of the array stays intact till the first for loop . but as the control proceeds to the second loop ( see the two comments ) the value of the array is gone...I am using CodeLite ...guys help me?????
To solve the array issue you just need to make a few small changes.
int stop=0,d,*t; // Declare an uninitialized pointer to int
float f(float x)
{
int loop,loopa;
float add=0.0,sum=0.0;
for(;stop==0;)
{
int p ;
cout << "Enter the degree of the poly. eq. (+ve integer)" << endl;
cin >> d ;
t = new int[d+1]; // Remove the int and asterix before t. You want to assign the new array to the pointer, not the value the pointer is pointing to.
cout << "The eq. will be in the form of ax^"<<d<<"+bx^"<<(d-1)<<" and so on ." ;
p = 97 + d ;
for(loop=d;loop>=0;loop--)
{
cout << "Enter the value of " << char(p-loop) << endl;
cin >> t[loop];
cout << "a="<<t[loop]<<endl;
}
stop=1; //ARRAY IS STILL THERE WHY/////
} for(loop=0;loop<=d;loop++) cout<<"out="<<t[loop]<<endl;
//ARRAY IS GONE TILL NOW//
cout<<"d="<<d<<endl;
for(loopa=d;loopa>=0;loopa--)
{
cout<<"loopa="<<loopa<<"value="<<t[loopa]<<endl;
add = t[loopa] * pow(x,loopa);
sum=sum+add;
}
delete[] t; // All new'ed things need to be deleted to not cause a leak. Delete it here since it is no longer needed.
return sum;
}
Please note that even if this works, it is not advised to use raw pointers in C++. Better to use an std::array<int> or std::vector<int> so you don't have to take care of the allocating and deleting of memory.
EDIT: Accidentaly left the int in fron of t. Changed now.

Code won't cin/ uninitialized local variable

So far my only problem with this code is that C won't initialize. I know that if I make degree_type == "C" it won't compile because I can't turn an int into a character. What's exactly wrong with this code?
#include <iostream>
using namespace std;
int main()
{
char C;
double degree;
int degree_type;
cout << "What's the Degree type?: ";
cin >> degree_type;
if (degree_type == C)
{
cout << "What's the Temperature:? ";
cin >> degree;
cout << "Your Degrees in Celsius is, " << 9 / 5 * degree + 32 << " degrees fahrenheit." << endl;
}
else
{
cout << "What's the Temperature:? ";
cin >> degree;
cout << "Your Degrees in Fahrenhait is, " << (degree - 32) * 5 / 9 << " degrees Celsius." << endl;
}
return 0;
}
You are (or were, before you changed your question) using cin to read a character. When you read one character, the next character (the Enter keypress) remains in the input buffer waiting to be read. The next time you read from cin (to get the temperature), it will immediately see the Enter keypress from the previous input and not let you type anything.
Use getline instead:
std::string str;
std::getline(std::cin, str);
degree_type = str.at(0);
Once you have done that, the test degree_type = C does not do what you think it does for two reasons:
The single equals = is assignment. For comparison, use ==.
The C is the name of a variable. For the character C, use 'C'.

Why does this code produce strange, unexpected output?

Why am I not getting a proper result?
I don't get a proper output of px although I have it named as a double I am getting some freaking number-text mashup as a result.
#include <iostream>
using namespace std;
int main(){
double a = 0; double b = 0; double c = 0; double x = 0;
cout << "Welcome to Lytis! \nPlease enter a:";
cin >> a;
cout << "Please enter b:";
cin >> b;
cout << "Please enter c:";
cin >> c;
if (a != 0){
double d = (b*b) - (4 * a * c);
}
f (d == 0){
double x = -(b) / (2 * a);
double *px = &x;
cout << "The only solution is x=" << px;
cin.get();
}
What am I missing?
1) Your code does not compile (e.g. d is not declared)
2) The "number-text meshup" is the address of x (the pointer) that you are printing out.
Use the dereference operator * to get the value pointed to :
cout << "The only solution is x=" << *px;
^^^
Here
3) You should check the return value of cin to be safe against wrong inputs.
4) "Lytis" means "Sex" in Lithuanian.
It appears px is of type double *, so outputting it as such is printing out a memory location (usually expressed in hexadecimal, i.e. 0-9 A-F ).
The assignment double *px = &x is legit, as it is assigning a reference (memory location) to a pointer, but when you output a pointer with cout it will display its location.
Maybe try:
cout << "The only so....." << *px;

C++ Structs Not Compiling... Not Initialized Properly? Not using them right?

I am -trying- to use nested structs/structures, and after several hours of pseudocode and attempts, the final result that I come up with doesn't work or doesn't compile.
I would like to take two vectors A and B, and compare them against each other. I set up nested struct to read the start and end point of the vector, and the vector struct itself. So I think I may be doing some wrong further below, but I am stuck.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
struct Point // Reads in three coordinates for point to make a three dimensional vector
{
double x;
double y;
double z;
};
struct MathVector // Struct for the start and end point of each vector.
{
Point start;
Point end;
};
Point ReadPoint()
{
Point pt; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> pt.x;
cout << "Please input the y-coordinate: " << endl;
cin >> pt.y;
cout << "Please input the z-coordinate: " << endl;
cin >> pt.z;
return pt;
}
void DotProduct (MathVector letterA, MathVector letterB, double& a_times_b ) //formula to compute orthogonality
{
a_times_b = (letterA.end.x - letterA.start.x)*(letterB.end.x - letterB.start.x) + (letterA.end.y - letterA.start.y)*(letterB.end.y - letterB.start.y) + (letterA.end.z - letterA.start.z)*(letterB.end.z - letterB.start.z);
}
int main()
{
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
DotProduct (letterA, letterB, a_times_b);
cout << "The vector " << letterA << " compared with " << letterB << " ";
if ( a_times_b == 0)
cout << "is orthoganal." << endl;
else
cout << "is not orthoganal." << endl;
return 0;
}
One problem is with your ReadPoint whose return type is Point, but you're returning an instance of MathVector. Also, you read the input into variables which ignore eventually.
You should write ReadPoint as:
Point ReadPoint()
{
Point p;
cout << "Please input the x-coordinate: " << endl;
cin >> p.x;
cout << "Please input the y-coordinate: " << endl;
cin >> p.y;
cout << "Please input the z-coordinate: " << endl;
cin >> p.z;
return p;
}
Or a little better version:
Point ReadPoint()
{
Point p;
cout << "Please enter point-coordinate : " << endl;
cin >> p.x >> p.y >> p.z; //example input : 1 2 3
return p;
}
Or, still better is, overload >> operator as:
std::istream & operator>>(std::istream & in, Point & p)
{
cout << "Please enter point-coordinate : " << endl;
return cin >> p.x >> p.y >> p.z; //example input : 1 2 3
}
//Use this as
Point pointA, pointB;
cin >> pointA >> pointB;
Now read a good C++ book. If you're already reading one, then make sure it is really good. Here is a list of really good C++ books, of all levels:
The Definitive C++ Book Guide and List
ReadPoint returns letter of type MathVector instead of Point
You haven't overloaded operator << to tell it how to handle MathVector objects
letterA and letterB are of type MathVector
MathVector letterA;
MathVector letterB;
double a_times_b;
letterA = ReadPoint();
letterB = ReadPoint();
you should create another method to read Mathvector.. as you are doing with Point.
and in method ReadPoint
return type must be Point .. If you reading point then do calculation here to create the object of MathVector go tet startpoint and endpoint format.
Point ReadPoint()
{
MathVector letter; // Letter distinguishes between vector A and vector B, or "letterA" and "letterB"
double x, y, z;
cout << "Please input the x-coordinate: " << endl;
cin >> x;
cout << "Please input the y-coordinate: " << endl;
cin >> y;
cout << "Please input the z-coordinate: " << endl;
cin >> z;
return letter;
}
You didn't explain what it is you're trying to do or what errors you got, but this code makes no sense. You have three variables, x, y, and z. You fill them with values you get from the user. Then you don't do anything with those variables and return the MathVector created by a default constructor even though you say you're going to return a Point. That makes very little sense.
No match for 'operator=' error means that there's no function for assigning a MathVector to a Point. You are calling ReadPoint() which returns a Point and trying to assign the returned value to a variable of type MathVector. The compiler can't create a 'convertion' function automatically. You have to provide one yourself. Perhaps what you meant was
letterA.start = ReadPoint();
letterA.end = ReadPoint();