LAB PRACTICE
DATA STRUCTURE AND ALGORITHMS
Topic
Classes & Objects
Example:1
#include <iostream>
using namespace std;
// Define a class named Car
class Car {
public:
// Attributes (data members)
string brand;
string model;
int year;
// Method (member function)
void start() {
cout << "The car " << brand << " " << model << " is starting." << endl;
}
};
int main() {
// Create an object of Car
Car car1;
// Assign values to the object’s members
[Link] = "Toyota";
[Link] = "Corolla";
[Link] = 2020;
// Call a method on the object
[Link]();
// Output object data
cout << "Brand: " << [Link] << endl;
cout << "Model: " << [Link] << endl;
cout << "Year: " << [Link] << endl;
return 0;
}
Example : 02
#include <iostream>
using namespace std;
class Person {
public:
string name;
int age;
void introduce() {
cout << "My name is " << name << " and I am " << age << " years old." <<
endl;
}
};
int main() {
Person p;
[Link] = "Alice";
[Link] = 25;
[Link]();
return 0;
}
Example : 03
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};
int main() {
Calculator calc;
int result = [Link](5, 3);
cout << "Sum is: " << result << endl;
return 0;
}
Example : 04
#include <iostream>
using namespace std;
class Square {
public:
int number;
void getInput() {
cout << "Enter a number: ";
cin >> number;
}
void findSquare() {
int result = number * number;
cout << "Square of " << number << " is: " << result << endl;
}
};
int main() {
Square s;
[Link]();
[Link]();
return 0;
}
Topic : Functions
Example : 01
#include <iostream>
using namespace std;
// Function definition
int add(int a, int b) {
return a + b;
}
void greet() {
cout << "Welcome to Functions!" << endl;
}
int main() {
greet(); // calling void function
int result = add(4, 6); // calling return function
cout << "Sum of two numbers 4 and 6 = " << result;
return 0;
}
Example : 02
#include <iostream>
using namespace std;
int main()
{
int a, b, c, d, e; // variables for 5 numbers
long long product; // to store multiplication result (use long long for
big numbers)
// Taking input
cout << "Enter 5 numbers: ";
cin >> a >> b >> c >> d >> e;
// Multiplying
product = a * b * c * d * e;
// Displaying result
cout << "The product of the 5 numbers is: " << product << endl;
return 0;
}
Example : 03
#include <iostream>
using namespace std;
void printName(string fname); // declaration
int main() {
printName("Liam");
printName("Jenny");
printName("Anja");
return 0;
}
void printName(string fname) { // definition
cout << fname << endl;
}