Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Кашина_СП_ЛБ5_2

.docx
Скачиваний:
0
Добавлен:
22.09.2026
Размер:
746 Кб
Скачать

Министерство науки и высшего образования Российской Федерации Федеральное государственное бюджетное образовательное учреждение высшего образования

«Владимирский государственный университет

имени Александра Григорьевича и Николая Григорьевича Столетовых» (ВлГУ)

Колледж инновационных технологий и предпринимательства

КАФЕДРА ФИЗИКИ И ПРИКЛАДНОЙ МАТЕМАТИКИ

Лабораторная работа № 5_2

по дисциплине «Системное программирование»

на тему: «Функции в С++

Выполнил

студент группы ИПсп-123

Кашина Д. А.

Принял

Красильщикова В. В.

Владимир, 2026

Цель: закрепление навыков работы с функциями в С++.

Задание 1:

Ход работы:

  1. Код программы

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

#include <cstring>

using namespace std;

// Функция вычисления суммы элементов двумерного целочисленного массива

int sumArray(int** arr, int rows, int cols) {

int sum = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

sum += arr[i][j];

}

}

return sum;

}

// Функция сортировки двумерного целочисленного массива

void sortArray(int** arr, int rows, int cols) {

int size = rows * cols;

int* temp = new int[size];

int index = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

temp[index++] = arr[i][j];

}

}

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (temp[j] > temp[j + 1]) {

int buf = temp[j];

temp[j] = temp[j + 1];

temp[j + 1] = buf;

}

}

}

index = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

arr[i][j] = temp[index++];

}

}

delete[] temp;

}

// Перегруженная функция для символьных массивов (сумма - объединение строк)

char* sumArray(char*** arr, int rows, int cols) {

int totalLength = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

totalLength += strlen(arr[i][j]) + 1;

}

}

totalLength += 1;

char* result = new char[totalLength];

result[0] = '\0';

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

strcat(result, arr[i][j]);

if (i == rows - 1 && j == cols - 1) {

strcat(result, ".");

}

else {

strcat(result, " ");

}

}

}

return result;

}

// Перегруженная функция сортировки для строк (по алфавиту)

void sortArray(char*** arr, int rows, int cols) {

int size = rows * cols;

char** temp = new char* [size];

int index = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

temp[index++] = arr[i][j];

}

}

for (int i = 0; i < size - 1; i++) {

for (int j = 0; j < size - i - 1; j++) {

if (strcmp(temp[j], temp[j + 1]) > 0) {

char* buf = temp[j];

temp[j] = temp[j + 1];

temp[j + 1] = buf;

}

}

}

index = 0;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

arr[i][j] = temp[index++];

}

}

delete[] temp;

}

int main() {

setlocale(LC_ALL, "rus");

cout << "ОБЩЕЕ ЗАДАНИЕ" << endl;

cout << "Кашина Ипсп-123" << endl;

cout << "=============" << endl << endl;

// Часть 1-2: Работа с целочисленными массивами

cout << "1-2. Работа с целочисленными массивами:" << endl;

int rows = 2, cols = 3;

int** intArr = new int* [rows];

for (int i = 0; i < rows; i++) {

intArr[i] = new int[cols];

}

int value = 5;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

intArr[i][j] = value--;

}

}

cout << "Исходный массив:" << endl;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << intArr[i][j] << " ";

}

cout << endl;

}

int sum = sumArray(intArr, rows, cols);

cout << "Сумма элементов: " << sum << endl;

sortArray(intArr, rows, cols);

cout << "Отсортированный массив:" << endl;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << intArr[i][j] << " ";

}

cout << endl;

}

for (int i = 0; i < rows; i++) {

delete[] intArr[i];

}

delete[] intArr;

cout << endl;

// Часть 2: Работа с символьными массивами

cout << "2. Работа с символьными массивами:" << endl;

int strRows = 2, strCols = 2;

char*** strArr = new char** [strRows];

for (int i = 0; i < strRows; i++) {

strArr[i] = new char* [strCols];

}

strArr[0][0] = new char[10];

strArr[0][1] = new char[10];

