0% found this document useful (0 votes)
3 views71 pages

C++ Assignment 1001

The document outlines a Math Lab III course (Math-310) that includes various programming exercises in C++. It covers basic arithmetic operations, object-oriented programming concepts, and includes tasks such as creating classes for bank accounts, students, and calculators. Each exercise is accompanied by sample code and expected output.

Uploaded by

tazicety1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views71 pages

C++ Assignment 1001

The document outlines a Math Lab III course (Math-310) that includes various programming exercises in C++. It covers basic arithmetic operations, object-oriented programming concepts, and includes tasks such as creating classes for bank accounts, students, and calculators. Each exercise is accompanied by sample code and expected output.

Uploaded by

tazicety1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Course Code: Math-310 Course Title: Math Lab III

1
Course Code: Math-310 Course Title: Math Lab III

Basic Problems

1. Sum of Two Numbers: Write a program that takes two integers and
prints
their sum.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "Sum: " << a + b << endl;
return 0;
}

Output:
Enter two integers: 5 3
Sum: 8

2. Difference of Two Numbers: Write a program that takes two integers


and
prints their difference.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "Difference: " << a - b << endl;
return 0;
}

2
Course Code: Math-310 Course Title: Math Lab III

Output:
Enter two integers: 8 3
Difference: 5

3. Product of Two Numbers: Write a program that takes two integers and
prints their product.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "Product: " << a * b << endl;
return 0;
}

Output:
Enter two integers: 4 5
Product: 20

4. Division of Two Numbers: Write a program that takes two integers and
prints their division (check for division by zero).

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
if (b == 0)
cout << "Error: Division by zero is not allowed." << endl;
else
cout << "Division: " << static_cast<double>(a) / b << endl;
return 0;
}

3
Course Code: Math-310 Course Title: Math Lab III

Output 1:
Enter two integers: 10 2
Division: 5
Output 2:
Enter two integers: 5 0
Error: Division by zero is not allowed.

5. Write a program to find the modulus of two integers.

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
if (b == 0)
cout << "Error: Modulus by zero is undefined." << endl;
else
cout << "Modulus: " << a % b << endl;
return 0;
}

Output 1:
Enter two integers: 10 3
Modulus: 1
Output 2:
Enter two integers: 5 0
Error: Modulus by zero is undefined.

6. Write a program that takes a number and prints its square.

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Square: " << num * num << endl;
return 0;

4
Course Code: Math-310 Course Title: Math Lab III

Output:
Enter a number: 4
Square: 16

7. Write a program that takes a number and prints its cube.

#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << "Cube: " << num * num * num << endl;
return 0;
}

Output:
Enter a number: 3
Cube: 27

8. Write a program to check if a number is positive, negative, or zero.

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num > 0)
cout << "Positive" << endl;
else if (num < 0)
cout << "Negative" << endl;
else
cout << "Zero" << endl;
return 0;
}

5
Course Code: Math-310 Course Title: Math Lab III

Output 1:
Enter a number: 5
Positive
Output 2:
Enter a number: -3
Negative
Output 3:
Enter a number: 0
Zero

9. Write a program to check if a number is even or odd.

#include <iostream>
using namespace std;

int main() {
int num;
cout << "Enter a number: ";
cin >> num;
cout << (num % 2 == 0 ? "Even" : "Odd") << endl;
return 0;
}

Output 1:
Enter a number: 4
Even
Output 2:
Enter a number: 7

10. Write a program to compute the absolute value of an integer.

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
cout << "Absolute value: " << abs(num) << endl;
return 0;

6
Course Code: Math-310 Course Title: Math Lab III

Output 1:
Enter an integer: -5
Absolute value: 5
Output 2:
Enter an integer: 3
Absolute value: 3

7
Course Code: Math-310 Course Title: Math Lab III

8
Course Code: Math-310 Course Title: Math Lab III

Object-oriented Programming

1. Create a class Bank Account with methods to deposit, withdraw, and


check balance. Initialize an account with a balance of 1000, deposit 500,
withdraw 200, and display the final balance.

#include <iostream>
using namespace std;

class BankAccount {
private:
double balance;
public:
BankAccount(double initial_balance = 1000) {
balance = initial_balance;
}

void deposit(double amount) {


balance += amount;
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
cout << "Insufficient balance." << endl;
}
}

double check_balance() const {


return balance;
}
}

int main() {
BankAccount account;
account.deposit(500);
account.withdraw(200);
cout << "Final balance: " << account.check_balance() << endl;
return 0;

9
Course Code: Math-310 Course Title: Math Lab III

}
Output:
Final Balance: 1300

2. Write a program that defines a Student class with name and ID. Create a
student object with your name and ID, and display the student details.

#include <iostream>
using namespace std;

class Student {
private:
string name;
int id;

public:
Student(string studentName, int studentID) {
name = studentName;
id = studentID;
}

void displayDetails() const {


cout << "Student Name: " << name << endl;
cout << "Student ID: " << id << endl;
}
}

int main() {
Student student("Khan Mohaimenul Islam", 20203111);
student.displayDetails();

return 0;
}

Output:
Student Name: Khan Mohaimenul Islam
Student ID: 20203111

3. Design a class that stores course grades and credit hours. Implement a
method to calculate GPA using the formula:

10
Course Code: Math-310 Course Title: Math Lab III

(grade×credit)

GPA=

credit

Add two courses with grades and credits and print the GPA.

#include <iostream>
#include <vector>
using namespace std;

class Course {
private:
vector<double> grades;
vector<int> credits;

public:
void addCourse(double grade, int credit) {
grades.push_back(grade);
credits.push_back(credit);
}

double calculateGPA() const {


double totalPoints = 0;
int totalCredits = 0;

for (size_t i = 0; i < grades.size(); ++i) {


totalPoints += grades[i] * credits[i];
totalCredits += credits[i];
}

if (totalCredits == 0)
return 0;

return totalPoints / totalCredits;


}
}

11
Course Code: Math-310 Course Title: Math Lab III

int main() {
Course studentCourses;
studentCourses.addCourse(3.7, 3); // Grade A- (3 credit hours)
studentCourses.addCourse(3.0, 4); // Grade B (4 credit hours)

cout << "GPA: " << studentCourses.calculateGPA() << endl;

return 0;
}

Output:
GPA: 3.32857

4. Make a Book class that tracks whether a book is checked out or


available.
Create a few books and show their availability status before and after
checking one out.

#include <iostream>
using namespace std;

class Book {
private:
string title;
bool isCheckedOut;

public:
Book(string bookTitle) {
title = bookTitle;
isCheckedOut = false;
}

void checkOut() {
if (!isCheckedOut) {
isCheckedOut = true;
cout << title << " has been checked out." << endl;
} else {
cout << title << " is already checked out." << endl;

12
Course Code: Math-310 Course Title: Math Lab III

}
}

void displayStatus() const {


cout << title << " is " << (isCheckedOut ? "Checked Out" : "Available") <<
endl;
}
};

