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

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.

Related

Program akes only 1 alphabet input and exits while leaving remaining code unexecuted, why?

when user input a character and press enters to take next input, output window asks to press any key and exit, please help me out to get remaining code working,
Here is the code
char r, R;
char c;
int channels;
int resedential()
{
// float channelscost = costperchannel*channels;
// float Bill = channelscost+processingfee+basiccost;
// cout << "Dear Customer Here is Your Bill" <<" "<<Bill<<endl;
}
int main()
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
if( c == r || R )
{
cout << " Enter Customer Type" << " " << endl;
cin >> c;
}
}
One thing I recognise, is that your if statement doesn't do what you think it does. Right now you aren't checking if c is equal to R.
Fixed Code:
if(c == r || c == R)
{
cout << "Enter Customer Type " << endl;
cin >> c;
}
Also check that there are actual values in r and R. So it doesn't compare to a constant (char(0)) – ASCII code NUL, resulting from default initialization of file-scoped variables to zero.
Example:
char r = 'A';
char R = 'B';

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.

convert letters into numbers (A=1; B=2...) c++

I was trying to make letters into numbers in c++. When I write in console it should count modulo and type out if ship is coming (i did all, but can't make letters into numbers :/ )
This what should happen: ABC a = 1; b=2; c=3 1*2*3=6....
So I need to write a word and it should be separated into letters and converted into numbers like that.
I am just learning and I don't know much :)
My current code:
int shipnum, groupnum, moduleship, modulegroup;
cout << "type ship number "; cin >> shipnum;
cout << "type group number "; cin >> groupnum;
/*shipnum dabar 5... (5 mod 2)
groupnum dabar 3... (3 mod 2)
*/
moduleship = shipnum % 47; //skaiciuojam moduli...
modulegroup = groupnum % 47;
if (moduleship == modulegroup) {
cout << "YES ship is coming for you :)";
}
else if (moduleship != modulegroup) { // "!=" reiskia "nelygu"
cout << "SORRY, NO ship for you :(";
}
return 0;
Your question isn't precise, although I find it enough. Tip: Be precise with the information you provide, there's no need to show the rest of the code.
Lets say we have this char Ship[20]="ABCDEF";. If you encoding is as simple as A=1, B=2, etc, then you only need something like this:
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
decoded = decoded * i
}
cout<<decoded;
This loop will run till it encounters the '\0' (null character) at the end of the string. So, you would have a factorial on the fact that your codeing (A=1,B=2, etc) represents a factorial.
otherwise, you could use a switch case, or if statements to check for individual characters and decode appropriately.
char Ship[20]="ABCDEF";
int decoded=1;
for(int i=1; Ship[i]=!'/0'; ++i) {
switch(Ship[i]){
case 'A' : decoded = decoded * 1;
break;
case 'B' : decoded = decoded *2;
break;
//So on
default : break;
}
}
cout<<decoded;
Output in both cases:
720
"convert letters into numbers (A=1; B=2…)"
string a{"ABC"};
int a0 = a[0]; // 65
int a1 = a[1]; // 66
int a2 = a[2]; // 67
.....
want to wrap A = 1, B = 2...
a0 = a0 - (65 - 1);
a1 = a1 - (65 - 1);
....
The question is not clear but i think the question basically is to convert char into int which follows the encoding A=1, B=2, ......, Z=26 and do the required processing which is to multiply all the encodings.
So here is how you could do it:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s; //Input string
cout << "enter the string(CAPITALS ONLY) :";
cin >> s; //read the input string
int result = 1;
for (auto &elem : s){ //process all the characters of s
result *= elem - 'A' + 1; //corresponding int value is multiplied to the result
}
cout << "the result is :" << result;
}
Sample Output:
enter the string(CAPITALS ONLY) :AEF
the result is :30
(a+b)2=a2+b2+2ab: in cpp example
#include<iostream>
using namespace std;
//Declaring Function in scope
void firstFormula();
int main(void) //Main function
{
cout << "Hello World!!" << endl; //sample test text printing
firstFormula(); //executing function
return 0;
}
//function implementation
void firstFormula(){
//initializing variables
int a, b;
cout << "Enter Value of A" << endl;
cin >> a;//updating input values of a
cout << "Enter Value of B" << endl;
cin >> b;//updating input values of b
int v1 = a + b; //(a+b)2
int v2 = v1 * v1; //L.H.S
cout << "Value of v1=" << v1 << endl << "V2=" << v2 << endl;
cout << "Value of a=" << a << endl << "Value of B=" << b << endl;
int v3 = a * a;
int v4 = b * b;
int v5 = 2 * a * b;
int v6 = v3 + v4 + v5; //` R.H.S value after equation` `egfyufe`
cout << "Output=" << "V3=" << v3 << endl << "V4=" << v4 << endl << "v5="
<< v5 << endl << "V6=" << v6 << endl;
} //end

