Reputation: 163
For example, to this program that calculates equations of grade 3, after it calculates the equation, it stops. how do I make it so it loops back again to the start without executing again? I'm still new to this platform so I'll be in your care!
#include < stdio.h >
int main() {
int a, v, b, c, delt;
float x1, x2;
printf("\nIntroduceti cele 3 parametrii ecuatia: ");
scanf("%d %d %d", & a, & b, & c);
if (a != 0) {
v = pow(b, 2);
delt = v - (4 * a * c);
if (delt >= 0) {
delt = sqrt(delt);
x1 = -(b + delt) / (2.0 * a);
x2 = -(b - delt) / (2.0 * a);
printf("\nValoara lui x1 este: %f", x1);
printf("\n");
printf("\nValoara lui x2 este: %f", x2);
} else {
printf("Ecuatia nu are soluti! \n");
}
} else if (a == 0) {
printf("\nBLACKHOLE");
}
return 0;
}
Upvotes: 0
Views: 1105
Reputation: 565
You could wrap everything in a do-while
loop and ask the user whether he wants to continue the execution or not, for example:
int a,v,b,c,delt;
float x1,x2;
char choice;
do{
printf("\nIntroduceti cele 3 parametrii ecuatia: ");
scanf("%d %d %d", &a, &b, &c);
if(a!=0)
{
v=pow(b, 2);
delt = v-(4*a*c);
if (delt>=0)
{
delt=sqrt(delt);
x1=-(b+delt)/(2.0*a);
x2=-(b-delt)/(2.0*a);
printf("\nValoara lui x1 este: %f", x1);
printf("\n");
printf("\nValoara lui x2 este: %f", x2);
}
else
{
printf("Ecuatia nu are soluti! \n");
}
}
else if(a==0)
{
printf("\nBLACKHOLE");
}
printf("\nEvaluate new equation?(y/n) ")
scanf("%c",&choice)
}while(strcmp(choice,"y")==0);
return 0;
The block inside the do{...}
will execute at least once, then the user will be asked to input a char (y/n) to decide whether to continue or not.
The strcmp(string1,string2)
compares two strings and returns 0 if they are equal, so if the user chose "y", the strcmp will return 0 and the do-while will be executed again.
Upvotes: 1
Reputation: 3200
Just wrap your code into an infinite loop (while(1) { /* Your code here*/ }
):
#include < stdio.h >
int main() {
int a, v, b, c, delt;
float x1, x2;
while (1) {
printf("\nIntroduceti cele 3 parametrii ecuatia: ");
scanf("%d %d %d", & a, & b, & c);
if (a != 0) {
v = pow(b, 2);
delt = v - (4 * a * c);
if (delt >= 0) {
delt = sqrt(delt);
x1 = -(b + delt) / (2.0 * a);
x2 = -(b - delt) / (2.0 * a);
printf("\nValoara lui x1 este: %f", x1);
printf("\n");
printf("\nValoara lui x2 este: %f", x2);
} else {
printf("Ecuatia nu are soluti! \n");
}
} else if (a == 0) {
printf("\nBLACKHOLE");
}
}
return 0;
}
Upvotes: 0