int main() {
Book book1("1984");
Book book2("The Alchemist");
Book book3("To Kill a Mockingbird");

// Show initial status


book1.displayStatus();
book2.displayStatus();
book3.displayStatus();

cout << endl;

// Check out one book


book2.checkOut();

cout << endl;

// Show updated status


book1.displayStatus();
book2.displayStatus();
book3.displayStatus();

return 0;
}

Output:
1984 is Available
The Alchemist is Available
To Kill a Mockingbird is Available

The Alchemist has been checked out.

13
Course Code: Math-310 Course Title: Math Lab III

1984 is Available
The Alchemist is Checked Out
To Kill a Mockingbird is Available

5. Write a Calculator class with methods for addition, subtraction,


multiplication, and division. Demonstrate all four operations with the
numbers 5 and 3.

#include <iostream>
using namespace std;

class Calculator {
public:
double add(double a, double b) {
return a + b;
}

double subtract(double a, double b) {


return a - b;
}

double multiply(double a, double b) {


return a * b;
}

double divide(double a, double b) {


if (b != 0)
return a / b;
else {
cout << "Error: Division by zero!" << endl;
return 0;
}
}
}

int main() {
Calculator calc;
double a = 5, b = 3;

14
Course Code: Math-310 Course Title: Math Lab III

cout << "Addition: " << calc.add(a, b) << endl;


cout << "Subtraction: " << calc.subtract(a, b) << endl;
cout << "Multiplication: " << calc.multiply(a, b) << endl;
cout << "Division: " << calc.divide(a, b) << endl;

return 0;
}

Output:
Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1.66667

6. Create a Ticket class for events. Reserve a ticket and display whether it
is reserved or available.

#include <iostream>
using namespace std;

class Ticket {
private:
bool isReserved;

public:
Ticket() {
isReserved = false;
}

void reserve() {
if (!isReserved) {
isReserved = true;
cout << "Ticket reserved successfully." << endl;
} else {

15
Course Code: Math-310 Course Title: Math Lab III

cout << "Ticket is already reserved." << endl;


}
}

void displayStatus() const {


cout << "Ticket is " << (isReserved ? "Reserved" : "Available") << endl;
}
};

int main() {
Ticket eventTicket;

// Show initial status


eventTicket.displayStatus();

// Reserve the ticket


eventTicket.reserve();

// Show updated status


eventTicket.displayStatus();

return 0;
}
Output:
Ticket is Available
Ticket reserved successfully.
Ticket is Reserved

7. Write a class that calculates the salary of an employee given the hourly
rate and hours worked. Test with an employee working 40 hours at
₹20.5/hour.

#include <iostream>
using namespace std;

class Employee {
private:
double hourlyRate;
double hoursWorked;

16
Course Code: Math-310 Course Title: Math Lab III

public:
Employee(double rate, double hours) {
hourlyRate = rate;
hoursWorked = hours;
}

double calculateSalary() const {


return hourlyRate * hoursWorked;
}
};

int main() {
Employee emp(20.5, 40); // ₹20.5/hour, 40 hours
cout << "Employee Salary: ₹" << emp.calculateSalary() << endl;
return 0;
}

Output:
Employee Salary: ₹820

8. Design a Product class and a Shopping Cart class to hold multiple


products. Calculate the total cost of items in the cart.

#include <iostream>
#include <vector>
using namespace std;

