Write a program to solve the system of equations Ax = b in tridiagonal form using Thomas Algorithm.

#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX_N 20
void tridge(float a[],float b[],float c[],float f[],int i,int iflag);
void main()
{
 float a[MAX_N+1],b[MAX_N+1],c[MAX_N+1],f[MAX_N+1];
 int n,i,j,iflag;
 clrscr();
 printf("\n what is the order n of system ?");
 scanf("%d",&n);
 printf("\n give b[1],c[1],rhs[1] for equation 1:");
 scanf("%f%f%f",&b[1],&c[1],&f[1]);
 for(i=2;i<=n-1;i++)
 {
 printf("\n give a[%d],b[%d],c[%d],rhs[%d] for the equation %d\n",i,i,i,i,i);
 scanf("%f%f%f%f",&a[i],&b[i],&c[i],&f[i]);
 }
 printf("\n give a[n],b[n],rhs[n] for equation %d:",n);
 scanf("%f%f%f",&a[n],&b[n],&f[n]);
 iflag=0;
 tridge(a,b,c,f,n,iflag);
 printf("solution");
 printf("\ni a[i]");
 for(j=1;j<=n;j++)
 printf("\n%d\t%f",j,f[j]);
 printf("\n");
 getch();
 return;
 }
 void tridge(float a[],float b[],float c[],float f[],int n,int iflag)
 {
  const float zero=0.0;
  int j;
  if(iflag==0)
  {
   for(j=2;j<=n;j++)
   {
    if(b[j-1]==zero)
    {
     return;
     }
    a[j]=a[j]/b[j-1];
    b[j]=b[j]-a[j]*c[j-1];
    }
    if(b[n]==zero)
    {
     return;
     }
    }
    for(j=2;j<=n;j++)
    f[j]=f[j]-a[j]*f[j-1];
    f[n]=f[n]/b[n];
    for(j=n-1;j>=1;j--)
    f[j]=(f[j]-c[j]*f[j+1])/b[j];
    return;
    }

No comments:

Post a Comment