My assignment to develop a program to compute 3 systems of linear equations: the program must allow the user to input the coefficients and constants, number of iterations and level of acceptable error. I can't seem to include both the number of iterations and level of error as parameters to stop the loop and show the final values of the variables. Here's what I have so far:
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
cout<<"Welcome. This is Problem 1. "<<endl;
cout<<"computing systems of three linear equations through gauss-seidel method"<<endl;
float coefEqxn1[3];
for (int x=0; x<3;)
{
for ( int eq1=1; eq1<=3; eq1++)
{
cout<<"Please enter Coefficient " <<eq1<< " of equation 1 : ";
cin>>coefEqxn1[x];
x++;
}
}
float coefEqxn2[3];
for (int x=0; x<3;)
{
for ( int eq2=1; eq2<=3; eq2++)
{
cout<<"Please enter Coefficient " <<eq2<<" of equation 2 :" ;
cin>>coefEqxn2[x];
x++;
}
}
float coefEqxn3[3];
for (int x=0; x<3;)
{
for ( int eq3=1; eq3<=3; eq3++)
{
cout<<"Please enter Coefficient "<<eq3<<" of equation 3 :";
cin>>coefEqxn3[x];
x++;
}
}
float constants[3];
for (int y=0; y<3;)
{
for (int con=1; con<=3; con++)
{
cout<<"Please enter the contant of equation "<<con<<" : ";
cin>>constants[y];
y++;
}
}
cout<<"Calculating through Cramer's Rule..."<<endl;
int iteration=0;
cout<<"enter # iteration"<<endl;
cin>>iteration;
int stopC=0;
cout<<"enter level of error"<<endl;
cin>>stopC;
float matrixArray[3][4];
{
for ( int y=0; y<3;)
{
for (int x=0; x<=3;x++)
matrixArray[0][y]=coefEqxn1[y];
y++;
}
matrixArray[0][3]=constants[0];
for ( int y=0; y<3;)
{
for (int x=0; x<=3;x++)
matrixArray[1][y]=coefEqxn2[y];
y++;
}
matrixArray[1][3]=constants[1];
for ( int y=0; y<3;)
{
for (int x=0; x<=3;x++)
matrixArray[2][y]=coefEqxn3[y];
y++;
}
matrixArray[2][3]=constants[2];
}
for(int a=0; a<3; a++)
{
for(int b=0; b<=3; b++)
cout<<"matrixArray["<<a<<"]["<<b<<"]: "<<matrixArray[a][b]<<endl;
}
float valueOfX[100], valueOfY[100], valueOfZ[100];
for( int i=1; i<iteration; )
{
valueOfX[0]=0, valueOfY[0]=0, valueOfZ[0]=0;
valueOfX[i]=(matrixArray[0][3]-(matrixArray[0][2]*valueOfZ[i-1]+matrixArray[0][1]*valueOfY[i-1]))/matrixArray[0][0];
valueOfY[i]=(matrixArray[1][3]-(matrixArray[1][2]*valueOfZ[i-1]+matrixArray[1][0]*valueOfX[i]))/matrixArray[1][1];
valueOfZ[i]=(matrixArray[2][3]-(matrixArray[2][1]*valueOfY[i]+matrixArray[2][0]*valueOfX[i]))/matrixArray[2][2];
float reX=0, reY=0, reZ=0;
reX=((valueOfX[i+1]-valueOfX[i])/valueOfX[i+1])*100;
reY=((valueOfY[i+1]-valueOfY[i])/valueOfY[i+1])*100;
reX=((valueOfZ[i+1]-valueOfZ[i])/valueOfZ[i+1])*100;
if (reX<=inputErrorLevel)
break;
if (reY<=inputErrorLevel)
break;
if (reZ<=inputErrorLevel)
break;
cout<<"reX = "<<reX<<endl;
cout<<"reY = "<<reY<<endl;
cout<<"reY = "<<reX<<endl;
i++;
}
cout<<"x = "<<valueOfX[iteration-1]<<endl;
cout<<"y = "<<valueOfY[iteration-1]<<endl;
cout<<"z = "<<valueOfZ[iteration-1]<<endl;
}
Based on what you want you should have something like
double inputErrorLevel; //Read from user input
// The for loop guarantees that the loop will run at max iteration times.
// Noticed I changed it to start from zero otherwise it will only run
// iteration -1 times
for( int i=0; i<iteration; ++i )
{
//Do heavy computation stuff.
double currentErrorLevel = ComputeErrorAtCurrentIteration();
if ( currentErrorLevel < inputErrorLevel )
break; // break will ensure more iterations are not done
// if error level is acceptable
}
Typical programming practice is to to
for ( int i = 0 ; i < 5; ++i )
{
}
instead of
for ( int i = 0 ; i < 5; )
{
++i;
}
This looks like a typo?
reX=((valueOfZ[i+1]-valueOfZ[i])/valueOfZ[i+1])*100;
Shouldn't that be:
reZ=((valueOfZ[i+1]-valueOfZ[i])/valueOfZ[i+1])*100;
Same here:
cout<<"reY = "<<reX<<endl;
But to answer your question this should be using i to index the results not iteration. iteration variable is going to always be constant so it will always give that result regardless of error.
Like:
cout<<"x = "<<valueOfX[i-1]<<endl;
cout<<"y = "<<valueOfY[i-1]<<endl;
cout<<"z = "<<valueOfZ[i-1]<<endl;
Related
#include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter the size of the array :";
cin>>n;
int A[n][n];
int y=n,k=1,p=0,i;
while(k<=n*n)
{
for(i=p;i < y;i++)
{
A[y-1][i]=k++;
}
for(i=y - 2;i > p;i--)
{
A[i][y-1]=k++;
}
for(i=y - 2;i > p;i--)
{
A[p][i]=k++;
}
for(i = p + 1;i < y; i++)
{
A[i][p]=k++;
}
p++;
y--;
}
if(!n%2)
{
A[(n+1)/2][(n+1)/2]=n*n;
}
for(i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<A[i][j]<<"\t";
}
cout<<endl;
}
return 0;
I need to do a spiral matrix the way like this > enter image description here.
It breaks on the last "for" cycle and just doesn't show anything;;; Still, it shows up if I'm replacing one of the loop's statements;; I would be grateful if you point me where's my mistake!
(this code is a modified one brought from here https://www.includehelp.com/cpp-programs/print-a-spiral-matrix.aspx)
There were simply some little mistakes on the bounds of the loops (the bounds of the spiral). Here is a slightly modified programme.
PS: Note that you should avoid to use VMA int A[n][n] which is C, not C++.
#include<iostream>
//using namespace std;
int main()
{
int n;
std::cout << "Enter the size of the array :";
std::cin >> n;
int A[n][n];
int y = n, k = 1,p = 0,i;
while(k<= n*n)
{
for(i=p;i < y;i++)
{
A[y-1][i]=k++;
}
for(i=y - 2;i >= p;i--)
{
A[i][y-1]=k++;
}
for(i = y - 2;i >= p;i--)
{
A[p][i]=k++;
}
for(i = p + 1;i < y-1; i++)
{
A[i][p]=k++;
}
p++;
y--;
}
if(!n%2)
{
A[(n+1)/2][(n+1)/2]=n*n;
}
for(i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
std::cout<<A[i][j]<<"\t";
}
std::cout << "\n";
}
return 0;
}
For my CS class we are making a program that reads in numbers, calculates the inflation rate from those 2 numbers, sends those numbers to an array, bubblesorts the array, and then prints that array out after it is sorted. However, I can't get my bubblesort to sort, either there is a compiler error when I use &, or there it just doesnt sort. Can anyone help? Thank you!
#include
using namespace std;
double InflationRate(float old_cpi, float new_cpi);
double inflateRate;
void getCPIValues(float &old_cpi, float &new_cpi);
float swap_values(float&i, float&j);
void bubbleSort(float a[], int number_used);
float old_cpi=-1;
float new_cpi=-1;
const int MAX_RATES=20;
float a[MAX_RATES]={};
int main() //C++ programs start by executing the function main
{
char Continue = 'y';
double total = 0;
int i=0;
do{
getCPIValues(old_cpi, new_cpi);
InflationRate(old_cpi, new_cpi);
cout<< "Inflation rate is "<<inflateRate<<endl;
total = total+inflateRate;
cout << "Try again? (y or Y): ";
i++;
a[i-1]= inflateRate;
cin >> Continue;
}while ((Continue == 'y')||(Continue == 'Y'));
cout<<"Average rate is "<<total/i<<endl;
int number_used= i-1;
for (int p; p<=number_used; p++)
{
cout<<a[p]<<endl;
}
return 0;
}
double InflationRate(float old_cpi, float new_cpi)
{
inflateRate = (new_cpi - old_cpi)/old_cpi*100;
return(inflateRate);
}
void getCPIValues(float &old_cpi, float &new_cpi)
{
cout<<"Enter the old and new consumer price indices: ";
cin>>old_cpi>>new_cpi;
if ((old_cpi<=0)||(new_cpi<=0))
{
do
{
cout<<"Error: CPI values must be greater than 0";
cin>>old_cpi>>new_cpi;
}while ((old_cpi<=0)||(new_cpi<=0));
}
}
float swap_values(float&i, float&j)
{
int temp = i;
i=j;
j=temp;
return(i, j);
}
void bubbleSort(float a[], int number_used)
{
for (int m = 0; m < number_used-1; m++)
for (int n = 0; n < number_used-m-1; n++)
if (a[n] > a[n+1])
swap_values(&a[n], &a[n+1]);
}
[![enter image description here][1]][1]
This is what I have tried out but whenever I run the program it crashes and says error, although it compiles correctly. It asks me to enter department number but after that doesn't show me any output
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int STDTs = 25;
const int DEPTs = 7;
void initializeGPAs(double gpa[][DEPTs])
{
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
gpa[i][j]=(10+rand()%31)/10;
}
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
sum+=gpa[j][i];
deptAvg[i]=double(sum/STDTs);
}
}
int StdsOnProbationCount(double gpa[][DEPTs])
{
int ctr=0;
for(int i=0;i<STDTs;i++)
for(int j=0;j<DEPTs;j++)
if(gpa[i][j]<2)
ctr++;
return ctr;
}
int StdsOnProbationCountinDeptX(double gpa[][DEPTs], int x)
{
int ctr=0;
for(int i=0;i<STDTs;i++)
if(gpa[i][x-1]<2)
ctr++;
return ctr;
}
void showReport(double gpa[][DEPTs],string dept_names[], double deptAvg[], int ctr1, int ctr2, int x)
{
cout<<endl;
for(int i=0;i<DEPTs;i++)
{
cout<<'\t'<<dept_names[i]<<" ";
}
cout<<endl;
for(int i=0;i<STDTs;i++)
{
cout<<"Student "<<i+1<<": ";
for(int j=0;j<DEPTs;j++)
cout<<gpa[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(int t=0;t<DEPTs;t++)
cout<<"Dept Avg.: "<<deptAvg[t]<<" ";
cout<<endl<<endl;
cout<<"Total number of students who are on probation is: "<<ctr1;
cout<<endl;
cout<<"Number of students who are on probation in "<<dept_names[x-1]<<" Dept. is "<<ctr2;
}
int main()
{
double gpa[STDTs][DEPTs];
int ctr1, ctr2, x;
double deptAvg[DEPTs];
string dept_names[DEPTs]={"MATH","STAT","COMP","PHYS","CHEM","BIOL","GEOL"};
initializeGPAs(gpa);
computeDeptAvg(gpa, deptAvg);
ctr1 = StdsOnProbationCount(gpa);
cout<<"Enter Department Number [1 to 7]: ";
cin >> x;
ctr2 = StdsOnProbationCountinDeptX(gpa, x);
showReport(gpa, dept_names, deptAvg, ctr1, ctr2, x);
return 0;
}
edit: I figured everything out but my problem seems to be in this function because it displays zeroes for all the department averages
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int i=0;i<STDTs;i++)
{
int sum=0;
for(int j=0;j<DEPTs;j++)
{
sum+=gpa[j][i];
deptAvg[j]=double(sum/STDTs*1.0);
}
}
}
I'll consider only your computeDeptAvg function.
Your sum variable should be of type double, declaring it as an int makes all of your calculations (specifically the sum+=gpa[j][i] and sum/STDTs, which is an integer division) prone to truncating errors.
You nested the two loops in the wrong order: You should sum the scores of all the students in a particular department in order to calculate the average of that department. Besides, deptAvg[j] is overwritten every time the outer loop is executed.
You have declared gpa in main as a double gpa[STDTs][DEPTs];, but in your loops you are using gpa[j][i], where j is in the range [0, DEPTs) and i in [0, STDTs).
A modified version could be:
void computeDeptAvg(double gpa[][DEPTs] , double deptAvg[])
{
for(int d = 0; d < DEPTs; d++)
{
double sum = 0.0;
for(int s = 0; s < STDTs; s++)
{
sum += gpa[s][d];
}
deptAvg[d] = sum / STDTs;
}
}
This is what I wrote so far, where did I go wrong?
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i]<<" ";
}
}
Edit:
Many thanks to everyone that tried to help. The problem was that I had to int count in the loop so that it would start from 0 every time. Here's my new working code:
#include <iostream>
using namespace std;
int main()
{
int x[5];
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{ int count=0;
for (int n=2;n<=x[i];n++)
{
if (x[i]%n==0)
count++;
}
if (count==1)
cout<<x[i];
}
}
#include <iostream>
using namespace std;
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
bool check = true;
for (int n=2;n<x[i];n++)
{
if (x[i]%n==0)
{
check = false;
break;
}
}
if (check)
cout<<x[i]<<" ";
}
}
For better complexity, change your nested for loop to :
for (int n=2;n<=sqrt(x[i]);n++)
Other way :
int main ()
{
for (int i=2; i<100; i++)
{
bool check=true;
for (int n=2; n*n<=x[i]; n++)
{
if (x[i] % n == 0)
{
check=false;
break;
}
}
if(check) cout << x[i] << " ";
}
return 0;
}
Here's my solution.
I basically assume all numbers are prime, but if I find them not to be prime I don't print them out.
int main() {
bool primeNumber;
int length = 0;
int x[5], count=0;
for (int i=0;i<5;i++){
length++;
cin>>x[i];
}
for (int i = 0; i < length; i++ )
{
primeNumber = true;
for (int j = 3; j <= x[i]/2; j += 2 )//Not necessary to check agains numbers higher than half the number you want to check
{
if (x[i] % j == 0)
{
primeNumber = false;
}
}
if(primeNumber){cout << "Primenumber: " << x[i] << endl;}
}
}
EDIT:
Here's a comment on your code
Let's say your array looks like this
{5,9,13,15, 17}
int main()
{
int x[5], count=0;
for (int i=0;i<5;i++)
cin>>x[i];
for (int i=0;i<5;i++)
{
for (int n=2;n<x[i];n++)
{
Here you loop from 2-4(2,3,4). It's only necessary to loop half the number you want to check. e.g. (x[i]/2), but you can do it like you have done here.
if (x[i]%n==0){
count++;}
When your number is 5 and you check agains n numbers This will produce 5%2=1,5%3=2,5%4=1. But 5 is a prime number and your code didn't manage to detect that.
}
if (count==1)
Let's say you did find that 5 is a prime above and you managed to increment count to 1. What happens when you find another prime number in your array e.g. 7. That will make count be equal to 2. But you only check against 1, so therefor your next prime number doesn't get printed because count will only be equal to 1 after the first prime number and not the rest.
cout<<x[i]<<" ";
}
}
Hopefully you understood my explanation. It always helps to go over your code by hand or debug mode and think what the code will do with different numbers.
All numers are divideable by itself. That will make all numbers prime if you try to divide numbers with themselves
I got a little problem about this program i am making ,
The main purpose of this program I am making is to get 2 polynomial and sum / sub / multiply it ,
Didn't finished the output and main() parts yet, just on the code itself,
When I try to use the multiply part,
I get this error : stack around the variable 'a' is corrupted ,
Dunno what I did wrong .... took me 1 hours to think of this way and write this , but just 2 hours trying to fix this but can't get anywhere.
class PolyNomial
{
int printcounter;
double *coefficients;
int degree;
public:
PolyNomial()//the default constructor to initialize a polynomial equal to 0
{
degree = 0;
coefficients = new double[degree + 1];
coefficients[0] = 0;
}
PolyNomial(double y[], int x)//the constructor to initialize a polynomial with the given coefficient array and degree
{
degree = x;
if (degree>10)
{
cout<<"Error : The PolyNomial's Degree is bigger than 10 and can not be shown in this program";
}
else
{
int c=0;
coefficients = new double[degree + 1];
for(c=0;c<=degree;c++)
{
coefficients[c] = y[c];
}
}
}
void add(PolyNomial p)
{
int i;
if ( degree < p.degree )
{
i = p.degree;
printcounter = p.degree;
}
else
{
i = degree;
printcounter = degree;
}
for(;i>=0;i--)
{
coefficients[i] = coefficients[i] + p.coefficients[i];
}
}
void sub(PolyNomial p)
{
int i;
if ( degree < p.degree )
{
i = p.degree;
printcounter = p.degree;
}
else
{
i = degree;
printcounter = degree;
}
for(;i>=0;i--)
{
coefficients[i] = coefficients[i] - p.coefficients[i];
}
}
void print()
{
int i;
for(i=0;i<=printcounter;i++)
cout<<coefficients[i]<<" ";
}
void Multiply(PolyNomial p)
{
int i,j;
i = degree;
j = p.degree;
double a[100];
int counter;
for ( counter = 0 ; counter <= i+j; counter++)
{
a[counter]=0;
}
int x= i+ j ;
for(;i>=0;i--)
{
for(;j>=0;j--)
if (i+j>=10)
{
cout<<"Error : The PolyNomial's Degree is bigger than 10 and can not be shown in this program";
break;
}
a[i+j] = a[i+j] + ( coefficients[i] * p.coefficients[j] );
}
PolyNomial k(coefficients,x);
k.print();
}
};
int main()
{
double a[100];
int x,i;
cout<<"Enter the PolyNomial's Degree : ";
cin>>x;
cout<<"\nEnter the coefficients one by one by , from bigger to smaller : ";
for ( i=0 ; i<=x ; i++ )
{
cin>>a[i];
}
PolyNomial p(a,x);
cout<<"\n\nEnter the PolyNomial's Degree : ";
cin>>x;
cout<<"\nEnter the coefficients one by one by , from lowest degree to highest : ";
for ( i=0 ; i<=x ; i++ )
{
cin>>a[i];
}
PolyNomial o(a,x);
_getch();
// p.add(o);
p.Multiply(o);
// p.print();
_getch();
// p.sub(o);
// p.Multiply(o);
}
This line
a[i+j] = a[i+j] + ( coefficients[i] * p.coefficients[j] );
is not inside the for j loop (you haven't used { and } to enclose it}. This means that j is -1 when it gets run. If i is 0 you are assigning to a[-1] which causes the stack corruption message.
Note that you also aren't resetting j each time round the i loop, so the inner loop will only execute once.
In C and C++ local variables are generally stored on the stack, a small(ish) area of memory that programs use to store local/function level data; when an executable calls a function, the processor uses the stack to store the address that the call is being made from, and then branches to the subroutine. When the subroutine finishes, if it has cleaned up it's stack, then it should be back to a state where the top value of the stack is the address it needs to jump back to in order to resume processing.
At the same time, C/C++ programs use the stack to store local variables -- the principle being that when you leave a sub-routine all the variables go away very elegantly.
Your variables "a" are local variables, they are on the stack. Since they are arrays, that means that if you write outside the contraints of the array, you will overwrite areas of the stack being used by other variables or possibly even by the CPU for return-address tracking.
Your variables "a" have 100 elements. This array forms a single, contiguous block:
{a[0]}{a[1]}...{a[99]}
If you write to 'a[100]' you are writing past the end of the array and over some other variable's memory, or possibly the return address of a function.
You might want to consider using a [std::array][1] or a [std::vector][2].
At the time you create your polynomial, you create a coefficients array with the size of degree + 1. So far so good. Now if you add two polynomials, you simply add the coefficients but disregard the allocated space. If the polynomial with the lowest degree should be the result of the addition, you'll get in trouble
Well for now tnx to all the answers and comments i got my code working but it dose not do the job correctly,
Example : if I add a 2 degree polynomial first then a 3 degree like this :
1 2 3
1 2 3 4
The result will be :
0 0 3 6 9 12
Which is only one part of the multiply processes,
The 2 polynomial I added are :
3x^2 + 2x^1 + 1
4x^3 + 3x^2 + 2x^1 + 1
Here is the new code :
class PolyNomial
{
int printcounter;
double *coefficients;
int degree;
public:
PolyNomial()//the default constructor to initialize a polynomial equal to 0
{
degree = 0;
coefficients = new double[degree + 1];
coefficients[0] = 0;
}
PolyNomial(double y[], int x)//the constructor to initialize a polynomial with the given coefficient array and degree
{
degree = x;
if (degree>10)
{
cout<<"Error : The PolyNomial's Degree is bigger than 10 and can not be shown in this program";
}
else
{
int c=0;
coefficients = new double[degree + 1];
for(c=0;c<=degree;c++)
{
coefficients[c] = y[c];
}
}
}
void add(PolyNomial p)
{
int i;
if ( degree < p.degree )
{
i = p.degree;
printcounter = p.degree;
}
else
{
i = degree;
printcounter = degree;
}
for(;i>=0;i--)
{
coefficients[i] = coefficients[i] + p.coefficients[i];
}
}
void sub(PolyNomial p)
{
int i;
if ( degree < p.degree )
{
i = p.degree;
printcounter = p.degree;
}
else
{
i = degree;
printcounter = degree;
}
for(;i>=0;i--)
{
coefficients[i] = coefficients[i] - p.coefficients[i];
}
}
void print()
{
int i;
for(i=0;i<=printcounter;i++)
cout<<coefficients[i]<<" ";
}
void Multiply(PolyNomial p)
{
int i,j;
i = degree;
j = p.degree;
double mult[100];
int counter;
for ( counter = 0 ; counter <= i+j; counter++)
{
mult[counter]=0;
}
int x= i+ j ;
for(;i>=0;i--)
{
for(;j>=0;j--)
{
if (i+j>=10)
{
cout<<"Error : The PolyNomial's Degree is bigger than 10 and can not be shown in this program";
break;
}
mult[i+j] = mult[i+j] + ( coefficients[i] * p.coefficients[j] );
}
}
PolyNomial k(mult,x);
k.printcounter = x;
k.print();
}
};
int main()
{
double a[100];
int x,i;
cout<<"Enter the PolyNomial's Degree : ";
cin>>x;
cout<<"\nEnter the coefficients one by one by , from lowesr degree to highest : ";
for ( i=0 ; i<=x ; i++ )
{
cin>>a[i];
}
PolyNomial p(a,x);
cout<<"\n\nEnter the PolyNomial's Degree : ";
cin>>x;
cout<<"\nEnter the coefficients one by one by , from lowest degree to highest : ";
for ( i=0 ; i<=x ; i++ )
{
cin>>a[i];
}
PolyNomial o(a,x);
_getch();
// p.add(o);
p.Multiply(o);
// p.print();
_getch();
// p.sub(o);
// p.Multiply(o);
}