How to Write a C Program to simple iteration method in C Programming Language ?
Solution:
#define _CRT_SECURE_NO_WARNINGS #include<stdlib.h> #include<stdio.h> #include<math.h> double *xk, *xk1; double t, l1, l2, max, Axk = 0, eps; int n, i, j, k, count = 0;; int compare() { max = abs(xk[0] - xk1[0]); for (i = 1; i < n; i++) { if (abs(xk[i] - xk1[i]) > max) max = abs(xk[i] - xk1[i]); } if (max <= eps) return 1; else return 0; } int main() { FILE *f1; FILE *f2; double **a; f1 = fopen("input.txt", "r"); fscanf(f1, "%d", &n); //считываем размер матрицы коэффициентов a = (double**)malloc(n*sizeof(double*)); //выделяем память под матрицу for (i = 0; i < n; i++) a[i] = (double*)malloc((n + 1)*sizeof(double)); for (i = 0; i < n; i++) //заполняем матрицу коэффициентов for (j = 0; j <= n; j++) fscanf(f1, "%lf", &a[i][j]); fscanf(f1, "%lf%lf", &l1, &l2); fscanf(f1, "%lf", &eps); xk = (double*)malloc(n*sizeof(double)); xk1 = (double*)malloc(n*sizeof(double)); for (i = 0; i < n; i++) { xk[i] = 1; xk1[i] = 0; } t = 2 / (l1 + l2); do { for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Axk += a[i][j] * xk[j]; } xk1[i] = xk[i] - t*(Axk - a[i][n]); Axk = 0; } for (k = 0; k < n; k++) { xk[k] = xk1[k]; } count++; } while (compare() == 0); fclose(f1); f2 = fopen("output.txt", "w"); for (i = 0; i < n; i++) fprintf(f2, "x[%d] = %.8f\n", i + 1, xk1[i]); fprintf(f2, "число итераций = %d", count); fclose(f2); return 0; }