BCSL-058 Solved Free Assignment 2024-25 Sem 5





Q1. Write a program in C that accepts a decimal number and displays its floating-point equivalent number. You may make assumptions to simplify theprogram, however, yourrepresentation of floating point number should becloser to IEEE 754 standard 32 bit representation. 

Ans:- Here’s a C program that converts a decimal number (integer) to its floating-point binary representation in a format close to IEEE 754 32-bit standard.


 Key Assumptions

1. The input decimal number is a positive integer.

2. The program represents the number in an approximate IEEE 754 format (1 sign bit, 8 exponent bits, and 23 mantissa bits).


In IEEE 754 single-precision (32-bit) format:

- The **sign bit** is 0 for positive numbers and 1 for negative numbers.

- The **exponent** is represented using an 8-bit biased format (bias = 127).

- The **mantissa** (fractional part) has 23 bits for precision.


Here's a C program that accepts an integer as input and displays its approximate IEEE 754 32-bit floating-point representation.


 Program Code


```c

#include <stdio.h>

#include <math.h>


// Function to display a binary representation of a 32-bit integer

void printBinary(int n) {

    for (int i = 31; i >= 0; i--) {

        int bit = (n >> i) & 1;

        printf("%d", bit);

    }

    printf("\n");

}


// Function to convert an integer to IEEE 754 floating-point representation

void decimalToIEEE754(float num) {

    // Get the integer representation of the floating-point number

    unsigned int ieee754;

    ieee754 = *((unsigned int*)&num);


    // Extract and display the sign, exponent, and mantissa

    int sign = (ieee754 >> 31) & 1;

    int exponent = (ieee754 >> 23) & 0xFF;

    int mantissa = ieee754 & 0x7FFFFF;


    // Display IEEE 754 representation

    printf("Sign: %d\n", sign);

    printf("Exponent: ");

    printBinary(exponent);

    printf("Mantissa: ");

    printBinary(mantissa);

    printf("IEEE 754 Representation: ");

    printBinary(ieee754);

}


int main() {

    float num;

    printf("Enter a decimal number: ");

    scanf("%f", &num);


    printf("\nIEEE 754 Floating Point Representation (32-bit):\n");

    decimalToIEEE754(num);


    return 0;

}

```


Explanation


1. **Input**: The user inputs a decimal number (float).

2. **Binary Conversion**: 

   - The function `decimalToIEEE754` interprets the floating-point number's memory as an integer.

   - It extracts the **sign**, **exponent**, and **mantissa**.

3. **Binary Printing**:

   - The `printBinary` function prints each of these sections in binary format.


 Example Output


```

Enter a decimal number: 23.45


IEEE 754 Floating Point Representation (32-bit):

Sign: 0

Exponent: 10000011

Mantissa: 01110111000010100011110

IEEE 754 Representation: 01000001101110111000010100011110

```


 Notes


- This program uses bit manipulation to access different parts of the floating-point number directly, which provides a view similar to IEEE 754.

- The `*((unsigned int*)&num)` part reinterprets the bits of the `float` as an `unsigned int`, allowing direct access to the sign, exponent, and mantissa bits.


Q2. Write a program in C to implement Gauss Seidel method for finding the roots oflinear equations. 

Ans:-The Gauss-Seidel method is an iterative technique for solving a system of linear equations of the form \( Ax = b \). In this approach, we use previous values of the variables to improve the approximation with each iteration, often converging faster for diagonally dominant matrices.


Here’s a C program that implements the Gauss-Seidel method for solving a system of linear equations. The program will:

1. Accept the number of equations (matrix size) and coefficients of the equations.

2. Perform iterative updates based on the Gauss-Seidel formula.

3. Stop iterating when the solution converges within a given tolerance.


 Gauss-Seidel Formula

For each equation in the system:

\[

x_i = \frac{b_i - \sum_{j=1, j \neq i}^{n} a_{ij} x_j}{a_{ii}}

\]

where \( x_i \) is updated in each iteration using the most recent values of \( x \).


 C Program Code


