Approximating the steady-state solution of a grid in C Program

How to write a C Program to Approximating the steady-state solution of a grid in C Programming Language ?


Solution:
//Approximating the steady-state solution of a grid

#include<stdio.h>

void printArray(double a[10][10]);

int main (void)
{
  int i, j, k = 0, its;
  double top, right, bottom, left;
  double eps, sum, avg, diff, maxValue = 0.0;
  double curr[10][10];
  double new[10][10];

  //Prompt user for number of iterations
  puts("Enter number of iterations:");
  scanf("%d", &its);

  //Error check
  if(its > 100 || its < 0)
    {
      puts("ERROR");
      return 0;
    }

  //Prompt user for error tolerance
  puts("Enter epsilon value:");
  scanf("%lf", &eps);

  //Error check
  if(0.001 >= eps ||  eps >= 0.1)
    {
      puts("ERROR");
      return 0;
    }

  //Prompt user for boundary values
  puts("Enter four numbers for the boundary values:");
  scanf("%lf %lf %lf %lf", &top, &right, &bottom, &left);
 
  //Initializes both arrays
  for(i = 0; i < 10; i++)
    {
      for(j = 0; j < 10; j++)
{
 curr[i][j] = 0;
 new[i][j] = 0;
}
    }

  //Sets boundaries
  for(i = 0; i < 10; i++)
    {
      curr[i][9] = right;
      curr[9][i] = bottom;
      curr[i][0] = left;
      curr[0][i] = top;
      new[i][9] = right;
      new[9][i] = bottom;
      new[i][0] = left;
      new[0][i] = top;
     
    }

  while(k < its)
  {
    for(i = 1; i < 9; i++)
      {
       for(j = 1; j < 9; j++)
{
  //finds the average
  sum = curr[i-1][j]+curr[i][j+1]+curr[i+1][j]+curr[i][j-1];
  avg = sum / 4.0;
  new[i][j] = avg;
}
      }
 printArray(new);
 for(i = 1; i < 9; i++)
 {
 for(j = 1; j < 9; j++)
 {
 diff = new[i][j] - curr[i][j];
 if(maxValue < diff)
 {
 maxValue = diff;
 }
 }
 }
    if(maxValue < eps)
      {
printf("Converges in %d steps", k);
printArray(new);
return 0;
      }
 
    for(i = 1; i < 9; i++)
      {
       for(j = 1; j < 9; j++)
{
  curr[i][j] = new[i][j];
  if(j == 1 && i == 1)
    {
  printArray(new);
  puts("");
  printArray(curr);
  puts("");
    }
}
      }
    k++;
    // printf("%d\n", k);
  }

  puts("No convergence");
  //printArray(new);
  return 0;

}

//Function to print grid
void printArray(double a[10][10])
{
  int i, j;
  for(i = 0; i < 10; i++)
    {
      for(j = 0; j < 10; j++)
{
 printf("%.2lf ", a[i][j]);
}
      puts("");
    }
}


Learn More :