Challenge

Project 1

Solution-

Steps involved in solving the problem

  1. The iostream and fstream header files are included for input/output operations.
#include <iostream> #include <fstream> using namespace std;
  1. The main function is defined, which is the entry point of the program.
int main() { // Code goes here return 0; }
  1. The user is prompted to enter the number of rows and columns for the arrays commodities, vendors, and result.
int rows, cols; cout << "Enter the number of rows and columns: "; cin >> rows >> cols;
  1. Memory is dynamically allocated for the arrays using nested loops and new operator.
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]; }
  1. A do-while loop 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);
  1. Inside the do-while loop, 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;
  1. If the user chooses to save the data to a file, the ofstream class 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"; }
  1. Memory is deallocated using nested loops and the delete operator.
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;
  1. The main function 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

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.