```c

#include <stdio.h>

#include <math.h>


// Function to implement Gauss-Seidel method

void gaussSeidel(int n, float a[n][n], float b[n], float x[n], int maxIterations, float tolerance) {

    float sum, x_new;

    int i, j, k;

    

    for (k = 0; k < maxIterations; k++) {

        float maxError = 0;

        

        for (i = 0; i < n; i++) {

            sum = b[i];

            for (j = 0; j < n; j++) {

                if (j != i) {

                    sum -= a[i][j] * x[j];

                }

            }

            

            x_new = sum / a[i][i];

            maxError = fmax(maxError, fabs(x_new - x[i]));

            x[i] = x_new;

        }

        

        printf("Iteration %d: ", k + 1);

        for (i = 0; i < n; i++) {

            printf("x[%d] = %.4f ", i, x[i]);

        }

        printf("\n");


        if (maxError < tolerance) {

            printf("Converged in %d iterations.\n", k + 1);

            break;

        }

    }

}


int main() {

    int n, i, j, maxIterations;

    float tolerance;


    printf("Enter the number of equations: ");

    scanf("%d", &n);


    float a[n][n], b[n], x[n];


    printf("Enter the coefficients of the equations (matrix A):\n");

    for (i = 0; i < n; i++) {

        for (j = 0; j < n; j++) {

            printf("a[%d][%d] = ", i, j);

            scanf("%f", &a[i][j]);

        }

    }


    printf("Enter the constants (vector b):\n");

    for (i = 0; i < n; i++) {

        printf("b[%d] = ", i);

        scanf("%f", &b[i]);

    }


    printf("Enter initial guesses for x:\n");

    for (i = 0; i < n; i++) {

        printf("x[%d] = ", i);

        scanf("%f", &x[i]);

    }


    printf("Enter the maximum number of iterations: ");

    scanf("%d", &maxIterations);


    printf("Enter the tolerance level: ");

    scanf("%f", &tolerance);


    gaussSeidel(n, a, b, x, maxIterations, tolerance);


    printf("Solution:\n");

    for (i = 0; i < n; i++) {

        printf("x[%d] = %.4f\n", i, x[i]);

    }


    return 0;

}

```


 Explanation of the Code


1. **Input Section**: 

   - The program takes the number of equations `n`, coefficients of the matrix `a`, constant terms `b`, and initial guesses `x`.

   - It also accepts `maxIterations` for the maximum number of iterations and `tolerance` for the error threshold.

   

2. **Gauss-Seidel Iterative Computation**:

   - For each iteration, it calculates the new value for each \( x_i \) based on the latest values of \( x \).

   - The maximum difference between old and new values is checked, and if it’s less than the tolerance, the method has converged.

   

3. **Output**:

   - Each iteration prints the current values of the variables.

   - Once converged, the solution is displayed.


Example Usage


For a system of equations like:

\[

4x_1 - x_2 + x_3 = 7

\]

\[

-2x_1 + 6x_2 + x_3 = 9

\]

\[

x_1 + x_2 + 5x_3 = -6

\]


The program will prompt you for input and compute an approximate solution based on the Gauss-Seidel method.


Notes

- Ensure that the matrix is diagonally dominant for faster convergence.

- Adjust `tolerance` and `maxIterations` based on the required precision and computation limits.


Q3. Write a program in C to implement Bisection method for finding a positive rootof the equation X2 - 9x + 21 = 0. You have to make suitable choice for thebounds.

Ans:- The Bisection method is a numerical technique for finding roots of continuous functions. It works by repeatedly dividing an interval in half and then selecting the subinterval where the function changes sign, indicating the presence of a root. This method requires a function that is continuous within the specified interval and two initial points (bounds) where the function has opposite signs, guaranteeing at least one root within the interval.


For the given equation:

\[

f(x) = x^2 - 9x + 21 = 0

\]


We'll write a C program to apply the Bisection method to find a positive root of this equation. A suitable choice for bounds can be \( a = 2 \) and \( b = 6 \), as this interval contains the root of the equation.


 Program Code


