Fortran Problem Solving part 1 is already published. So go and check it out.
This article covers some questions that can be solved using Fortran Programming Language and you need some knowledge before proceeding here. So, I suggest you read all the previous lessons covered in Fortran.
Fortran Problem Solving: Question
Solve this quadratic equation: 
In order to solve this quadratic equation, first let’s know about it.
Quadratic Equation
The general form of quadratic equation is
.
The value of from the above equation is called the roots of that equation. Why roots?? because the above equation gives two values of
.
The formula to calculate the roots from quadratic equation is:
Using plus and minus sign separately, gives two different values of x.
Now let’s implement that formula in Fortran code to solve a quadratic equation :
Fortran Code to Solve Quadratic Equation
There is one thing that should be considered before writing a formula to code directly.
In the above formula, there is a calculation of the square root of . The result of that might be real or imaginary based upon the positive value or negative value that we get from the calculation of
. If the calculation gives negative value in code, we might get an error. So we need to set up a condition in a code.
So first we will calculate and store the result in another variable
det
(let say). Then we proceed only if the value of det is greater or equal to zero. Because we don’t want to proceed with the negative value of det
, as square root of negative value gives an imaginary part.
program quadratic
implicit none
real :: a, b, c
real :: det
real :: root1, root2
! using value of a, b and c from
a = 1
b = 5
c = 6
det = b**2 - 4*a*c
! checking condition to avoid error due to imaginary value
if (det => 0)then
root1 = (-b + sqrt(det))/2*a
root2 = (-b - sqrt(det))/2*a
end if
! printing the final result
print*, root1, root2
end program
The output of the above code is:
-2.00000000 -3.00000000
You can make the above code even more dynamic by asking the user to put the value of a,b and c.
For the user input, you have to use read(*,*)
statement. See the code below:
program quadratic
implicit none
real :: a, b, c
real :: det
real :: root1, root2
! asking user for the value of a,b and c
write(*,*)"Enter the value of a,b and c."
read(*,*)a, b, c
det = b**2 - 4*a*c
! checking condition to avoid error due to imaginary value
if (det => 0)then
root1 = (-b + sqrt(det))/2*a
root2 = (-b - sqrt(det))/2*a
end if
! printing the final result
print*, root1, root2
end program
Output:
Enter the value of a, b and c
1, 5, 6
-2.00000000 -3.00000000
You can check using different values of a, b and c. Play around.
Now try to write a code to show the roots even for imaginary number. Can you??
And also try to put the condition when a=0, b=0 and c=0.
Have Fun. Enjoy coding.
If you are unclear I recommend you watching the video on this lesson.
Thanks Sir
Very good teaching