# Thread: how can I get the program to loop back into itself?

1. ## how can I get the program to loop back into itself?

If you look at the bottom of the code, how can I make it so if the user enters "y" or "Y" the program runs again? Right now it just quits either way.

Code:
```#include <stdio.h>
#include <math.h>
#define N 100

int main()
{
//bounds for the multidimensional array which can handle up to 100 variables
float coeff[N][N+1]; /*={{4,2,1,11},{2,3,4,20},{3,5,3,22},};*/
int i,j,k;    // loop counters
int n=3;        // Number of equations. Can be more, but for now set at 3
float pivot;
float sum;
float x[N];
char ch;
do
{
printf("To use this program enter all coefficients of variables\n");
printf("Start with the first row and first column, and  move on to the next row after each one is entered\n");
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 row %d col %d element\n",i+1,j+1);
scanf("%f",&coeff[i][j]);
}
}
for(k=0;k<n;k++)
{
for(i=k+1;i<n;i++)
{
// This determines the varible value we need to pivot
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];  //determines value of variables (x's)
for(i=n-2;i>=0;i--)
{
// store the sum of variables in here in order to substitute back into the matrix
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');
getchar();
}```

2. It's called recursion.

3. It works fine for me.

And of course recursion shouldn't be used in main. The way you do it should suffice. The only thing you should pay attention to is to initialize correctly variables in each loop, which i don't think there is a problem with.

4. Hmmm. It worked fine for you? did you run it? Because my problem is that it won't start over if I enter yes at the end.

5. Maybe it's the Undefined behavior of fflush(stdin) biting you in the ass?

6. fflush(stdin) is not supported in C. fflush() is for output streams only.

What you can do is use

someVariable = getchar()

to pull any unwanted newline or other char, from the input keyboard buffer.

If you have multiple char's on the input buffer that you need to clear out, you can use this indusrial strength combo:

Code:
```//this is a one line while loop
while((someVariable = getchar()) != '\n');  //note the semi-colon at the end of this line
someVariable = getchar();```
if the above introduces an extra enter key requirement, remove the last line of code, but keep the while loop.

Exactly what you'll need depends on what you're scanf() is requesting. scanf() for numbers, will skip over whitespace in the input buffer (no problem there). scanf() for char's will *not*.