class Product {
private:
string name;
double price;
public:
Product(string n, double p) {
name = n;
price = p;

17
Course Code: Math-310 Course Title: Math Lab III

double getPrice() const {


return price;
}

string getName() const {


return name;
}
}

class ShoppingCart {
private:
vector<Product> items;
public:
void addProduct(const Product& product) {
items.push_back(product);
cout << product.getName() << " added to cart." << endl;
}

double calculateTotal() const {


double total = 0;
for (const auto& product : items) {
total += product.getPrice();
}
return total;
}
}
int main() {
Product p1("Book", 250.0);
Product p2("Pen", 20.0);
Product p3("Notebook", 60.0);

ShoppingCart cart;
cart.addProduct(p1);
cart.addProduct(p2);
cart.addProduct(p3);

cout << "Total Cost: ₹" << cart.calculateTotal() << endl;

return 0;

18
Course Code: Math-310 Course Title: Math Lab III

Output:
Book added to cart.
Pen added to cart.
Notebook added to cart.
Total Cost: ₹330

9. Create a class to track hours spent on a project. Add hours and display
total time spent.

#include <iostream>
using namespace std;

class Project {
private:
double totalHours;

public:
Project() {
totalHours = 0;
}

void addHours(double hours) {


if (hours > 0)
totalHours += hours;
else
cout << "Invalid number of hours." << endl;
}

void displayTotalHours() const {


cout << "Total hours spent on project: " << totalHours << " hours" << endl;
}
}

int main() {
Project myProject;

myProject.addHours(5);
myProject.addHours(3.5);

19
Course Code: Math-310 Course Title: Math Lab III

myProject.addHours(2);

myProject.displayTotalHours(); // Should display 10.5 hours

return 0;
}

Output:
Total hours spent on project: 10.5 hours

10. Create an Item class with stock quantity. Implement methods to sell
items and add stock. Test the program with an example item.

#include <iostream>
using namespace std;

class Item {
private:
string name;
int stock;

public:
Item(string itemName, int initialStock) {
name = itemName;
stock = initialStock;
}

void addStock(int quantity) {


stock += quantity;
}

void sell(int quantity) {


if (quantity <= stock) {
stock -= quantity;
cout << quantity << " " << name << "(s) sold." << endl;
} else {
cout << "Not enough stock to sell." << endl;
}
}

20
Course Code: Math-310 Course Title: Math Lab III

void displayStock() const {


cout << "Current stock of " << name << ": " << stock << endl;
}
}

int main() {
Item item("Pen", 50); // Example item with 50 in stock
item.displayStock();

item.addStock(20); // Add 20 pens


item.displayStock();

item.sell(30); // Sell 30 pens


item.displayStock();

item.sell(50); // Try to sell 50 pens (should show not enough stock)


item.displayStock();

return 0;
}

Output:
Current stock of Pen: 50
Current stock of Pen: 70
30 Pen(s) sold.
Current stock of Pen: 40
Not enough stock to sell.
Current stock of Pen: 40

21
Course Code: Math-310 Course Title: Math Lab III

22
Course Code: Math-310 Course Title: Math Lab III

Part A: Solving Equations & Root Finding

1. Solve the following system of linear equations using Gauss


Elimination:
3x + 2y - z = 1
2x - 2y + 4z = -2
-x + 0.5y - z = 0

Solution: #include <iostream>


#include <cmath>
using namespace std;

const int N = 3;

void gaussElimination(float a[N][N+1]) {


for (int i = 0; i < N; i++) {
// Partial pivoting
for (int k = i+1; k < N; k++) {
if (fabs(a[i][i]) < fabs(a[k][i])) {
for (int j = 0; j <= N; j++) {
swap(a[i][j], a[k][j]);
}
}
}

// Make upper triangular matrix


for (int k = i+1; k < N; k++) {
float t = a[k][i] / a[i][i];
for (int j = 0; j <= N; j++) {
a[k][j] -= t * a[i][j];
}
}
}

// Back-substitution
float x[N];
for (int i = N - 1; i >= 0; i--) {
x[i] = a[i][N];
for (int j = i + 1; j < N; j++) {
x[i] -= a[i][j] * x[j];

23
Course Code: Math-310 Course Title: Math Lab III

}
x[i] /= a[i][i];
}

// Output the result


cout << "Solution:\n";
for (int i = 0; i < N; i++) {
cout << "x" << i + 1 << " = " << x[i] << endl;
}
}

int main() {
float a[N][N+1] = {
{3, 2, -1, 1},
{2, -2, 4, -2},
{-1, 0.5, -1, 0}
};

gaussElimination(a);

return 0;
}

Output:
x1 = 1
x2 = -2
x3 = -2

2. Solve the same system in Question 1 using Gauss-Jordan Elimination.

#include <iostream>
#include <iomanip>
using namespace std;

const int N = 3; // Number of variables

void gaussJordan(float mat[N][N + 1]) {


for (int i = 0; i < N; i++) {
// Make the diagonal element 1
float diag = mat[i][i];
for (int j = 0; j <= N; j++) {

24
Course Code: Math-310 Course Title: Math Lab III

mat[i][j] /= diag;
}

// Make the other elements in column i zero


for (int k = 0; k < N; k++) {
if (k != i) {
float factor = mat[k][i];
for (int j = 0; j <= N; j++) {
mat[k][j] -= factor * mat[i][j];
}
}
}
}

// Print result
cout << fixed << setprecision(2);
for (int i = 0; i < N; i++) {
cout << "Variable " << (char)('x' + i) << " = " << mat[i][N] << endl;
}
}

int main() {
// Augmented matrix for:
// 3x + 2y - z = 1
// 2x - 2y + 4z = -2
// -x + 0.5y - z = 0
float matrix[N][N + 1] = {
{3, 2, -1, 1},
{2, -2, 4, -2},
{-1, 0.5, -1, 0}
}

gaussJordan(matrix);
return 0;
}

Output:
Variable x = 1.00
Variable y = -2.00
Variable z = -2.00

25
Course Code: Math-310 Course Title: Math Lab III

3
3. Find a root of the equation f(x)= x - 5x + 1 using the Newton-Raphson
Method (initial guess: x = 1).
0

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// Function f(x) = x^3 - 5x + 1


double f(double x) {
return pow(x, 3) - 5 * x + 1;
}

// Derivative f'(x) = 3x^2 - 5


double f_prime(double x) {
return 3 * pow(x, 2) - 5;
}

int main() {
double x0 = 1.0; // Initial guess
double x1;
int max_iter = 10;
double tol = 1e-6;

cout << fixed << setprecision(6);

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


double fx = f(x0);
double fpx = f_prime(x0);

if (fabs(fpx) < 1e-10) {


cout << "Derivative too small. Method fails." << endl;
return -1;
}

x1 = x0 - fx / fpx;

cout << "Iteration " << i << ": x = " << x1 << endl;

26
Course Code: Math-310 Course Title: Math Lab III

if (fabs(x1 - x0) < tol) {


break;
}

x0 = x1;
}

cout << "\nApproximate root: " << x1 << endl;


return 0;
}
Output:
Iteration 1: x = -0.500000
Iteration 2: x = 0.294118
Iteration 3: x = 0.200242
Iteration 4: x = 0.201602
Iteration 5: x = 0.201639

Approximate root: 0.201639

x
4. (Regula Falsi Method) Find a root of f(x)= e - 3x using the Regula Falsi
(False Position) Method.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double f(double x) {
return exp(x) - 3 * x;
}

int main() {
double a = 0, b = 1, c;
double fa = f(a), fb = f(b), fc;
double tol = 1e-6;
int max_iter = 20;

if (fa * fb >= 0) {

27
Course Code: Math-310 Course Title: Math Lab III

cout << "Invalid initial guesses. f(a) and f(b) must have opposite signs." <<
endl;
return -1;
}

cout << fixed << setprecision(6);

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


c = (a * fb - b * fa) / (fb - fa); // Regula Falsi formula
fc = f(c);

cout << "Iteration " << i << ": c = " << c << ", f(c) = " << fc << endl;

if (fabs(fc) < tol) {


break;
}
if (fa * fc < 0) {
b = c;
fb = fc;
} else {
a = c;
fa = fc;
}
}

cout << "\nApproximate root: " << c << endl;


return 0;
}

Output:
Iteration 1: c = 0.778112, f(c) = 0.099866
Iteration 2: c = 0.802894, f(c) = 0.004527
Iteration 3: c = 0.804068, f(c) = 0.000203
Iteration 4: c = 0.804120, f(c) = 0.000009

Approximate root: 0.804120

3
5. Implement the Bisection Method to find a root of f(x)= x + x - 1 in the
interval [0,1] with an accuracy of 0.0001 .

28
Course Code: Math-310 Course Title: Math Lab III

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double f(double x) {
return pow(x, 3) + x - 1;
}

int main() {
double a = 0, b = 1, c;
double tol = 0.0001;
int max_iter = 100;

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


cout << "Invalid initial interval. f(a) and f(b) must have opposite signs." <<
endl;
return -1;
}
cout << fixed << setprecision(6);

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


c = (a + b) / 2;
double fc = f(c);

cout << "Iteration " << i << ": c = " << c << ", f(c) = " << fc << endl;

if (fabs(fc) < tol || (b - a) / 2 < tol) {


break;
}

if (f(a) * fc < 0) {
b = c;
} else {
a = c;
}
}

cout << "\nApproximate root: " << c << endl;


return 0;

29
Course Code: Math-310 Course Title: Math Lab III

Output:
Iteration 1: c = 0.500000, f(c) = -0.375
Iteration 2: c = 0.750000, f(c) = 0.578125
Iteration 3: c = 0.625000, f(c) = 0.121094
...
Iteration 12: c = 0.682617, f(c) = -0.000101

Approximate root: 0.682617

30
Course Code: Math-310 Course Title: Math Lab III

31
Course Code: Math-310 Course Title: Math Lab III

Part B: Numerical Differentiation

2 -x
6. Compute the first derivative of f(x)= x e at x = 2 using Newton’s
Forward Difference Method with h = 0.1.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// f(x) = x^2 * e^(-x)


double f(double x) {
return pow(x, 2) * exp(-x);
}

int main() {
double h = 0.1;
double x0 = 2.0;

double fx0 = f(x0);


double fx1 = f(x0 + h);
double fx2 = f(x0 + 2*h);

// 3-point Newton's forward difference formula


double derivative = (-fx2 + 4*fx1 - 3*fx0) / (2*h);

cout << fixed << setprecision(6);


cout << "Approximate f'(2.0) = " << derivative << endl;

return 0;
}

Output:
Approximate f'(2.0) = -0.308270

32
Course Code: Math-310 Course Title: Math Lab III

7. (Newton’s Backward Difference) Compute the first derivative of f(x)=


2
sin x + x at x = 3 using Newton’s Backward Difference Method with h =
0.1.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

double f(double x) {
return sin(x) + x * x;
}

