Professional Documents
Culture Documents
Lab-Mid-Term Solution: Lahore University of Management and Sciences
Lab-Mid-Term Solution: Lahore University of Management and Sciences
Lab-Mid-Term Solution
for
Introduction to Programming
(CS200)
Question-1:
int sumOfDigits(int x) {
if (x >= 0 && x <= 9)
return x;
return (x % 10) + sumOfDigits(x / 10);
}
int main() {
int x = 9123871298;
if (x < 0)
x = x * (-1);
cout << sumOfDigits(x);
return 0;
}
Question-2:
bool is_anagram(string s1, string s2) {
bool check = true;
for (int i = 0; i < s1.size(); i++) {
for (int j = 0; j < s1.size(); j++) {
if (s1[i] == s2[j]) {
s2[j] = '&';
break;
}
}
return 0;
}
Question-3:
#include<iostream>
#include<string>
using namespace std;
class Polynomial {
private:
int* coeffs;
int size;
public:
Polynomial() {
size = 4;
coeffs = new int[4];
for (int i = 0; i < 4; i++)
coeffs[i] = 0;
}
Polynomial(const Polynomial &obj) {
size = obj.size;
coeffs = new int[size];
for (int i = 0; i < size; i++) {
coeffs[i] = obj.coeffs[i];
}
}
void operator = (const Polynomial& obj) {
size = obj.size;
coeffs = new int[size];
for (int i = 0; i < size; i++) {
coeffs[i] = obj.coeffs[i];
}
}
~Polynomial() {
size = 0;
delete[] coeffs;
}
Polynomial(string s) {
size = 4;
coeffs = new int[4];
for (int i = 0; i < 4; i++)
coeffs[i] = 0;
//Loop over the whole string e.g of form "3x3+x+4"
for (int i = 0; i < s.size(); i++) {