Introduction Code for solving system of equation by Gaussian elimination method. The Code is well commented and would not need any further explanation The code Code: #include <stdio.h> #include <conio.h> #define N 100 /****************************************************************/ /***** Gauss elimination method to solve system of equation *****/ /****************************************************************/ void main() { float coeff[N][N+1]={{4,2,1,11},{2,3,4,20},{3,5,3,22},}; /* Co-efficient inputing variables */ int i,j,k; /* Loop variables */ int n=3; /* Number of equations */ float pivot; /* pivoting variables */ float sum; /* Back substitution sum storing variable */ float x[N]; /* values of the variables i.e. x's */ char ch; /* choice inputing variable */ do { printf("\nEnter the number of variables\n"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n+1;j++) { printf("\nEnter %d row %d col element\n",i+1,j+1); scanf("%f",&coeff[i][j]); } } for(k=0;k<n;k++) { for(i=k+1;i<n;i++) { pivot=coeff[i][k]/coeff[k][k]; for(j=k;j<n+1;j++) coeff[i][j]=coeff[i][j]-pivot*coeff[k][j]; } } x[n-1]=coeff[n-1][n]/coeff[n-1][n-1]; for(i=n-2;i>=0;i--) { sum=0; for(j=i;j<n+1;j++) sum=sum+coeff[i][j]*x[j]; x[i]=(coeff[i][n]-sum)/coeff[i][i]; } for(i=0;i<n;i++) printf("\nx%d = %g\n",i+1,x[i]); printf("\nDo you wish to continue[y/n]\n"); fflush(stdin); scanf("%c",&ch); }while(ch=='y' || ch=='Y'); getch(); } Post if you have any queries.
What is the use of fflush(stdin)? can you explain for me? i don't really know about it, but I often seen it after the end of a loop..... nice....
yeah, I know about flushs the inputBuffer. But, what I want to ask, "Why we must flush the inputBuffer? Is it important?". Coz I couldn't answert that question before, when my friend asked me. --------------------------------------------------- Sorry if my English not that good:surprised
At times the input buffer contains input for which some scanf /cin statements are skipped without asking for input and so its a god practice to flush it.
shabbir, I would NOT nominate this for Article of the Month... Reason- Does not follow ANSI C- int main void Should there be a requirement as such- if you are going to nominate this.. And Code: float coeff[N][N+1]={{4,2,1,11},{2,3,4,20},{3,5,3,22},}; Not need...
The code works in TurboC because my assignments wanted it to work in that compiler and that is the one used by my university and it does not matter if its nominated or not but my intentions were to share my code for members
It's a bad practice to use fflush(stdin) to flush the input stream.This method is UNPORTABLE, and hence should be avoided ! It will compile fine, but it's behavior is undefined on many C compilers. But, it can be used safely with output stream. To flush input stream, we can define something like : Code: void my_fflush(FILE *pFile) { char c; while( ((c = fgetc(pFile)) != EOF) && (c != '\n') ); } and call it like : Code: my_fflush(stdin);