C code using Euler Method

Problem: Here we have to find dy/dx=x+y where y(0)=1 at the point x=0.05 and x=0.10 taking h=0.05

Algorithm:

  1. Start
  2. Define function
  3. Get the values of x0, y0, h and xn
    *Here x0 and y0 are the initial conditions
    h is the interval
    xn is the required value
  4. n = (xn – x0)/h + 1
  5. Start loop from i=1 to n
  6. y = y0 + h*f(x0,y0)
    x = x + h
  7. Print values of y0 and x0
  8. Check if x < xn
    If yes, assign x0 = x and y0 = y
    If no, goto 9.
  9. End loop i
  10. Stop

 

Code:

#include<stdio.h>
float fun(float x,float y)
{
    float f;
    f=x+y;
    return f;
}
main()
{
    float a,b,x,y,h,t,k;
    printf("\nEnter x0,y0,h,xn: ");
    scanf("%f%f%f%f",&a,&b,&h,&t);
    x=a;
    y=b;
    printf("\n  x\t  y\n");
    while(x<=t)
    {
        k=h*fun(x,y);
        y=y+k;
        x=x+h;
        printf("%0.3f\t %0.3f\n",x,y);
    }
}

 Output:

euler

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *