33
Total Posts
3
Categories
24/7
Updated

C++

Write a program to find the numerical solution of Differential equations by using Runge Kutta method / Euler method.

Published on Dec 22, 2025
#include <iostream>
using namespace std;

// Differential equation dy/dx = f(x, y)
double f(double x, double y) {
    return x + y;
}

int main() {
    int choice, n;
    double x0, y0, xn, h, x, y;

    cout << "Choose Method:\n";
    cout << "1. Euler Method\n";
    cout << "2. Runge-Kutta 4th Order Method\n";
    cout << "Enter choice: ";
    cin >> choice;

    cout << "Enter initial values x0 and y0: ";
    cin >> x0 >> y0;

    cout << "Enter final value of x (xn): ";
    cin >> xn;

    cout << "Enter step size h: ";
    cin >> h;

    n = (xn - x0) / h;
    x = x0;
    y = y0;

    switch (choice) {

    // -------- Euler Method --------
    case 1:
        cout << "\nUsing Euler Method\n";
        cout << "x\t y\n";
        for (int i = 0; i <= n; i++) {
            cout << x << "\t " << y << endl;
            y = y + h * f(x, y);
            x = x + h;
        }
        break;

    // -------- Runge-Kutta Method --------
    case 2:
        cout << "\nUsing Runge-Kutta 4th Order Method\n";
        cout << "x\t y\n";
        for (int i = 0; i <= n; i++) {
            cout << x << "\t " << y << endl;

            double k1 = h * f(x, y);
            double k2 = h * f(x + h / 2, y + k1 / 2);
            double k3 = h * f(x + h / 2, y + k2 / 2);
            double k4 = h * f(x + h, y + k3);

            y = y + (k1 + 2*k2 + 2*k3 + k4) / 6;
            x = x + h;
        }
        break;

    default:
        cout << "Invalid choice!" << endl;
    }

    return 0;
}

Documentation

Output Using Euler Method
x       y
0       1
0.1     1.1
0.2     1.22
0.3     1.364

Output Using Runge-Kutta 4th Order Method
x       y
0       1
0.1     1.11034
0.2     1.24281
0.3     1.39972


✔ Euler Method
✔ Runge–Kutta Method (4th Order)

 

Problem Assumption

Solve the differential equation:

dy/dx=f(x,y)=x+y

with given initial condition:

y(x0)=y0