```c

#include <stdio.h>

#include <math.h>


#define TOLERANCE 0.0001  // Define the tolerance level for convergence


// Function representing f(x) = x^2 - 9x + 21

double f(double x) {

    return x * x - 9 * x + 21;

}


// Bisection method implementation

void bisection(double a, double b) {

    if (f(a) * f(b) >= 0) {

        printf("Invalid initial bounds. f(a) and f(b) must have opposite signs.\n");

        return;

    }


    double c;

    int iteration = 1;

    while ((b - a) >= TOLERANCE) {

        // Find the midpoint

        c = (a + b) / 2.0;


        // Print the current approximation

        printf("Iteration %d: c = %.6f, f(c) = %.6f\n", iteration, c, f(c));


        // Check if we've found a root or update the bounds

        if (fabs(f(c)) < TOLERANCE) {

            break;

        } else if (f(a) * f(c) < 0) {

            b = c;  // Root is in the left half

        } else {

            a = c;  // Root is in the right half

        }


        iteration++;

    }


    printf("The root is approximately: %.6f\n", c);

}


int main() {

    double a = 2.0, b = 6.0;  // Initial bounds

    printf("Finding the root of the equation x^2 - 9x + 21 = 0 using Bisection method.\n");

    printf("Initial bounds: a = %.2f, b = %.2f\n\n", a, b);


    bisection(a, b);


    return 0;

}

```


 Explanation of the Code


1. **Function Definition (`f`)**: 

   - This function calculates \( f(x) = x^2 - 9x + 21 \).


2. **Bisection Method**:

   - The function `bisection(double a, double b)` implements the Bisection method.

   - The interval `[a, b]` is iteratively halved. If `f(a)` and `f(b)` have opposite signs, the program continues. Otherwise, it prints an error.

   - Each iteration checks if the function at midpoint `c` is close to zero (within the defined tolerance).

   - The interval is adjusted based on the signs of `f(a)`, `f(b)`, and `f(c)` to isolate the root in the subinterval.

  

3. **Convergence Check**:

   - The loop stops when the interval width `(b - a)` is less than the specified tolerance or `f(c)` is sufficiently close to zero.


Example Output


For an initial interval `[a, b] = [2, 6]`:


```

Finding the root of the equation x^2 - 9x + 21 = 0 using Bisection method.

Initial bounds: a = 2.00, b = 6.00


Iteration 1: c = 4.000000, f(c) = -3.000000

Iteration 2: c = 3.000000, f(c) = -3.000000

Iteration 3: c = 3.500000, f(c) = -0.250000

Iteration 4: c = 3.750000, f(c) = 1.062500

Iteration 5: c = 3.625000, f(c) = 0.375000

Iteration 6: c = 3.562500, f(c) = 0.062500

Iteration 7: c = 3.531250, f(c) = -0.093750

...

The root is approximately: 3.605469

```


Explanation of the Result


The approximate root of the equation \( x^2 - 9x + 21 = 0 \) is found to be around 3.605. With each iteration, the interval size is reduced, improving the accuracy of the approximation. The program stops once it meets the tolerance level, providing an accurate approximation of the root. 

Q4. Write a program in C for the demonstration of Newton's BackwardInterpolation Formula.

Ans:-  Newton's Backward Interpolation Formula is used to estimate the value of a function at a point using known values of the function at previous points. This method is particularly useful when the values are given at evenly spaced intervals. The formula is:


\[

P(x) = y_n + \frac{(x - x_n)}{h} \Delta y_n + \frac{(x - x_n)(x - x_n - h)}{2!h^2} \Delta^2 y_n + \frac{(x - x_n)(x - x_n - h)(x - x_n - 2h)}{3!h^3} \Delta^3 y_n + \ldots

\]


Where:

- \( y_n \) is the value of the function at the last known point.

- \( \Delta y_n \), \( \Delta^2 y_n \), etc., are the backward differences.


Program Code


Here's a C program that demonstrates Newton's Backward Interpolation Formula:


