# Numerical Methods: Solution of non-linear equations by using Bisection method in C

**Algorithm:**

- Declare and initialize necessary variables like up_range, mid, low_range etc.
- Read the range( upper and lower) from user within which the root of the equation is to be calculated.
- If root lies within the range? if yes: go to step 4. if no: go to step 2
- Calculate the mid value of upper and lower range, mid = (upper+lower)/2
- Calculate the functional value at mid i.e. func(mid).
- If func(mid)*func(low_range) is less than zero, then replace upper range by mid else replace lower range by mid
- Display the no of iteration and root
- if func(mid) is very small? yes: go to step 9. No: go to step 4
- Display the value of most closest and accurate root.

**Source Code:**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include<stdio.h> #include<math.h> //function that returns the functional value float func(float x){ return (pow(x,3)+5*pow(x,2)-7); } int main(){ float up_range, low_range, mid; int i = 0; //no of iteration printf("Enter the range: "); scanf("%f%f",&up_range,&low_range); while(func(up_range)*func(low_range) > 0){ //repeatadly read until the range has root printf("\nThis range doesnot contains any root"); printf("\nEnter again the range: "); scanf("%f%f",&up_range,&low_range); } do{ mid = (up_range + low_range) / 2; if(func(low_range) * func(mid) < 0){ //if signs of mid and low_range is up_range = mid; //different, replace up_range by mid }else{ //else raplace, low_range by mid low_range = mid; } i++; printf("\nAt iteration: %d, root = %f",i,mid); }while(fabs(func(mid))> 0.0001); printf("\nThe root of the equation is %f", mid); return 0; } |

**Output: **

1 | <a href="http://lh3.ggpht.com/-yYuvrO-_Kts/TmRvNYIVBbI/AAAAAAAAAEE/TjgwhrNosZ8/s1600-h/bisection3.jpg"><img style="display: inline; border-width: 0px;" title="bisection" src="http://lh6.ggpht.com/-x9xjKyyNp0U/TmRvQ6PeF3I/AAAAAAAAAEI/POeo1ZBxLPw/bisection_thumb1.jpg?imgmax=800" alt="bisection" width="438" height="381" border="0" /></a> |

wrong h