Keeping track of which is the smallest and which is the largest value so far in a loop

could you please help me with solving simple problem? I am very fresh with C++ and learning from book "Programming: Principles and Practice Using C++ by Bjarne Stroustrup". I have never learnt C++ before so I am not familiar with many useful features. The drill says:
"6. Now change the body of the loop so that it reads just one double
each time around. Define two variables to keep track of which is the
smallest and which is the largest value you have seen so far. Each
time through the loop write out the value entered. If it’s the
smallest so far, write the smallest so far after the number. If it is
the largest so far, write the largest so far after the number"
I do not know how to do this correctly without using vector. Here is my code:
#include "C:/std_lib_facilities.h"
int main()
{
double a, b,differ=0;
char c=' ';
cout << "Enter two values: \n";
while (c != '|' && cin >> a >> b )
{
if (a > b)
{
cout << "The smaller value is: "<< b << " and the larger value is: " << a << "\n \n";
differ = a - b;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else if (a < b)
{
cout << "The smaller value is: " << a << " and the larger value is: " << b << "\n \n";
differ = b - a;
if (differ < 1.0 / 100)
cout << "Numbers are almost equal\n\n";
}
else
{
cout << "These values are equal!\n";
}
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
And here are previous steps, these I have solved with code above:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
Could you give me some hint how to do step 6.? I had some ideas but none of them worked..
Here is new code:
#include "C:/std_lib_facilities.h"
int main()
{
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
double a,differ=0;
char c=' ';
cout << "Enter value: \n";
while (c != '|' && cin >> a)
{
if (a > largestSoFar)
{
largestSoFar = a;
cout <<"Largest so far is: "<< largestSoFar << endl;
}
else if (a < smallestSoFar)
{
smallestSoFar = a;
cout <<"Smallest so far is: "<< smallestSoFar << endl;
}
else if(smallestSoFar >= a && a<=largestSoFar)
cout << a << endl;
cout << "Enter a character | to break loop: \n";
cin >> c;
}
cout << "You have exited the loop.\n";
keep_window_open();
}
I do not know how to do this correctly without using vector.
You do not need vector for this. The description correctly says that two variables would be sufficient:
// Declare these variables before the loop
double smallestSoFar = std::numeric_limits<double>::max();
double largestSoFar = std::numeric_limits<double>::min();
Modify your loop to read into a, not into both a and b. Check the newly entered value against smallestSoFar and largestSoFar, do the printing, and re-assign smallest and largest as necessary. Note that the first time around you should see both printouts - for largest so far and for smallest so far.
Based on the knowledge that you are suppose to know at the current stage for the this assignment. The code should go something like this:
#include < iostream>
#include < cstdlib>
int main() {
double num_1 = 0;
double num_2 = 0;
double largest = 0;
double smallest = 0;
bool condition1 = true;
while (true) {
std::cin >> num_1;
if (num_1 > largest){
largest = num_1;
}
else if (num_1 < smallest) {
smallest = num_1;
}
std::cout << "The largest so far: " << largest << std::endl;
std::cin >> num_2;
if (condition1) {
smallest = largest;
condition1 = false;
}
if (num_2 < smallest) {
smallest = num_2;
}
else if (num_2 > largest) {
largest = num_2;
}
std::cout << "The smallest so far: " << smallest << std::endl;
}
system("pause");
return 0;
}
double large = 0;
double small = 0;
double input;
int counter = 0;
while (counter < 5) {
cin >> input;
cout <<"Large value: "<< large << '\t' <<"Small value: "<< small\
<< '\t' <<"Input value: "<< input << '\n';
if (input < small) {
cout << "The smallest value is " << input<<\
"\nthe largest value is "<< large<<'\n';
small = input;
}
else if (input > small&& input < large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << large<<'\n';
}
else if (input > small&& input > large) {
cout << "The smallest value is " << small << \
"\nthe largest value is " << input << '\n';
large = input;
}
counter += 1;

Using pointers and arrays to solve linear system

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.