C++ Experiments

Experiment 8: Arithmetic Expressions

#include <iostream>
using namespace std;

int main() {
    int a = 21, b = 10, c;
    c = a + b;
    cout << "Addition: " << c << endl;
    c = a - b;
    cout << "Subtraction: " << c << endl;
    c = a * b;
    cout << "Multiplication: " << c << endl;
    c = a / b;
    cout << "Division: " << c << endl;
    c = a % b;
    cout << "Modulus: " << c << endl;
    return 0;
}
        

Experiment 9: Arrays

#include <iostream>
using namespace std;

int main() {
    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    cout << "Greeting message: " << greeting << endl;
    return 0;
}
        

Experiment 10: Functions

#include <iostream>
using namespace std;

int add(int, int);
int main() {
    int num1, num2;
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    cout << "Sum = " << add(num1, num2);
    return 0;
}
int add(int a, int b) {
    return a + b;
}
        

Experiment 11: Constructor & Destructor

#include <iostream>
using namespace std;
class Student {
public:
    Student() { cout << "Constructor Called" << endl; }
    ~Student() { cout << "Destructor Called" << endl; }
};
int main() {
    Student obj;
    return 0;
}
        

Experiment 12: Objects & Classes

#include <iostream>
using namespace std;
class Student {
    int roll;
    float fees;
public:
    void read() { cin >> roll >> fees; }
    void display() { cout << roll << " " << fees; }
};
int main() {
    Student s;
    s.read();
    s.display();
    return 0;
}
        

Experiment 19: Virtual Function

#include <iostream>
using namespace std;
class Base {
public:
    virtual void show() { cout << "Base Class"; }
};
class Derived : public Base {
public:
    void show() override { cout << "Derived Class"; }
};
int main() {
    Base *b; Derived d;
    b = &d;
    b->show();
    return 0;
}
        

Experiment 20: Friend Function

#include <iostream>
using namespace std;
class Base {
    int a, b;
public:
    void input() { cin >> a >> b; }
    friend float mean(Base ob);
};
float mean(Base ob) { return float(ob.a + ob.b) / 2; }
int main() {
    Base obj;
    obj.input();
    cout << "Mean: " << mean(obj);
    return 0;
}