Runge–Kutta Method (2nd & 4th Order)

Source Code:

(a) Runge–Kutta 2nd Order

Write a program in C to solve π’‡π’“π’‚π’„π’…π’šπ’…π’™ = 𝒙 + π’š with π’š (𝟎) = 𝟏 at 𝒙 = 𝟎. 𝟏 using the Runge–Kutta 2nd Order Method.

#include <stdio.h>
#include <conio.h>
double f(double x,double y){ return x + y; }
int main(){
    clrscr();
    double x=0,y=1,h=0.1,k1,k2;
    k1 = f(x,y);
    k2 = f(x+h,y+h*k1);
    y = y + (h/2)*(k1+k2);
    x = x + h;
    printf("\n\n\ty(%.1f)=%.4f\n",x,y);
    getch();
    return 0;
}

Output

(b) Runge–Kutta 4th Order

Write a program in C to solve π’‡π’“π’‚π’„π’…π’šπ’…π’™ = 𝒙 + π’š with π’š (𝟎) = 𝟏 at 𝒙 = 𝟎. 𝟏 using the Runge–Kutta 4th Order Method.

#include <stdio.h>
#include <conio.h>
double f(double x,double y){ return x + y; }
int main(){
    clrscr();
    double x=0,y=1,h=0.1,k1,k2,k3,k4;
    k1=f(x,y);
    k2=f(x+h/2,y+h*k1/2);
    k3=f(x+h/2,y+h*k2/2);
    k4=f(x+h,y+h*k3);
    y = y + (h/6)*(k1+2*k2+2*k3+k4);
    x = x + h;
    printf("\n\n\ty(%.1f)=%.4f\n",x,y);
    getch();
    return 0;
}

Output