strArr[1][0] = new char[10];

strArr[1][1] = new char[10];

strcpy(strArr[0][0], "Hello");

strcpy(strArr[0][1], "world");

strcpy(strArr[1][0], "C++");

strcpy(strArr[1][1], "programming");

cout << "Исходный массив строк:" << endl;

for (int i = 0; i < strRows; i++) {

for (int j = 0; j < strCols; j++) {

cout << strArr[i][j] << " ";

}

cout << endl;

}

char* sentence = sumArray(strArr, strRows, strCols);

cout << "Полученное предложение: " << sentence << endl;

sortArray(strArr, strRows, strCols);

cout << "Отсортированные строки:" << endl;

for (int i = 0; i < strRows; i++) {

for (int j = 0; j < strCols; j++) {

cout << strArr[i][j] << " ";

}

cout << endl;

}

delete[] sentence;

for (int i = 0; i < strRows; i++) {

for (int j = 0; j < strCols; j++) {

delete[] strArr[i][j];

}

delete[] strArr[i];

}

delete[] strArr;

cout << endl;

// Часть 3: Указатель на функцию

cout << "3. Указатель на функцию:" << endl;

rows = 2; cols = 3;

int** demoArr = new int* [rows];

for (int i = 0; i < rows; i++) {

demoArr[i] = new int[cols];

}

value = 1;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

demoArr[i][j] = value++;

}

}

int (*funcPtr)(int**, int, int);

funcPtr = &sumArray;

int result = (*funcPtr)(demoArr, rows, cols);

cout << "Массив:" << endl;

for (int i = 0; i < rows; i++) {

for (int j = 0; j < cols; j++) {

cout << demoArr[i][j] << " ";

}

cout << endl;

}

cout << "Сумма элементов (вызов через указатель): " << result << endl;

for (int i = 0; i < rows; i++) {

delete[] demoArr[i];

}

delete[] demoArr;

return 0;

}

  1. Результат работы программы

  1. Блок схема программы

Задание 2:

Ход работы:

  1. Код программы:

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>

#include <string>

using namespace std;

// Функция для двух целочисленных параметров - возвращает максимальное

int max(int a, int b) {

if (a > b)

return a;

else

return b;

}

// Перегруженная функция для трех целочисленных параметров - возвращает максимальное

int max(int a, int b, int c) {

int temp;

if (a > b)

temp = a;

else

temp = b;

if (temp > c)

return temp;

else

return c;

}

int main() {

setlocale(LC_ALL, "rus");

cout << "Кашина ИПсп-123" << endl;

cout << "ИНДИВИДУАЛЬНОЕ ЗАДАНИЕ (ВАРИАНТ 4)" << endl;

cout << "===================================" << endl << endl;

// Демонстрация функции с двумя параметрами

cout << "Функция с двумя параметрами:" << endl;

int x1 = 15, x2 = 25;

cout << "x1 = " << x1 << ", x2 = " << x2 << endl;

cout << "Максимальное значение: " << max(x1, x2) << endl << endl;

// Демонстрация перегруженной функции с тремя параметрами

cout << "Перегруженная функция с тремя параметрами:" << endl;

int y1 = 42, y2 = 17, y3 = 33;

cout << "y1 = " << y1 << ", y2 = " << y2 << ", y3 = " << y3 << endl;

cout << "Максимальное значение: " << max(y1, y2, y3) << endl << endl;

// Дополнительные тесты

cout << "Дополнительные тесты:" << endl;

cout << "max(10, 5) = " << max(10, 5) << endl;

cout << "max(-10, -5) = " << max(-10, -5) << endl;

cout << "max(7, 7) = " << max(7, 7) << endl;

cout << "max(100, 50, 75) = " << max(100, 50, 75) << endl;

cout << "max(-30, -20, -10) = " << max(-30, -20, -10) << endl;

cout << "max(5, 10, 5) = " << max(5, 10, 5) << endl;

return 0;

}

  1. Результат выполнения программы:

  1. Блок-схема программы:

Вывод: в ходе лабораторной работы были закреплены навыки работы с функциями в С++.

Соседние файлы в предмете Системное программирование