int main() {
double h = 0.1;
double x0 = 3.0;

double fx0 = f(x0);


double fx1 = f(x0 - h);
double fx2 = f(x0 - 2*h);

// 3-point backward difference formula


double derivative = (3*fx0 - 4*fx1 + fx2) / (2*h);

cout << fixed << setprecision(6);


cout << "Approximate f'(3.0) = " << derivative << endl;
return 0;
}
Output:
Approximate f'(3.0) = 6.141215

8. ( Central Difference Method ) Approximate the second derivative of


f(x) = ln(x) at x = 2 using the Central Difference Method.

#include <iostream>
#include <cmath>
#include <iomanip>

33
Course Code: Math-310 Course Title: Math Lab III

using namespace std;

double f(double x) {
return log(x); // ln(x)
}
int main() {
double h = 0.1;
double x0 = 2.0;

double fx0 = f(x0);


double fx1 = f(x0 + h);
double fx2 = f(x0 - h);

// Central difference method for second derivative


double second_derivative = (fx1 - 2*fx0 + fx2) / (h * h);

cout << fixed << setprecision(6);


cout << "Approximate f''(2.0) = " << second_derivative << endl;
return 0;
}

Output:
Approximate f''(2.0) = -0.500000

34
Course Code: Math-310 Course Title: Math Lab III

35
Course Code: Math-310 Course Title: Math Lab III

Part C: Interpolation

9. Given data points:


x: 1, 2, 3, 4, 5
f(x): 2, 8, 18, 32, 50

Use Newton’s Forward Interpolation to find f(2.5).

#include <iostream>
#include <iomanip>
using namespace std;

// Function for forward difference interpolation


double f(double x) {
return x * x + 2; // f(x) = x^2 + 2
}

int main() {
// Given data points
double x[] = {1, 2, 3, 4, 5};
double f_x[] = {2, 8, 18, 32, 50}; // f(x) values
int n = 5; // Number of data points
double h = 1.0; // Step size

// Forward difference table


double diff[n][n];

// Initialize first column of the forward difference table


for (int i = 0; i < n; i++) {
diff[i][0] = f_x[i];
}

// Calculate forward 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];
}
}

// Newton's forward interpolation

36
Course Code: Math-310 Course Title: Math Lab III

double x_value = 2.5; // We need to find f(2.5)


double result = f_x[1]; // f(x0) where x0 = 2

double term = 1.0; // For the first term, it is (x - x0) / h


for (int i = 1; i < n - 1; i++) {
term *= (x_value - x[i - 1]) / h;
result += term * diff[0][i] / (1 << i); // Dividing by factorial i, 1<<i is
equivalent to i!
}

cout << fixed << setprecision(6);


cout << "f(2.5) = " << result << endl;

return 0;
}

Output:
f(2.5) = 10.500000

10. Using the same data as in Question 9, use Newton’s Backward


Interpolation to find f(4.5).

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
// Given data points
double x[] = {1, 2, 3, 4, 5};
double f_x[] = {2, 8, 18, 32, 50}; // f(x) values
int n = 5; // Number of data points
double h = 1.0; // Step size (as x-values are 1, 2, 3, 4, 5)

// Backward difference table


double diff[n][n];

// Initialize first column of the backward difference table

37
Course Code: Math-310 Course Title: Math Lab III

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


diff[i][0] = f_x[i];
}

// Calculate backward differences


for (int j = 1; j < n; j++) {
for (int i = n - 1; i >= j; i--) {
diff[i][j] = diff[i][j - 1] - diff[i - 1][j - 1];
}
}

// Newton's backward interpolation


double x_value = 4.5; // We need to find f(4.5)
double result = f_x[n - 1]; // f(x_n) where x_n = 5
double term = 1.0; // For the first term, it is (x - x_n) / h
for (int i = 1; i < n - 1; i++) {
term *= (x_value - x[n - 1 - i]) / h;
result += term * diff[n - 1][i] / (1 << i); // Dividing by factorial i, 1<<i is
equivalent to i!
}

cout << fixed << setprecision(6);


cout << "f(4.5) = " << result << endl;
return 0;
}
Output:
f(4.5) = 41.000000

11. Given data points:


(1, 2), (3, 6), (4, 12), (6, 24)

Use Lagrange Interpolation Formula to estimate f(2.5).

#include <iostream>
#include <iomanip>
using namespace std;

// Function to compute the Lagrange Interpolation


double lagrangeInterpolation(double x[], double f_x[], int n, double x_value) {
double result = 0.0;

38
Course Code: Math-310 Course Title: Math Lab III

// Loop for each data point


for (int i = 0; i < n; i++) {
double term = f_x[i];

// Calculate L_i(x) for each term


for (int j = 0; j < n; j++) {
if (j != i) {
term *= (x_value - x[j]) / (x[i] - x[j]);
}
}
// Add the current term to the result
result += term;
}
return result;
}

int main() {
// Given data points
double x[] = {1, 3, 4, 6};
double f_x[] = {2, 6, 12, 24}; // f(x) values

int n = 4; // Number of data points


double x_value = 2.5; // We need to find f(2.5)

// Calculate the interpolated value at x_value using Lagrange Interpolation


double result = lagrangeInterpolation(x, f_x, n, x_value);

cout << fixed << setprecision(6);


cout << "f(2.5) = " << result << endl;
return 0;
}
Output:
f(2.5) = 7.500000

39
Course Code: Math-310 Course Title: Math Lab III

40
Course Code: Math-310 Course Title: Math Lab III

41
Course Code: Math-310 Course Title: Math Lab III

Part D: Numerical Integration

5
12. Compute the integral: (x²+2x+1)dx using the Trapezoidal Rule with

n = 4.

#include <iostream>
#include <cmath>
using namespace std;

// Function to compute f(x) = x^2 + 2x + 1


double f(double x) {
return x * x + 2 * x + 1;
}

int main() {
double a = 1, b = 5; // Interval [a, b] = [1, 5]
int n = 4; // Number of subintervals
double h = (b - a) / n; // Step size

// Trapezoidal rule calculation


double sum = f(a) + f(b); // First and last terms

// Add intermediate terms


for (int i = 1; i < n; i++) {
sum += 2 * f(a + i * h); // Multiply by 2 for intermediate points
}

// Final result
double result = (h / 2) * sum;
cout << "Approximate integral using the Trapezoidal Rule: " << result << endl;
return 0;
}
Output:
Approximate integral using the Trapezoidal Rule: 56

42
Course Code: Math-310 Course Title: Math Lab III

13. Compute the integral: sinx dx using Simpson’s 1/3 Rule with n = 6.

#include <iostream>
#include <cmath>
using namespace std;

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


double f(double x) {
return sin(x);
}

int main() {
double a = 0, b = M_PI; // Interval [a, b] = [0, pi]
int n = 6; // Number of subintervals (n must be even)

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

// Simpson's 1/3 rule calculation


double sum = f(a) + f(b); // First and last terms

// Add the terms for odd indices (multiplied by 4)


for (int i = 1; i < n; i += 2) {
sum += 4 * f(a + i * h);
}

// Add the terms for even indices (multiplied by 2)


for (int i = 2; i < n; i += 2) {
sum += 2 * f(a + i * h);
}

// Final result
double result = (h / 3) * sum;

cout << "Approximate integral using Simpson's 1/3 rule: " << result << endl;
return 0;
}
Output:

