DSALab 04
DSALab 04
DSA Lab 04
Activity 1
Write polynomial class
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
class Term {
public:
int coefficient;
int exponent;
class Polynomial {
private:
std::vector<Term> terms;
public:
// Add a term to the polynomial
void addTerm(int coefficient, int exponent) {
for (size_t i = 0; i < terms.size(); ++i) {
if (terms[i].exponent == exponent) {
terms[i].coefficient += coefficient;
if (terms[i].coefficient == 0) {
// Remove the term if the coefficient becomes zero
terms.erase(terms.begin() + i);
}
return;
}
}
// Otherwise, add a new term
terms.push_back(Term(coefficient, exponent));
}
int main() {
Polynomial polynomial;
int numTerms, coeff, exp;
return 0;
}
Result
Enter the number of terms in the polynomial: 3
Enter coefficient and exponent for term 1: 9 2
Enter coefficient and exponent for term 2: 5 7
Enter coefficient and exponent for term 3: 4 2
The polynomial is: 13x^2 +5x^7
Activity 2
#include <iostream>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int number;
if (number < 0) {
std::cout << "Factorial is not defined for negative numbers." << std::endl;
} else {
std::cout << "Factorial of " << number << " is " << factorial(number) <<
std::endl;
}
return 0;
}
Activity 3
#include <iostream>
void fibonacci(int n) {
int a = 0, b = 1, nextTerm;
std::cout << "Fibonacci Sequence up to " << n << " terms:" << std::endl;
for (int i = 1; i <= n; ++i) {
std::cout << a << " ";
nextTerm = a + b;
a = b;
b = nextTerm;
}
std::cout << std::endl;
}
int main() {
int numTerms;
std::cout << "Enter the number of terms in the Fibonacci sequence: ";
std::cin >> numTerms;
if (numTerms <= 0) {
std::cout << "Please enter a positive integer." << std::endl;
} else {
fibonacci(numTerms);
}
return 0;
}
Activity 4
#include <iostream>
int main() {
int num1, num2;
std::cout << "The GCD of " << num1 << " and " << num2 << " is: " << result
<< std::endl;
return 0;
}
Activity 5
Graded Lab