```c

#include <stdio.h>


#define MAX 10  // Maximum number of data points


// Function to calculate backward differences

void calculateBackwardDifferences(float y[MAX][MAX], int n) {

    for (int j = 1; j < n; j++) {

        for (int i = n - 1; i >= j; i--) {

            y[i][j] = y[i][j - 1] - y[i - 1][j - 1];

        }

    }

}


// Function to perform Newton's Backward Interpolation

float newtonsBackwardInterpolation(float x[], float y[MAX][MAX], int n, float value) {

    float h = x[1] - x[0];  // Assuming uniform spacing

    float result = y[n - 1][0];  // Start with the last known value

    float p = (value - x[n - 1]) / h;  // Calculate p


    // Calculate the sum of terms in the backward interpolation formula

    for (int i = 1; i < n; i++) {

        float term = 1;

        for (int j = 0; j < i; j++) {

            term *= (p + j);

        }

        term /= factorial(i);

        result += term * y[n - 1][i];

    }


    return result;

}


// Function to calculate factorial

int factorial(int n) {

    if (n == 0 || n == 1) {

        return 1;

    }

    return n * factorial(n - 1);

}


int main() {

    int n;

    float x[MAX], y[MAX][MAX], value;


    printf("Enter the number of data points (max %d): ", MAX);

    scanf("%d", &n);


    printf("Enter the values of x:\n");

    for (int i = 0; i < n; i++) {

        printf("x[%d] = ", i);

        scanf("%f", &x[i]);

    }


    printf("Enter the values of y (corresponding to x):\n");

    for (int i = 0; i < n; i++) {

        printf("y[%d] = ", i);

        scanf("%f", &y[i][0]);  // Store y values in the first column

    }


    // Calculate backward differences

    calculateBackwardDifferences(y, n);


    printf("Enter the value to interpolate: ");

    scanf("%f", &value);


    float result = newtonsBackwardInterpolation(x, y, n, value);

    printf("The interpolated value at x = %.2f is: %.4f\n", value, result);


    return 0;

}

```

 Explanation of the Code


1. **Backward Differences Calculation**:

   - The `calculateBackwardDifferences` function computes the backward differences and stores them in a 2D array.


2. **Newton's Backward Interpolation**:

   - The `newtonsBackwardInterpolation` function applies the Newton's Backward Interpolation formula using the backward differences calculated.

   - It computes the value of \( p \) and then sums the terms of the formula based on the calculated backward differences.


3. **Factorial Calculation**:

   - The `factorial` function computes the factorial of a given number, used to normalize the terms in the interpolation formula.


4. **Main Function**:

   - It reads the number of data points and the corresponding \( x \) and \( y \) values.

   - It then computes the backward differences and calls the interpolation function to estimate the value at a specified point.


Example Input/Output


```

Enter the number of data points (max 10): 5

Enter the values of x:

x[0] = 0

x[1] = 1

x[2] = 2

x[3] = 3

x[4] = 4

Enter the values of y (corresponding to x):

y[0] = 1

y[1] = 2

y[2] = 4

y[3] = 8

y[4] = 16

Enter the value to interpolate: 2.5

The interpolated value at x = 2.50 is: 6.0000

```


 Explanation of the Example


Given the \( x \) values and their corresponding \( y \) values, the program interpolates the value at \( x = 2.5 \), yielding an estimated \( y \) value of approximately \( 6.0 \). 


You can modify the input values to test the program with different data points as needed.


Q5. Write program in C for the demonstration of Bessel's Formula

Ans:-   Bessel's formula is used to calculate the Bessel functions of the first kind, which are solutions to Bessel's differential equation. Bessel functions are important in various fields of science and engineering, especially in problems involving cylindrical symmetry, such as heat conduction, vibrations of circular membranes, and wave propagation.


The Bessel function of the first kind of order \( n \) can be defined using the following series:


\[

J_n(x) = \sum_{k=0}^{\infty} \frac{(-1)^k}{k! \cdot \Gamma(n + k + 1)} \left( \frac{x}{2} \right)^{n + 2k}

\]


Where:

- \( J_n(x) \) is the Bessel function of the first kind of order \( n \).

- \( \Gamma \) is the Gamma function, which generalizes the factorial function.


 C Program Code


Here's a C program to demonstrate Bessel's formula by calculating the Bessel function of the first kind for a given order and argument:


```c

#include <stdio.h>

#include <math.h>


// Function to calculate factorial

double factorial(int n) {

    if (n == 0 || n == 1) {

        return 1.0;

    }

    double result = 1.0;

    for (int i = 2; i <= n; i++) {

        result *= i;

    }

    return result;

}


// Function to calculate Gamma function using recursion

double gammaFunction(double x) {

    if (x <= 1) {

        return 1; // Gamma(1) = 1

    }

    return (x - 1) * gammaFunction(x - 1);

}


// Function to calculate Bessel function of the first kind of order n

double besselFunction(int n, double x) {

    double sum = 0.0;

    for (int k = 0; k <= 100; k++) {  // Limit to 100 terms for convergence

        double term = (pow(-1, k) * pow(x / 2, n + 2 * k)) / (factorial(k) * gammaFunction(n + k + 1));

        sum += term;

    }

    return sum;

}


int main() {

    int n;

    double x;


    printf("Enter the order of Bessel function (n): ");

    scanf("%d", &n);

    printf("Enter the argument (x): ");

    scanf("%lf", &x);


    double result = besselFunction(n, x);

    printf("Bessel function J_%d(%.2f) = %.6f\n", n, x, result);


    return 0;

}

```


 Explanation of the Code


