Code:
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#define err 1e-4
void main()
{
int a[3],b[3],c[3],d[3],i,n,choice=0;
//Displays the 'format' of the linear equations.
for (i=1;i<=3;i++)
cout<<"a"<<i<<"x + b"<<i<<"y + c"<<i<<"z = d"<<i<<endl;
cout<<endl;
//Asks user to input the values of a,b,c,d and the accuracy of the calculation.
for (i=0;i<3;i++)
{
cout<<"Enter value of a"<<i+1<<" :";
cin>>a[i];
cout<<"Enter value of b"<<i+1<<" :";
cin>>b[i];
cout<<"Enter value of c"<<i+1<<" :";
cin>>c[i];
cout<<"Enter value of d"<<i+1<<" :";
cin>>d[i];
cout<<endl;
}
cout<<"Enter the accuracy(number of decimal places): ";
cin>>n;
//clrscr();
//Displays the linear equations.
for (i=0;i<3;i++)
cout<<a[i]<<"x + "<<b[i]<<"y + "<<c[i]<<"z = "<<d[i]<<endl;
cout<<endl;
//Asks user to choose iterative method.
do
{
cout<<"Choose iterative method..."<<endl<<endl;
cout<<"1. Gauss Jacobi"<<endl;
cout<<"2. Gauss Seidel"<<endl<<endl;
cout<<"Enter choice: ";
cin>>choice;
if ((choice==1) || (choice==2)) //Exit the WHILE..DO loop if either 1 or 2 is input.
break;
}while((choice!=1)||(choice!=2));
if (choice==1) //If 1 is input, perform Gauss-Jacobi method;
{
int k=1;
float x,y,z,x1,y1,z1,x2,y2,z2;
y=0;
z=0;
x=0;
x1=(d[0]-(b[0]*y)-(c[0]*z))/a[0];
y1=(d[1]-(a[1]*x)-(c[1]*z))/b[1];
z1=(d[2]-(a[2]*x)-(b[2]*y))/c[2];
cout<<"x:"<<setprecision(n)<<x1<<"\t";
cout<<"y:"<<setprecision(n)<<y1<<"\t";
cout<<"z:"<<setprecision(n)<<z1<<endl<<endl;
do
{
x2=x;
y2=y;
z2=z;
x=(d[0]-(b[0]*y1)-(c[0]*z1))/a[0];
y=(d[1]-(a[1]*x1)-(c[1]*z1))/b[1];
z=(d[2]-(a[2]*x1)-(b[2]*y1))/c[2];
k++;
x1=x;
y1=y;
z1=z;
cout<<"x:"<<setprecision(n)<<x1<<"\t";
cout<<"y:"<<setprecision(n)<<y1<<"\t";
cout<<"z:"<<setprecision(n)<<z1<<endl<<endl;
}while(???);
cout<<"Using Gauss-Jacobi Method..."<<endl;
cout<<"Number of iterations performed: "<<k<<endl;
cout<<"Value of x is "<<x1<<endl;
cout<<"Value of y is "<<y1<<endl;
cout<<"Value of z is "<<z1<<endl;
}
else //If 2 is input, perform Gauss-Seidel method.
cout<<"Seidel";
}
a1=8 , b1=-3 , c1=2 , d1=20
a2 =4 , b2=11 , c2=-1 , d2=33
a3=6 , b3=3 , c3=12 , d3=35
The answers should be x= 3.0168 , y= 1.9859 and z=0.9118