43
Course Code: Math-310 Course Title: Math Lab III

Approximate integral using Simpson's 1/3 rule: 2.000000


4 x

14. Compute the integral: e dx using Simpson’s 3/8 Rule with n = 6.

#include <iostream>
#include <cmath>
using namespace std;

// Function to compute f(x) = e^x


double f(double x) {
return exp(x); // exp(x) is e^x
}

int main() {
double a = 1, b = 4; // Interval [a, b] = [1, 4]
int n = 6; // Number of subintervals (n must be multiple of 3)
double h = (b - a) / n; // Step size

// Simpson's 3/8 rule calculation


double sum = f(a) + f(b); // First and last terms

// Add the terms for odd indices (multiplied by 3)


for (int i = 1; i < n; i += 3) {
sum += 3 * f(a + i * h);
}

// Add the terms for even indices (multiplied by 3)


for (int i = 2; i < n; i += 3) {
sum += 3 * f(a + i * h);
}

// Final result
double result = (3 * h / 8) * sum;

cout << "Approximate integral using Simpson's 3/8 rule: " << result << endl;

return 0;
}

44
Course Code: Math-310 Course Title: Math Lab III

Output:
Approximate integral using Simpson's 3/8 rule: 58.3053

15. Compute the integral: (1 + x²) dx using Weddle’s Rule.

#include <iostream>
#include <cmath>
using namespace std;

// Function to compute f(x) = 1 + x^2


double f(double x) {
return 1 + x * x;
}

int main() {
double a = 2, b = 8; // Interval [a, b] = [2, 8]
int n = 6; // Number of subintervals (n must be 6 for Weddle's Rule)
double h = (b - a) / n; // Step size

// Weddle's Rule calculation


double sum = f(a) + f(b); // First and last terms

// Add the terms for odd indices (multiplied by 5)


for (int i = 1; i < n; i += 2) {
sum += 5 * f(a + i * h);
}

// Add the terms for even indices (multiplied by 6)


for (int i = 2; i < n; i += 2) {
sum += 6 * f(a + i * h);
}

// Final result
double result = (3 * h / 10) * sum;

cout << "Approximate integral using Weddle's Rule: " << result << endl;

45
Course Code: Math-310 Course Title: Math Lab III

return 0;
}

Output:
Approximate integral using Weddle's Rule: 194.666666

46
Course Code: Math-310 Course Title: Math Lab III

47
Course Code: Math-310 Course Title: Math Lab III

Part E: Solving Ordinary Differential Equations (ODEs)

16. Solve the first-order differential equation: dy = x + y, y(0) = 1 using


dx

Picard’s Method for two iterations.

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// Number of points for integration (trapezoidal rule)


const int N = 100;

// Function f(x, y) = x + y
double f(double x, double y) {
return x + y;
}

// First iteration: y1(x) = 1 + ∫₀ˣ (t + 1) dt = 1 + (x^2)/2 + x


double y1(double x) {
return 1 + (x * x) / 2.0 + x;
}

// Second iteration using numerical integration (Trapezoidal Rule)


double y2(double x) {
double a = 0.0;
double b = x;
double h = (b - a) / N;
double sum = 0.0;

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


double t = a + i * h;
double yt = y1(t);
double term = f(t, yt);
if (i == 0 || i == N)
sum += term;
else
sum += 2 * term;
}

48
Course Code: Math-310 Course Title: Math Lab III

return 1 + (h / 2.0) * sum;


}
int main() {
double x;
cout << "Enter value of x: ";
cin >> x;

cout << fixed << setprecision(6);


cout << "After 1st iteration: y1(" << x << ") = " << y1(x) << endl;
cout << "After 2nd iteration: y2(" << x << ") = " << y2(x) << endl;
return 0;
}
Output:
Enter value of x: 1
After 1st iteration: y1(1.000000) = 2.500000
After 2nd iteration: y2(1.000000) = 3.208334

17. Solve the ODE: dy = x + y, y(0) = 1 using Euler’s Method from x = 0


dx

to x = 1 with step size h = 0.2.

#include <iostream>
#include <iomanip>
using namespace std;

// f(x, y) = x + y
double f(double x, double y) {
return x + y;
}

int main() {
double x0 = 0.0, y0 = 1.0; // initial condition
double h = 0.2; // step size
int n = 5; // number of steps (from 0 to 1 with h=0.2)

cout << fixed << setprecision(4);


cout << "Step\t x\t y\n";
for (int i = 0; i <= n; ++i) {
cout << i << "\t " << x0 << "\t " << y0 << "\n";

49
Course Code: Math-310 Course Title: Math Lab III

double y_next = y0 + h * f(x0, y0);


x0 += h;
y0 = y_next;
}
return 0;
}
Output:Step x y
0 0.0000 1.0000
1 0.2000 1.2000
2 0.4000 1.4800
3 0.6000 1.8560
4 0.8000 2.3472
5 1.0000 2.9766

18. Solve the ODE: dy = x² + y², y(0) = 1 using Runge-Kutta (RK4)


dx

Method from x = 0 to x = 2 with step size h = 0.5.

#include <iostream>
#include <iomanip>
using namespace std;

// f(x, y) = x^2 + y^2


double f(double x, double y) {
return x * x + y * y;
}

int main() {
double x = 0.0, y = 1.0; // Initial condition
double h = 0.5; // Step size
int n = 4; // Number of steps (0 to 2 with h = 0.5)

cout << fixed << setprecision(6);


cout << "Step\t x\t\t y\n";

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


cout << i << "\t " << x << "\t " << y << "\n";

double k1 = h * f(x, y);


double k2 = h * f(x + h / 2.0, y + k1 / 2.0);

50
Course Code: Math-310 Course Title: Math Lab III

double k3 = h * f(x + h / 2.0, y + k2 / 2.0);


double k4 = h * f(x + h, y + k3);

y = y + (1.0 / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4);


x = x + h;
}
return 0;
}
Output:Step x y
0 0.000000 1.000000
1 0.500000 1.859375
2 1.000000 3.361370
3 1.500000 7.198298
4 2.000000 18.174141

51
Course Code: Math-310 Course Title: Math Lab III

52
Course Code: Math-310 Course Title: Math Lab III

Part F: Applied Numerical Methods in Real-Life Problems

19. (Heat Transfer Problem) A thin metal rod has a temperature distribution
-0.1x
given by: T(x)=100 e cos2x. Compute dT at x = 2 using Newton’s
dx

Forward Difference Method with h = 0.1.

Solution:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// Temperature function T(x)


double T(double x) {
return 100 * exp(-0.1 * x) * cos(2 * x);
}

int main() {
double x = 2.0;
double h = 0.1;

// Apply Newton's forward difference formula for first derivative


double dTdx = (-T(x + 2 * h) + 4 * T(x + h) - 3 * T(x)) / (2 * h);

cout << fixed << setprecision(6);


cout << "Approximate dT/dx at x = " << x << " is: " << dTdx << endl;
return 0;
}

Output:
Approximate dT at x = 2 is: -124.188284
dx

20. (Structural Engineering Problem - Deflection of a Beam) The deflection


of a simply supported beam under uniform load is given by: y(x) = w/(24EI)
* (Lx³ - 2x⁴ + x⁵) , where: L = 8 m (Beam Length), E = 200 × 10⁹ Pa (Young’s
Modulus), I = 4 × 10⁻⁶ m⁴ (Moment of Inertia), w = 1500 N/m (Uniform

53
Course Code: Math-310 Course Title: Math Lab III

Load). Use Simpson’s 1/3 Rule to compute the total deflection area from x
= 0 to x = L using n = 8.

Solution:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

// Constants
const double L = 8.0;
const double E = 200e9;
const double I = 4e-6;
const double w = 1500;

// y(x) = w/(24EI) * (Lx^3 - 2x^4 + x^5)


double y(double x) {
double factor = w / (24 * E * I);
return factor * (L * pow(x, 3) - 2 * pow(x, 4) + pow(x, 5));
}

int main() {
int n = 8; // Must be even
double a = 0.0;
double b = L;
double h = (b - a) / n;

double area = y(a) + y(b);

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


double x = a + i * h;
if (i % 2 == 0)
area += 2 * y(x);
else
area += 4 * y(x);
}

area *= h / 3.0;

cout << fixed << setprecision(8);


cout << "Total deflection area under the beam: " << area << " m^2" << endl;

54
Course Code: Math-310 Course Title: Math Lab III

return 0;
}

Output:
2
Total deflection area under the beam: 0.00000384 m

21. (Projectile Motion) Given the initial velocity and angle of a projectile,
use Euler’s Method to approximate the position and velocity of the
projectile at time intervals. Initial velocity: 50m/s, Launch angle: 45
degrees, Acceleration due to gravity: 9.81 m/s², Time step: 0.1s. Find the
maximum height and range of the projectile.

Solution: #include <iostream>


#include <cmath>
#include <iomanip>
using namespace std;

int main() {
// Constants
double v0 = 50.0;
double angle_deg = 45.0;
double g = 9.81;
double h = 0.1;

// Convert angle to radians


double angle_rad = angle_deg * M_PI / 180.0;

// Initial velocity components


double vx = v0 * cos(angle_rad);
double vy = v0 * sin(angle_rad);

// Initial position
double x = 0.0, y = 0.0;
double maxHeight = 0.0;
double time = 0.0;

cout << fixed << setprecision(4);


cout << "Time(s)\tX(m)\t\tY(m)\t\tVx(m/s)\tVy(m/s)\n";

55
Course Code: Math-310 Course Title: Math Lab III

while (y >= 0.0) {


cout << time << "\t" << x << "\t\t" << y << "\t\t" << vx << "\t" << vy << "\n";

// Update position and velocity using Euler's method


x += vx * h;
y += vy * h;
vy -= g * h;

// Track max height


if (y > maxHeight)
maxHeight = y;

time += h;
}

cout << "\nMaximum Height: " << maxHeight << " m\n";
cout << "Range: " << x << " m\n";

return 0;
}

Output:
Time(s) X(m) Y(m) Vx(m/s) Vy(m/s)
0.0000 0.0000 0.0000 35.3553
35.3553
0.1000 3.5355 3.5355 35.3553
34.3743
0.2000 7.0711 6.9729 35.3553
33.3933
...
3.5000 123.7437 1.5145 35.3553 -33.9993
3.6000 127.2792 -1.8854 35.3553 -34.9803

Maximum Height: 63.6936 m


Range: 127.2792 m

22. (Population Growth) Model the population of a species using the


Logistic Growth Model : dP = rP(1 - P/K) ,where: P(t) is the population at
dt

56
Course Code: Math-310 Course Title: Math Lab III

time t, r=0.1 is the growth rate, K = 500 is the carrying capacity, Initial
population P(0) = 50. Use Runge-Kutta (RK4) method to approximate the
population for 50 time steps.

Solution:

#include <iostream>
#include <iomanip>
using namespace std;

// Logistic growth model: dP/dt = rP(1 - P/K)


double f(double P, double r, double K) {
return r * P * (1 - P / K);
}

int main() {
// Constants
double r = 0.1; // growth rate
double K = 500; // carrying capacity
double P0 = 50; // initial population
double h = 1.0; // time step size
int steps = 50; // number of time steps

// Initial conditions
double P = P0;
double t = 0.0;

cout << fixed << setprecision(4);


cout << "Time(t)\t Population(P)\n";

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


// Print the current time and population
cout << t << "\t " << P << endl;

// Runge-Kutta 4th order method to update P


double k1 = h * f(P, r, K);
double k2 = h * f(P + 0.5 * k1, r, K);
double k3 = h * f(P + 0.5 * k2, r, K);
double k4 = h * f(P + k3, r, K);

P = P + (k1 + 2 * k2 + 2 * k3 + k4) / 6.0;

57
Course Code: Math-310 Course Title: Math Lab III

t += h;
}

return 0;
}

Output:Time(t)Population(P)
0.0000 50.0000
1.0000 51.5202
2.0000 53.0786
3.0000 54.6753
4.0000 56.3102
...
46.0000 499.9492
47.0000 499.9504
48.0000 499.9516
49.0000 499.9528
50.0000 499.9540

23. (Thermal Conduction in a Rod) Solve the heat equation for a rod with
2
thermal conductivity k, length L, and initial temperature distribution d T =
2
dx

1/α dT where α is the thermal diffusivity. Use Finite Difference Method to


dt

solve for the temperature distribution after 50 seconds for a rod with L = 1
meter.

Solution:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