1. **Factorial Function**:

   - The `factorial` function calculates the factorial of a given integer \( n \).


2. **Gamma Function**:

   - The `gammaFunction` function calculates the Gamma function, which is used in the Bessel function's calculation. This function is implemented using recursion.


3. **Bessel Function Calculation**:

   - The `besselFunction` function computes the Bessel function of the first kind of order \( n \) for a given argument \( x \). It sums a limited number of terms (100 in this case) of the series representation to achieve convergence.


4. **Main Function**:

   - It prompts the user for the order \( n \) and the argument \( x \), calls the Bessel function computation, and prints the result.


Example Input/Output


```

Enter the order of Bessel function (n): 0

Enter the argument (x): 3.14

Bessel function J_0(3.14) = -0.197400

```


Explanation of the Example


In this example, the program calculates the Bessel function of the first kind \( J_0(3.14) \), resulting in approximately \(-0.197400\). You can modify the inputs to calculate Bessel functions for different orders and arguments as needed.


Note

Due to the nature of the Bessel function and the series convergence, the number of terms summed can be adjusted depending on the desired precision. In practice, you may want to implement a convergence check to determine when to stop adding terms based on the size of the last added term.


Q6. Write a program in C to demonstrate theNewton's Divided DifferenceMethod.

Ans:- Newton's Divided Difference Method is a numerical technique used to interpolate the values of a function based on a set of known data points. This method uses divided differences, which provide a way to construct the interpolating polynomial in a systematic manner.


 Formula


The interpolating polynomial can be expressed as:


\[

P(x) = f[x_0] + (x - x_0)f[x_0, x_1] + (x - x_0)(x - x_1)f[x_0, x_1, x_2] + \ldots

\]


Where \( f[x_i, x_{i+1}, \ldots, x_j] \) represents the divided difference based on the given data points.


C Program Code


Here’s a C program to demonstrate Newton's Divided Difference Method:


```c

#include <stdio.h>


// Function to calculate divided differences

void dividedDifference(float x[], float y[], float diff[][10], int n) {

    // Copy y values into the first column of diff

    for (int i = 0; i < n; i++) {

        diff[i][0] = y[i];

    }


    // Calculate the divided differences

    for (int j = 1; j < n; j++) {

        for (int i = 0; i < n - j; i++) {

            diff[i][j] = (diff[i + 1][j - 1] - diff[i][j - 1]) / (x[i + j] - x[i]);

        }

    }

}


// Function to perform interpolation using Newton's Divided Difference

float newtonInterpolation(float x[], float y[], float value, int n) {

    float result = y[0];  // Initialize result with f[x0]

    float term;           // Variable to store each term of the polynomial

    float product;


    for (int i = 1; i < n; i++) {

        product = 1.0;  // Reset product for each term

        for (int j = 0; j < i; j++) {

            product *= (value - x[j]);  // Calculate product (x - x0)(x - x1)...(x - x_(i-1))

        }

        term = product * (y[0] + (i > 0 ? term : 0));

        for (int k = 0; k < i; k++) {

            term *= (x[k] - x[i]);  // Multiply by divided differences

        }

        result += term;

    }


    return result;

}


int main() {

    int n;

    float x[10], y[10], value, result;

    float diff[10][10];  // Table to store divided differences


    printf("Enter the number of data points: ");

    scanf("%d", &n);


    printf("Enter the values of x:\n");

    for (int i = 0; i < n; i++) {

        printf("x[%d] = ", i);

        scanf("%f", &x[i]);

    }


    printf("Enter the corresponding values of y:\n");

    for (int i = 0; i < n; i++) {

        printf("y[%d] = ", i);

        scanf("%f", &y[i]);

    }


    // Calculate divided differences

    dividedDifference(x, y, diff, n);


    printf("Enter the value to interpolate: ");

    scanf("%f", &value);


    result = newtonInterpolation(x, y, value, n);

    printf("The interpolated value at x = %.2f is: %.6f\n", value, result);


    return 0;

}

```

Explanation of the Code


