Question

In: Economics

Matrix Calculator Goals Write, compile and test a matrix calculator program Review the concept of pointers,...

Matrix Calculator

Goals

  • Write, compile and test a matrix calculator program
  • Review the concept of pointers, and multi-dimensional dynamic arrays
  • Create a simple makefile
  • Write a robust input validation.

The purpose of this lab is to get familiar with the software environment we will be using this term, and review some C++ concepts to get prepared for future projects and labs. This lab might be very time-consuming since there are a lot of concepts you need to pick up.

For this course, we will be compiling code on the flip server. It is advised to use vim editor on the flip server to program, but you are allowed to use other IDEs or text editors. Please test the program on flip server before turning it in.

Requirements

Files:

For simplicity, there are only 2 sizes of matrix for this program: either a 2x2 or a 3x3 matrix.

Create a matrix calculator program that consists of 5 files.

The program should have two functions:

  • void readMatrix()
  • int determinant()

Each function should have its own header files (.hpp) and source code (.cpp). Including the main file that contains main function to run the program, there should be 5 files for the program to be compiled and run properly.

main function:

The main function should contain following steps:

  1. Ask the users to choose the size of the matrix (2x2 or 3x3).
  2. Dynamically allocates the memory space for the matrix, using readMatrix() to prompt the user to enter 4 or 9 integers to fill the matrix
  3. Calculate the determinant using determinant().
  4. Display both the matrix and the determinant to the user.

Note: please display the matrix in a square format, do not display it in a line.

  1. Free the dynamically allocated memory

void readMatrix():

The readMatrix() function has two parameters:

  • A pointer to a 2D array
  • An integer as the size of the matrix

The function should prompt the user for all the numbers within the matrix, that means for 2x2 matrix, it should ask the user for 4 numbers, and 9 numbers for a 3x3 matrix. Because the function takes a pointer to the 2D array, it should not return anything.

int determinant():

The determinant() function has two parameters:

  • A pointer to a 2D array
  • An integer as the size of the matrix

The function takes in the 2D array, which contains the value inside the matrix, and calculate the determinant. Afterwards, the function should return the determinant.

Note on how to calculate determinant of 2x2 and 3x3 matrices:

https://www.mathsisfun.com/algebra/matrix-determinant.html (Links to an external site.)Links to an external site.

Dynamic Memory

The program needs to dynamically allocate the 2D array in main function, and free the dynamically allocated memory when it is no longer in use. The following link can provide some hint:

http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new (Links to an external site.)Links to an external site.

The program must use dynamic memory for this lab. This will help you understand how standard containers work.

If memories are allocated but never freed during program runtime, it will cause memory leak. We will enforce the memory leak check from this lab to future projects/labs. If you have memory leaks for lab 1, lab 2, and project 1, you will not be penalized for it. From lab 3 and project 2, if you still have memory leaks, TAs will take points off up to 10% of the grade.

Input validation

In this lab, you can assume users will only input integers when asked, and TAs won’t test the program using other types of input, but what if they do?

Input validation is very important, it prevents the program from crashing when user input the wrong type of input. For example, inputting a character “c” when prompted an integer.

Try to write an input validation function that checks the user inputs’ data type. It should return an error message if the input type does not match what is prompted, and recovers from it by re-prompting for input, until the user enters the correct data type.

Input validation is not required for this lab, but you need to start learning it since it will be required in the future.

Makefile

Once your program is working, create a makefile to build the program. You do not need a complicated makefile; you only need a makefile that have following two target (functionalities):

  • Compiling, by typing “make” in the command line, the makefile compiles the program using g++.
  • Removing executables, by typing “make clean” in the command line, the makefile removes all the files created during compiling.

To get help on makefile, please watch the lecture videos, check out the make help sessions in the resource module on Canvas, and join the group discussions of makefile on Piazza.

What you need to submit:

  • 5 files for the program
  • makefile

Please put the 6 files into a zip archive. The name of the zip file should follow this format:

Lab1_LastName_FirstName.zip

Please submit ONLY the zip file on Canvas by the due date.

The following command is for zipping all the files: (entire command in one line)

zip –D Lab1_LastName_FirstName.zip file1.cpp file2.cpp file1.hpp file2.hpp main.cpp makefile

