Lab 6 C++
Lab 6 C++
Exercise 1
Create a class called Complex for performing arithmetic with complex numbers. Complex numbers
have the form real + i imag, where i = √-1.
Use floating point variables to represent the private data of the class.
Provide a constructor to initialize a complex number when it is declared.
The constructor should contain the default values in case no initializing values are provided.
Provide public member functions to perform the following operations:
• Addition of two Complex numbers
• Subtraction of two Complex numbers
• Multiplication of two Complex numbers
• Printing of a Complex number in a+ib format.
Write a driver program to test your class.
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public:
Complex(float r = 0, float i = 0) : real(r), imag(i) {}
int main() {
Complex num1(3, 2); // 3 + 2i
Complex num2(1, 7); // 1 + 7i
return 0;
}
LAB 7
Exercise 2
Write a class to calculate the area and circumference of a circle.
Напишите класс для вычисления площади и длины окружности.
Class Circle
Private:
float radius;
Public:
2
ComputeArea(); //Area:Πr
ComputeCircumference(); //Circumfernce:2Πr
#include <iostream>
using namespace std;
class Circle {
private:
float radius;
public:
Circle(float r = 0) : radius(r) {}
int main() {
Circle circle1(5);
return 0;
}
LAB 7
Exercise 3
Write a C++ class named date. Its member data should consist of three ints: month, day, and year. It
should also have two member functions: getdate(), which allows the user to enter a date in 12/31/02
format, and showdate(), which displays the date.
Напишите класс C++ с именем date. Его данные-члены должны состоять из трех целых
чисел: месяц, день и год. В нем также должны быть две функции-члена: getdate(), которая
позволяет пользователю вводить дату в формате 31.12.02, и showdate(), которая отображает
дату. год будет высокосным, если он либо кратен 4 и не кратен 100, либо кратен 400. Это
позволяет учитывать исключения для годов, кратных 100, но не кратных 400.
#include <iostream>
#include <iomanip>
using namespace std;
class Date {
private:
int month;
int day;
int year;
int daysInMonth;
switch (m) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysInMonth = 30;
break;
case 2:
daysInMonth = isLeapYear(y) ? 29 : 28;
break;
default:
return false;
}
public:
void getDate() {
char slash;
bool valid = false;
do {
cout << "Enter date in MM/DD/YY format: ";
cin >> month >> slash >> day >> slash >> year;
LAB 7
int main() {
Date date;
date.getDate();
date.showDate();
return 0;
}
Exercise 4
Create a class called ship that incorporates a ship’s number and location in longitudes and latitudes. A
member function of the ship class should get a position from the user and store it in the object; another
should report the serial number and position.
Write a main() program that creates three ships, asks the user to input the position of each, and then
displays each ship’s number and position.
Создайте класс с именем ship, который содержит номер судна и его местоположение в долготах
и широтах. Функция-член класса ship должна получать информацию о местоположении от
пользователя и сохранять ее в объекте; другая функция должна сообщать серийный номер и
местоположение.
Напишите программу main(), которая создает три корабля, просит пользователя ввести
местоположение каждого из них, а затем отображает номер и местоположение каждого корабля.
#include <iostream>
#include <iomanip>
using namespace std;
class Ship {
private:
int shipNumber;
LAB 7
float longitude;
float latitude;
public:
void getPosition() {
cout << "Enter the longitude for ship " << shipNumber << ": ";
cin >> longitude;
cout << "Enter the latitude for ship " << shipNumber << ": ";
cin >> latitude;
}
int main() {
Ship ship1(1);
Ship ship2(2);
Ship ship3(3);
ship1.getPosition();
ship2.getPosition();
ship3.getPosition();
return 0;
}
Exercise 5:
Create an employee class. The member data should comprise an int for storing the employee
number and a float for storing the employee’s compensation. Member functions should allow the
user to enter this data and display it. Write main() function that allows the user to enter data for
three employees and display it (Use Array of objects).
Создайте класс employee. Данные-члены должны содержать int для хранения номера сотрудника
и float для хранения вознаграждения сотрудника. Функции-члены должны позволять
пользователю вводить эти данные и отображать их. Напишите функцию main(), которая
позволяет пользователю вводить данные для трех сотрудников и отображать их (используйте
массив объектов).
LAB 7
#include <iostream>
using namespace std;
class Employee {
private:
int employeeNumber;
float compensation;
public:
void getData() {
cout << "Enter employee number: ";
cin >> employeeNumber;
cout << "Enter employee compensation: ";
cin >> compensation;
}
int main() {
const int numEmployees = 3;
Employee employees[numEmployees];
return 0;
}
Exercise 6:
Create a C++ class named Sphere, which has one data members, radius of the sphere. Write set()
and get() methods to store and return the radius of the Sphere class. It also has a function named
Area() which calculates the area of the Sphere. Input the radius from the user and calculate the
area of the Sphere.
Создайте класс C++ с именем Sphere, в котором есть один элемент данных - радиус сферы.
Напишите методы set() и get() для хранения и возврата значения радиуса класса Sphere. В нем
LAB 7
также есть функция Area(), которая вычисляет площадь сферы. Введите радиус от пользователя
и вычислите площадь сферы.
#include <iostream>
#include <cmath>
using namespace std;
class Sphere {
private:
float radius;
public:
void set(float r) {
radius = r;
}
int main() {
Sphere sphere;
float radius;
sphere.set(radius);
cout << "The surface area of the sphere is: " << sphere.area() << endl;
return 0;
}
Exercise 7:
Create a class named myString,which consists of one string data member and three functions.
Input the string from the user at run time then call the following functions on it.
• void CountConsonants( ) //displays the total number of consonants in the string
• void VowelCount( ) //displays the total vowels in the string
• void Palindrome( ) //displays if the string is a palindrome or not
Use pointer of object to call the member function of the class.
LAB 7
Создайте класс с именем myString, который состоит из одного элемента данных string и трех
функций. Введите строку от пользователя во время выполнения, а затем вызовите для нее
следующие функции.
• void CountConsonants( ) //отображает общее количество согласных в строке
• void VowelCount( ) //отображает общее количество гласных в строке
• void Palindrome( ) //отображает, является ли строка палиндромом или нет
Используйте указатель на объект для вызова функции-члена класса.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class myString {
private:
string str;
public:
void inputString() {
cout << "Enter a string: ";
getline(cin, str);
}
void CountConsonants() {
int count = 0;
for (char ch : str) {
ch = tolower(ch);
if (isalpha(ch) && !(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch
== 'u')) {
count++;
}
}
cout << "Total consonants: " << count << endl;
}
void VowelCount() {
int count = 0;
for (char ch : str) {
ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
cout << "Total vowels: " << count << endl;
}
void Palindrome() {
string original = str;
LAB 7
original.erase(remove_if(original.begin(), original.end(), ::isspace),
original.end());
transform(original.begin(), original.end(), original.begin(), ::tolower);
if (original == reversed) {
cout << "The string is a palindrome." << endl;
} else {
cout << "The string is not a palindrome." << endl;
}
}
};
int main() {
myString *s = new myString;
s->inputString();
s->CountConsonants();
s->VowelCount();
s->Palindrome();
delete s;
return 0;
}