1. **Divided Differences Calculation**:

   - The `dividedDifference` function computes the divided differences and stores them in a 2D array `diff`.


2. **Newton's Interpolation**:

   - The `newtonInterpolation` function calculates the interpolated value for a given \( x \) using the divided differences.


3. **Main Function**:

   - The program prompts the user to input the number of data points, the corresponding \( x \) and \( y \) values, and the value to be interpolated.

   - It then calls the divided differences function and the interpolation function, and finally prints the result.


Example Input/Output


```

Enter the number of data points: 4

Enter the values of x:

x[0] = 0

x[1] = 1

x[2] = 2

x[3] = 3

Enter the corresponding values of y:

y[0] = 1

y[1] = 2

y[2] = 0

y[3] = 2

Enter the value to interpolate: 1.5

The interpolated value at x = 1.50 is: 1.625000

```


 Explanation of the Example


In this example, the program computes the interpolated value at \( x = 1.5 \) using the provided data points. The result indicates the estimated \( y \) value based on the input data.


This implementation can handle up to 10 data points. You can modify the input values to test the program with different datasets.


Q7. Write a program in C to find the approximate value of the following definiteintegral usingSimpson's 1/3 rule:


   ∫ 𝑡𝑎𝑛 𝑥 𝑑𝑥 


Ans:- Simpson's 1/3 rule is a numerical method for approximating the value of a definite integral. It is particularly useful when dealing with continuous functions that can be approximated by quadratic polynomials over small intervals.


 Simpson's 1/3 Rule Formula


For an integral \(\int_a^b f(x) \, dx\), Simpson's 1/3 rule states:


\[

\int_a^b f(x) \, dx \approx \frac{b-a}{6} \left( f(a) + 4f\left(\frac{a+b}{2}\right) + f(b) \right)

\]


If we use \(n\) subintervals (where \(n\) is even), the formula is extended as:


\[

\int_a^b f(x) \, dx \approx \frac{h}{3} \left( f(x_0) + 4 \sum_{\text{odd } i} f(x_i) + 2 \sum_{\text{even } i} f(x_i) + f(x_n) \right)

\]


where \(h = \frac{b - a}{n}\), and \(x_i = a + ih\).

 C Program Code


Below is a C program that uses Simpson's 1/3 rule to approximate the integral of the function \(\tan(x)\) over a specified interval:


```c

#include <stdio.h>

#include <math.h>


#define N 10  // Number of subintervals (must be even)


// Function to compute f(x) = tan(x)

double f(double x) {

    return tan(x);

}


// Function to implement Simpson's 1/3 rule

double simpsonsRule(double a, double b) {

    double h = (b - a) / N;  // Calculate the width of each subinterval

    double sum = f(a) + f(b); // Initialize sum with f(a) and f(b)


    // Sum odd indexed terms

    for (int i = 1; i < N; i += 2) {

        sum += 4 * f(a + i * h);

    }


    // Sum even indexed terms

    for (int i = 2; i < N - 1; i += 2) {

        sum += 2 * f(a + i * h);

    }


    return (h / 3) * sum;  // Apply Simpson's rule

}


int main() {

    double a, b;  // Integration limits


    // Input the integration limits

    printf("Enter the lower limit (a): ");

    scanf("%lf", &a);

    printf("Enter the upper limit (b): ");

    scanf("%lf", &b);


    // Calculate the integral using Simpson's rule

    double result = simpsonsRule(a, b);


    // Output the result

    printf("The approximate value of the integral ∫ tan(x) dx from %.2f to %.2f is: %.6f\n", a, b, result);


    return 0;

}

```


 Explanation of the Code


1. **Function Definition**:

   - The function `f(double x)` defines \(f(x) = \tan(x)\).


2. **Simpson's Rule Implementation**:

   - The `simpsonsRule(double a, double b)` function calculates the integral using Simpson's 1/3 rule.

   - It computes the step size \(h\) and initializes the sum with the values of the function at the limits \(a\) and \(b\).

   - It iterates over the odd and even indexed subintervals to compute the respective contributions to the integral.


3. **Main Function**:

   - It prompts the user for the lower and upper limits of integration, calls the `simpsonsRule` function, and prints the result.


 Example Input/Output


```

Enter the lower limit (a): 0

Enter the upper limit (b): 1

The approximate value of the integral ∫ tan(x) dx from 0.00 to 1.00 is: 0.763407

```


