Project 1
Solution-
Steps involved in solving the problem
- The
iostreamandfstreamheader files are included for input/output operations.
#include <iostream>
#include <fstream>
using namespace std;
- The
mainfunction is defined, which is the entry point of the program.
int main() {
// Code goes here
return 0;
}
- The user is prompted to enter the number of rows and columns for the arrays
commodities,vendors, andresult.
int rows, cols;
cout << "Enter the number of rows and columns: ";
cin >> rows >> cols;
- Memory is dynamically allocated for the arrays using nested loops and
newoperator.
int** commodities = new int*[rows];
for (int i = 0; i < rows; i++) {
commodities[i] = new int[cols];
}
double** vendors = new double*[rows];
for (int i = 0; i < rows; i++) {
vendors[i] = new double[cols];
}
double** result = new double*[rows];
for (int i = 0; i < rows; i++) {
result[i] = new double[cols];
}
- A
do-whileloop is used to display a menu of options for the user to input data, until they choose to exit the program.
int choice;
do {
cout << "Menu:\n";
cout << "1. Enter commodities to be purchased\n";
cout << "2. Enter vendor quotations\n";
cout << "3. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
// Code to input commodities data
break;
case 2:
// Code to input vendor data
break;
case 3:
// Code to exit program
break;
default:
cout << "Invalid choice. Please try again.\n";
break;
}
} while (choice != 3);
- Inside the
do-whileloop, each case statement is left blank for now, as we have not yet implemented the code to input data.
case 1:
// Code to input commodities data
break;
case 2:
// Code to input vendor data
break;
case 3:
// Code to exit program
break;
- If the user chooses to save the data to a file, the
ofstreamclass is used to write the data to a file named "data.txt".
ofstream outfile("data.txt");
if (outfile.is_open()) {
// Code to write data to file
outfile.close();
} else {
cout << "Error: Unable to open file.\n";
}
- Memory is deallocated using nested loops and the
deleteoperator.
for (int i = 0; i < rows; i++) {
delete[] commodities[i];
}
delete[] commodities;
for (int i = 0; i < rows; i++) {
delete[] vendors[i];
}
delete[] vendors;
for (int i = 0; i < rows; i++) {
delete[] result[i];
}
delete[] result;
- The
mainfunction returns 0 to indicate successful completion of the program.
return 0;
Overall, this program demonstrates the basics of dynamically allocating memory for multi-dimensional arrays, displaying a menu of options for user input, writing data