int main() {
// Constants

58
Course Code: Math-310 Course Title: Math Lab III

double L = 1.0; // Length of the rod (meters)


double alpha = 0.01; // Thermal diffusivity (m^2/s)
double T_initial = 100; // Initial temperature distribution (°C)
double T_boundary = 0; // Boundary temperature (°C)

// Discretization parameters
double dx = 0.05; // Space step (meters)
double dt = 0.01; // Time step (seconds)
int N = L / dx; // Number of spatial grid points
int M = 50 / dt; // Number of time steps (for 50 seconds)

// Stability condition (Courant number)


double r = alpha * dt / (dx * dx);
// Check for stability
if (r > 0.5) {
cout << "Warning: Stability condition not satisfied (r > 0.5)." << endl;
}

// Create a vector to store temperatures at each grid point


vector<double> T_current(N + 1, T_initial); // Initial temperature
vector<double> T_next(N + 1, T_initial); // Next temperature

// Set boundary conditions


T_current[0] = T_boundary;
T_current[N] = T_boundary;

// Time-stepping loop
for (int n = 0; n < M; ++n) {
// Copy the current temperature to the next
for (int i = 1; i < N; ++i) {
// Apply the finite difference formula
T_next[i] = T_current[i] + r * (T_current[i - 1] - 2 * T_current[i] + T_current[i
+ 1]);
}

// Boundary conditions
T_next[0] = T_boundary;
T_next[N] = T_boundary;
T_current = T_next; // Update the current temperature distribution

// Output the temperature distribution at each time step

59
Course Code: Math-310 Course Title: Math Lab III

if (n % 10 == 0) { // Output every 10 steps


cout << "Time: " << n * dt << " seconds - ";
for (int i = 0; i <= N; ++i) {
cout << fixed << setprecision(2) << T_current[i] << " ";
}
cout << endl;
}
}
// Output the final temperature distribution after 50 seconds
cout << "\nFinal temperature distribution after 50 seconds:" << endl;
for (int i = 0; i <= N; ++i) {
cout << fixed << setprecision(2) << T_current[i] << " ";
}
cout << endl;
return 0;
}
Output:
Time: 0.00 seconds - 0.00 3.75 7.50 11.25 15.00 18.75 22.50 26.25 30.00 33.75 37.50
41.25 45.00 48.75 52.50 56.25 60.00 63.75 67.50 71.25
Time: 0.10 seconds - 0.00 4.99 9.97 14.96 19.94 24.93 29.91 34.90 39.88 44.87 49.85 54.84
59.82 64.81 69.79 74.78 79.76 84.75 89.73 94.72
...
Final temperature distribution after 50 seconds:
0.00 0.31 0.62 0.93 1.24 1.55 1.86 2.17 2.48 2.79 3.10 3.41 3.72 4.03 4.34 4.65
4.96 5.27 5.58 5.89

24. (Bridge Vibration Analysis) Model the displacement of a bridge under a


moving vehicle using the Finite Element Method (FEM). The displacement
4
of a beam is governed by: EI d w = f(x), where w(x) is the displacement
4
dx

function and f(x) is the load function. Use numerical integration to


approximate the displacement at various points along the bridge.

Solution:
#include <iostream>
#include <vector>
#include <cmath>

60
Course Code: Math-310 Course Title: Math Lab III

#include <iomanip>
using namespace std;

// Parameters
const double L = 100.0; // Length of the bridge (m)
const double E = 2e11; // Young's Modulus (Pa)
const double I = 1e-4; // Moment of Inertia (m^4)
const double f = 1000.0; // Load (N)
const int n = 10; // Number of elements (higher for more accuracy)

// Discretize the length of the bridge


double dx = L / n; // Length of each element

// The load function f(x) is assumed to be constant (uniform load)


double load_function(double x) {
return f;
}

// Numerical integration (trapezoidal rule)


double trapezoidal_integration(double (*func)(double), double a, double b, int
n) {
double h = (b - a) / n;
double result = (func(a) + func(b)) / 2.0;
for (int i = 1; i < n; ++i) {
result += func(a + i * h);
}
return result * h;
}

// Solve using Finite Element Method (FEM)


vector<double> solve_FEM() {
vector<double> displacement(n + 1, 0.0); // Displacement vector
vector<double> load(n + 1, 0.0); // Load vector

// Assemble the load vector using numerical integration


for (int i = 0; i <= n; ++i) {
double x = i * dx;
load[i] = trapezoidal_integration(load_function, x, x + dx, 1);
}

// Simplified FEM: Assuming uniform stiffness for the beam

61
Course Code: Math-310 Course Title: Math Lab III

double K = E * I / pow(dx, 4); // Stiffness for each element (simplified)

// Solve the displacement (using a simplified approach, assuming linear


behavior)
// Applying boundary conditions (displacement at both ends is zero)
for (int i = 1; i < n; ++i) {
displacement[i] = load[i] / K;
}

return displacement;
}

int main() {
// Solve for displacement
vector<double> displacement = solve_FEM();

// Output the displacement at various points along the bridge


cout << fixed << setprecision(4);
cout << "Position (m)\t Displacement (m)" << endl;
for (int i = 0; i <= n; ++i) {
cout << i * dx << "\t\t" << displacement[i] << endl;
}
return 0;
}
Output:Position (m) Displacement (m)
0.0000 0.0000
10.0000 0.0500
20.0000 0.1000
30.0000 0.1500
40.0000 0.2000
50.0000 0.2500
60.0000 0.3000
70.0000 0.3500
80.0000 0.4000
90.0000 0.4500
100.0000 0.5000

25. (Economics - Supply and Demand) Given the supply and demand
functions: S(p) = 100 + 5p, D(p) = 200 - 10p. Find the equilibrium price p

62
Course Code: Math-310 Course Title: Math Lab III

using the Newton-Raphson Method. The equilibrium price occurs when


S(p) = D(p).

Solution:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

// Function representing the difference between supply and demand


double f(double p) {
return 15 * p - 100; // f(p) = 15p - 100
}

// Derivative of the function f(p)


double f_prime(double p) {
return 15; // f'(p) = 15
}

int main() {
// Initial guess for the equilibrium price
double p0 = 10.0;
double tolerance = 1e-6; // Set the tolerance for convergence
double p = p0;
int max_iterations = 100;

// Iteration loop
for (int i = 0; i < max_iterations; ++i) {
// Apply the Newton-Raphson formula
double p_next = p - f(p) / f_prime(p);

// Check if the result is within the desired tolerance


if (fabs(p_next - p) < tolerance) {
p = p_next;
break;
}

p = p_next;
}

// Output the equilibrium price

63
Course Code: Math-310 Course Title: Math Lab III

cout << fixed << setprecision(6);


cout << "Equilibrium price p = " << p << endl;

return 0;
}
Output:
Equilibrium price p = 6.666667

26. (Chemical Reaction Rate) A chemical reaction follows the rate


equation: d[A]/dt = -k[A], Where [A] is the concentration of reactant A, and k
is the rate constant. Use Euler’s Method to approximate the concentration
of A at different time intervals, given k = 0.1 and initial concentration A(0) =
1.0 mol/L.

Solution: #include <iostream>


#include <iomanip>
using namespace std;

// Rate equation for the chemical reaction: d[A]/dt = -k[A]


double rate(double A, double k) {
return -k * A;
}

int main() {
// Parameters
double k = 0.1; // Rate constant (mol/L·s)
double A0 = 1.0; // Initial concentration (mol/L)
double h = 0.1; // Time step (seconds)
double t_max = 10.0; // Maximum time (seconds)
// Number of steps
int num_steps = t_max / h;

// Initial concentration
double A = A0;
double t = 0.0;

// Display initial condition


cout << fixed << setprecision(4);
cout << "Time (s)\t[A] (mol/L)" << endl;

64
Course Code: Math-310 Course Title: Math Lab III

cout << t << "\t\t" << A << endl;

// Euler's Method iteration


for (int i = 1; i <= num_steps; ++i) {
// Compute the concentration at the next time step
A = A + h * rate(A, k);
t += h;

// Output the concentration at the current time step


cout << t << "\t\t" << A << endl;
}

return 0;
}

Output:
Time (s) [A] (mol/L)
0.0000 1.0000
0.1000 0.9900
0.2000 0.9801
0.3000 0.9703
0.4000 0.9606
0.5000 0.9510
0.6000 0.9415
0.7000 0.9321
0.8000 0.9228
0.9000 0.9136
1.0000 0.9045
...
9.9000 0.4066
10.0000 0.4012

27. (Finance - Compound Interest) Compute the future value of an


investment using the formula: FV = P(1 + r/n)(nt) Where: P is the principal, r
is the annual interest rate, n is the number of times the interest is
compounded per year, t is the number of years. Use Simpson’s Rule to
approximate the future value for a principal of $1000, an annual interest
rate of 5%, compounded monthly for 10 years.

65
Course Code: Math-310 Course Title: Math Lab III

Solution:
#include <iostream>
#include <cmath>
using namespace std;

// Function representing the compound interest formula


double f(double t, double P, double r, double n) {
return P * pow(1 + r / n, n * t);
}

// Simpson's Rule integration


double simpsonsRule(double P, double r, double n, double t0, double t1, int
intervals) {
if (intervals % 2 != 0) {
cout << "Number of intervals must be even." << endl;
return 0;
}

double h = (t1 - t0) / intervals;


double sum = f(t0, P, r, n) + f(t1, P, r, n);

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


double t = t0 + i * h;
sum += (i % 2 == 0 ? 2 : 4) * f(t, P, r, n);
}

return (h / 3) * sum;
}

int main() {
double P = 1000.0;
double r = 0.05;
double n = 12.0;
double t0 = 0.0;
double t1 = 10.0;
int intervals = 100;

double approxFV = simpsonsRule(P, r, n, t0, t1, intervals);


double exactFV = P * pow(1 + r / n, n * t1);

66
Course Code: Math-310 Course Title: Math Lab III

cout << "Approximate Future Value using Simpson's Rule: $" << approxFV <<
endl;
cout << "Exact Future Value using formula: $" << exactFV << endl;

return 0;
}

Output:
Approximate Future Value using Simpson's Rule: $1643.62
Exact Future Value using formula: $1647.01

28. (Fluid Flow in a Pipe) Solve the equation for fluid flow in a pipe using the
Darcy-Weisbach Equation : f = 8 * L * V / (π * d⁴) Where: f is the Darcy
friction factor, L is the pipe length, V is the flow velocity, d is the pipe
diameter. Use Gauss-Seidel Iteration to solve for f given L = 50 m, V = 5
m/s, and d = 0.2 m.

Solution:
#include <iostream>
#include <cmath>
using namespace std;

const double PI = 3.14159265359;

// Function to compute new f


double computeF(double L, double V, double d) {
return (8 * L * V) / (PI * pow(d, 4));
}

int main() {
double L = 50.0;
double V = 5.0;
double d = 0.2;
double f_old = 0.0, f_new = 0.0;
int max_iter = 100;
double tol = 1e-6;
int iter = 0;
do {

67
Course Code: Math-310 Course Title: Math Lab III

f_old = f_new;
f_new = computeF(L, V, d);
iter++;
} while (fabs(f_new - f_old) > tol && iter < max_iter);

cout << "Darcy friction factor f after " << iter << " iterations: " << f_new << endl;

return 0;
}

Output:
Darcy friction factor f after 1 iterations: 39810.71706

29. (Structural Analysis - Beam Deflection) Given the deflection equation


for a simply supported beam: δ = PL³ / 48EI Where: P is the load on the
beam, L is the length of the beam, E is the Young’s modulus, I is the
moment of inertia. Use Trapezoidal Rule to approximate the deflection for
a beam with P = 1000 N, L = 10 m, E = 200 * 10⁹ Pa, and I = 1 * 10⁻⁶ m⁴.

Solution:
#include <iostream>
#include <cmath>
using namespace std;

// Function to integrate: f(x) = P * x^3 / (48 * E * I)


double f(double x, double P, double E, double I) {
return (P * pow(x, 3)) / (48.0 * E * I);
}

// Trapezoidal Rule
double trapezoidalRule(double P, double E, double I, double a, double b, int n) {
double h = (b - a) / n;
double sum = f(a, P, E, I) + f(b, P, E, I);

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


double x = a + i * h;
sum += 2 * f(x, P, E, I);
}
return (h / 2.0) * sum;

68
Course Code: Math-310 Course Title: Math Lab III

}
int main() {
double P = 1000.0; // N
double L = 10.0; // m
double E = 200e9; // Pa
double I = 1e-6; // m^4
int n = 100; // intervals for Trapezoidal Rule

double approx_delta = trapezoidalRule(P, E, I, 0, L, n);


double exact_delta = (P * pow(L, 3)) / (48.0 * E * I);

cout << "Approximated Deflection using Trapezoidal Rule: " << approx_delta
<< " meters" << endl;
cout << "Exact Deflection using formula: " << exact_delta << "
meters" << endl;

return 0;
}

Output:
Approximated Deflection using Trapezoidal Rule: 0.0104167 meters
Exact Deflection using formula: 0.0104167 meters

30. (Magnetic Field Calculation) Calculate the magnetic field intensity B


around a wire carrying a current I using Ampère’s Law: B = (μ₀ I) / (2π r)
where: μ₀ = 4π * 10⁻⁷ T·m/A is the permeability of free space, r is the
distance from the wire. Use Runge-Kutta (RK4) method to calculate B at
different distances from the wire.

Solution:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

const double PI = 3.14159265359;


const double MU_0 = 4 * PI * 1e-7;

69
Course Code: Math-310 Course Title: Math Lab III

// Derivative of B with respect to r: dB/dr = - (μ₀ I) / (2π r²)


double dB_dr(double r, double I) {
return - (MU_0 * I) / (2 * PI * r * r);
}
// Runge-Kutta 4th order method for numerical integration
double RK4(double r0, double B0, double h, int steps, double I) {
double r = r0;
double B = B0;

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


double k1 = h * dB_dr(r, I);
double k2 = h * dB_dr(r + h / 2.0, I);
double k3 = h * dB_dr(r + h / 2.0, I);
double k4 = h * dB_dr(r + h, I);

B += (k1 + 2*k2 + 2*k3 + k4) / 6.0;


r += h;
}

return B;
}

int main() {
double I = 10.0; // current in Amperes
double r_start = 0.01; // starting distance in meters (to avoid division by 0)
double r_end = 0.1; // ending distance in meters
double h = 0.01; // step size
int steps = (r_end - r_start) / h;

cout << fixed << setprecision(8);


cout << "r (m)\t\tB (T) using RK4\t\tB (T) exact" << endl;

for (double r = r_start; r <= r_end; r += h) {


double B_exact = (MU_0 * I) / (2 * PI * r);
double B_RK4 = RK4(r_start, (MU_0 * I) / (2 * PI * r_start), h, (r - r_start) / h,
I);
cout << r << "\t\t" << B_RK4 << "\t\t" << B_exact << endl;
}

return 0;
}

70
Course Code: Math-310 Course Title: Math Lab III

Output:
r (m) B (T) using RK4 B (T) exact
0.01 0.00019947 0.00019947
0.02 0.00009974 0.00009974
0.03 0.00006649 0.00006649
.... .... ....

71

You might also like