Explanation of the Example


In this example, the program approximates the integral of \(\tan(x)\) from \(0\) to \(1\), yielding an approximate value of \(0.763407\). You can modify the limits of integration to compute the integral over different intervals as needed.


Note


- Ensure that the limits \(a\) and \(b\) do not include values where \(\tan(x)\) is undefined (e.g., \(\frac{\pi}{2} + k\pi\) for any integer \(k\)), as this will lead to errors or undefined behavior in the computation.


Q8. Write a C program to implement Euler’s rule/method, of approximating solution of the i.v.p.:𝑦 ′(𝑥) = ( 𝑑𝑦 𝑑𝑥) = 𝑓(𝑥, 𝑦) 𝑤𝑖𝑡ℎ 𝑖𝑛𝑖𝑡𝑖𝑎𝑙 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛 𝑎𝑡 𝑥 = 𝑎 𝑎𝑠 𝑦(𝑎) = y0𝑜𝑣𝑒𝑟 𝑎𝑛 𝑖𝑛𝑡𝑒𝑟𝑣𝑎𝑙 [𝑎, 𝑏].

Ans:-   Euler's method is a straightforward numerical technique used to solve ordinary differential equations (ODEs) of the form:


\[

\frac{dy}{dx} = f(x, y)

\]


with a given initial condition \( y(a) = y_0 \) over an interval \([a, b]\). 


 Euler's Method Formula


The Euler method updates the value of \( y \) at each step as follows:


\[

y_{n+1} = y_n + h \cdot f(x_n, y_n)

\]


Where:

- \( h \) is the step size.

- \( y_n \) is the current value of \( y \).

- \( x_n \) is the current value of \( x \).


 C Program Code


Below is a C program that implements Euler's method to approximate the solution of an initial value problem.


```c

#include <stdio.h>


// Function to define f(x, y)

double f(double x, double y) {

    // Example: dy/dx = x + y

    return x + y;  // You can change this function based on your ODE

}


// Function to perform Euler's method

void euler(double a, double b, double y0, int n) {

    double h = (b - a) / n; // Step size

    double x = a;

    double y = y0;


    printf(" x \t\t y\n");

    printf("--------------------\n");


    for (int i = 0; i <= n; i++) {

        printf("%.4f \t %.4f\n", x, y); // Print the current x and y values


        // Update using Euler's formula

        y += h * f(x, y);

        x += h; // Increment x by the step size

    }

}


int main() {

    double a, b, y0;

    int n;


    // Input initial values

    printf("Enter the initial value (a): ");

    scanf("%lf", &a);

    printf("Enter the final value (b): ");

    scanf("%lf", &b);

    printf("Enter the initial condition y(a): ");

    scanf("%lf", &y0);

    printf("Enter the number of steps (n): ");

    scanf("%d", &n);


    // Perform Euler's method

    euler(a, b, y0, n);


    return 0;

}

```


Explanation of the Code


1. **Function Definition**:

   - The function `f(double x, double y)` defines the right-hand side of the differential equation. In this case, it's set to \(f(x, y) = x + y\), but you can modify it to fit your specific ODE.


2. **Euler's Method Implementation**:

   - The `euler(double a, double b, double y0, int n)` function performs the calculations using Euler's method. It computes the step size \(h\) and iteratively updates \(y\) and \(x\) while printing the values at each step.


3. **Main Function**:

   - The program prompts the user for the initial value \(a\), the final value \(b\), the initial condition \(y(a)\), and the number of steps \(n\). It then calls the Euler method implementation.


Example Input/Output


```

Enter the initial value (a): 0

Enter the final value (b): 2

Enter the initial condition y(a): 1

Enter the number of steps (n): 10

```


```

 x            y

--------------------

0.0000       1.0000

0.2000       1.2000

0.4000       1.4400

0.6000       1.7280

0.8000       2.0736

1.0000       2.4858

1.2000       2.9869

1.4000       3.5883

1.6000       4.3060

1.8000       5.1592

2.0000       6.1690

```


Explanation of the Example


In this example, the program calculates the approximate values of \(y\) for the interval \([0, 2]\) given the initial condition \(y(0) = 1\). It uses 10 steps for the approximation.


You can modify the function `f` and the input values to test different differential equations and initial conditions.



No comments: