Hi, this code in my textbook needs to be re-written with pass by reference while
ID: 3564512 • Letter: H
Question
Hi, this code in my textbook needs to be re-written with pass by reference while also eliminating the goto statements. I'm pretty new to C language still and not good at pass by reference.
Because it leads to "spaghetti code", the goto is seldom used in today's programming world. The following code illustrates how just a few goto statements make the flow of control Note how the programmer kept adding different cases and had to repatch the the program logic become obscure. Rewrite without using goto statements.Explanation / Answer
void quadraticRoots(double a, double b, double c, double* r1, double* r2){
double d = (b*b)-(4*a*c);
if(d==0){
if(a!=0.0)
*r1=*r2=(-b)/(2*a);
else{
printf("Degenerate case ");
return;
}
}
else if(d>0){
if(a!=0.0){
*r1=(-b-sqrt(d))/(2*a);
*r1=(-b+sqrt(d))/(2*a);
}
else{
printf("Degenerate case ");
return;
}
}
else{
if(a!=0.0){
printf"Imaginary roots ");
return;
}
}
}
Whenever any other function needs to call the above function, they need to pass the value of a ,b and c. Argument r1 and r2 are passed by reference. This means that we do not pass the value stored in r1 or r2 but we pass its address to the function. So the function can directly manipulate the value of r1 or r2. In the above function, it stores the value of the roots in r1 and r2. Thus any changes made by the function to the value of r1 and r2 are reflected in the calling function.
eg : if in main function we write the following-
double a= 1.0, b= -8.0, c=15.0;
double r1,r2;
quadraticRoots(a, b, c, &r1, &r2);
after the execution of the code, the function will modyfy the values of r1 and r2 to hol the value of calculated root values which is 5.0 and 3.0. Even if r1 and r2 would be having different sets of values, after pass by reference, their values might be changed by the called function.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.