There should be no internal directories in the zip file, meaning the zip file should not create a new folder when unzipped (Please test the unzipping on flip server, since TAs will be grading on flip server)

Remember to back up your files in your local computer frequently if you are developing on flip. If you delete your files by accident on flip, you might not be able to get it back.

Solutions

Expert Solution

main.cpp
--------------------------------------------------------------------
#include <iostream>
#include <string>
#include "readMatrix.hpp"

using namespace std;

int main(){

//Prompt the user for the size of matrix to be calculated.
cout << "Welcome to the matrix determinant calculator!\n" << endl;
cout << "Please select the matrix size you would like to input: " << endl;
cout << "\t (A): 2x2 matrix" << endl;
cout << "\t (B): 3x3 matrix\n" << endl;

char selection; //Stores matrix size selection
cin >> selection;

int size; //Size of matrix

//Uses selection from user to determine value to assign to 'size'
if (selection == 'A' || selection == 'a'){
size = 2;
}
else if (selection == 'B' || selection == 'b'){
size = 3;
}
else{
cout << "Your selection is invalid. Please start over." << endl;
return 0;
}

cout << "\nYou have selected a " << size << "x" << size << " matrix.\n" << endl;

//Initialize pointer array
int** matrix = new int*[size];
for (int i = 0; i < size; i++){
matrix[i] = new int[size];
}

readMatrix(matrix, size); //Sets up matrix by taking input from user
int calc = determinant(matrix, size); //Calculates determinant

cout << "The " << size << "x" << size << " matrix is: " << endl;

//Displays the matrix on the console
for (int row = 0; row < size; row++){
for (int col = 0; col < size; col++){
cout << matrix[row][col] << "\t";
}
cout << "\n";
}

//Deletes stored data
for (int i = 0; i < size; i++){
delete[] matrix[i];
}
delete[] matrix;

cout << "\nThe determinant of the matrix is: " << calc << endl;

return 0;
}
-------------------------------------------------------------------------------------------------------
determinant.cpp
---------------------------------------------------
#include <iostream>
#include <string>
#include "readMatrix.hpp"
#include "determinant.hpp"

using namespace std;

int determinant(int** matrix, int size){

int detm_calc; //Determinant calculation variable

//Determine which formula to use - 2x2 or 3x3 matrix.
if (size == 2){ //2x2 case
int a = matrix[0][0];
int b = matrix[0][1];
int c = matrix[1][0];
int d = matrix[1][1];

detm_calc = (a*d) - (b*c);

}

else{ //3x3 case
int a = matrix[0][0];
int b = matrix[0][1];
int c = matrix[0][2];
int d = matrix[1][0];
int e = matrix[1][1];
int f = matrix[1][2];
int g = matrix[2][0];
int h = matrix[2][1];
int i = matrix[2][2];

detm_calc = a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g);
}
return detm_calc;
}
---------------------------------------------------------------------------------------------------------
determinant.hpp
-----------------------------------------------------
#ifndef DETERMINANT_HPP
#define DETERMINANT_HPP

#include <string>
#include <iostream>
#include "readMatrix.hpp"

int determinant(int**, int);

#endif
-----------------------------------------------------------------------------------------------
readMatrix.cpp
-----------------------------------------------------
#include <iostream>
#include <string>
#include "readMatrix.hpp"
#include "determinant.hpp"

using namespace std;


void readMatrix(int** matrix, int size){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
cout << "Please enter the integer for row " << i+1 << " column " << j+1 << ":\t";
cin >> matrix[i][j];
}
cout << "\n";
}
}
-------------------------------------------------------------------------------------------
readMatrix.hpp
-----------------------------------------------------
#ifndef READMATRIX_HPP
#define READMATRIX_HPP

#include <string>
#include <iostream>
#include "determinant.hpp"

void readMatrix(int**, int);

#endif


Related Solutions

(17pts)Write, compile, and test a C++ program that uses an if-else structure for problem 3.7 on...
(17pts)Write, compile, and test a C++ program that uses an if-else structure for problem 3.7 on page 108.  Use the format specified earlier (initial block of comments with TCC logo, name, etc) Display instructions so that the user understands the purpose of the program and what to enter. Display the results in increasing (non-decreasing) order. Run the program for the following 6 test cases.Turn in a printout of the program and printouts of the 6 test cases.(The result should...
Goals Practice conditional statements Description Write a program to simulate a menu driven calculator that performs...
Goals Practice conditional statements Description Write a program to simulate a menu driven calculator that performs basic arithmetic operations (add, subtract, multiply and divide). The calculator accepts two numbers and an operator from user in a given format: For example: Input: 6.3 / 3 Output: 2.1 Create a Calculator class that has a method to choose the right mathematical operation based on the entered operator using switch case. It should then call a corresponding method to perform the operation. In...
Chapter 9 (Pointers) - Review Questions Find the Error Each of the following definitions and program...
Chapter 9 (Pointers) - Review Questions Find the Error Each of the following definitions and program segments has errors. Locate as many as you can. 46. int ptr* = nullptr; 47. int x, *ptr = nullptr; &x = ptr; 48. int x, *ptr = nullptr; *ptr = &x; 49. int x, *ptr = nullptr; ptr = &x; ptr = 100; //Store 100 in x cout << x << endl; 50. int numbers[] = {10, 20, 30, 40, 50}; cout <<...
UNIX/LINUX LAB (1) Review the sample shell program (tryShell.c), and compile/run the program (tryShell) with the...
UNIX/LINUX LAB (1) Review the sample shell program (tryShell.c), and compile/run the program (tryShell) with the following commands, and at the end, use CTRL+C to terminate the program: ls ls -l tryShell* date whoami hostname uname -a ctrl+C    (2) Run the program (tryShell) with "time -p" with a few commands: time -p ./tryShell (3) Edit the program (tryShell.c) so that it will exit (terminate the program) when the input command string is "exit" try shell.c code at bottom //////////// #include...
write a program to make scientific calculator in java
Problem StatementWrite a program that uses the java Math library and implement the functionality of a scientific calculator. Your program should have the following components:1. A main menu listing all the functionality of the calculator.2. Your program should use the switch structure to switch between various options of the calculator. Your Program should also have the provision to handle invalidoption selection by the user.3. Your calculator SHOULD HAVE the following functionalities. You can add any other additional features. PLEASE MAKE...
C++ Goals: Write a program that works with binary files. Write a program that writes and...
C++ Goals: Write a program that works with binary files. Write a program that writes and reads arrays to and from binary files. Gain further experience with functions. Array/File Functions Write a function named arrayToFile. The function should accept three arguments: the name of file, a pointer to an int array, and the size of the array. The function should open the specified file in binary made, write the contents into the array, and then close the file. write another...
In MPLAB write and compile (using the simulator) an assembly language program with the following functionality:...
In MPLAB write and compile (using the simulator) an assembly language program with the following functionality: Configures pin RA2 of the PIC24to be an output to control an attached LED. Configures pin RB13 of the PIC24 to be an input to read the value on an attached switch (this switch will connect to ground when pressed). Configures pin RB13 to use the internal pull-up resistor. After configuration, the LED will be "off" when the push-button is pressed, and "on" when...
6. Write a program in C programming (compile and run), a pseudocode, and draw a flowchart...
6. Write a program in C programming (compile and run), a pseudocode, and draw a flowchart for each of the following problems: a) Obtain three numbers from the keyboard, compute their product and display the result. b) Obtain two numbers from the keyboard, and determine and display which (if either) is the smaller of the two numbers. c) Obtain a series of positive numbers from the keyboard, and determine and display their average (with 4 decimal points). Assume that the...
Write a complete C program that searches an element in array using pointers. Please use the...
Write a complete C program that searches an element in array using pointers. Please use the function called search to find the given number. //Function Prototype void search (int * array, int num, int size)
write a C++ Program for matrix operations which include: 1. constructor in the form-- matrix::matrix(int numRows,...
write a C++ Program for matrix operations which include: 1. constructor in the form-- matrix::matrix(int numRows, int numColumns) 2. Implement a setter method of the form: -- void matrix::setElement(int row, int col) 3 Implement a getter method of the form: -- float matrix::getElement(int row, int col) 4. Make a threaded version of the matrix/matrix addition method. 5. Make a threaded version of the matrix/scalar multiplication method. 6. Matrix/matrix addition methods of the form: -- matrix matrix::matrixAdd(matrix inMatrix) // non-threaded version...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT