demo-infile-2d-array - // >> goes to...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
// Programmer: Doug Hogan // Program: Demo Program: 2D Arrays and Input Files // Date: November 6, 2008 // Description: This program reads a matrix from files add multiplies it by // a scalar multiple. #include <iostream> // for cin, cout #include <fstream> // for file input #include <iomanip> // for setw using namespace std; const int NUM_ROWS = 6; // number of rows in matrix const int NUM_COLS = 4; // number of columns in matrix int main() { double scalar; // scalar value by which to multiply double matrix[NUM_ROWS][NUM_COLS]; // input matrix double output[NUM_ROWS][NUM_COLS]; // output matrix (input times scalar) ifstream infile("matrix.txt"); // open file containing matrix if(!infile) // check that file is found { cout << "File not found."; } else // file found, so process it { // INPUT: Read matrix from file for(int row = 0; row < NUM_ROWS; row++) // read in rows { for(int col = 0; col < NUM_COLS; col++) // read in columns { infile >> matrix[row][col]; // read current element
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // &gt;&gt; goes to whitespace, so we // get just one element at a time } } infile.close(); // close file now since input // from file is done cout &lt;&lt; &quot;Enter scalar multiple: &quot;; cin &gt;&gt; scalar; // PROCESS: Multiply by scalar for(int row = 0; row &lt; NUM_ROWS; row++) // go through rows { for(int col = 0; col &lt; NUM_COLS; col++) // go through columns { output[row][col] = scalar * matrix[row][col]; // multiply element-wise } } // OUTPUT: Display product matrix cout &lt;&lt; &quot;Product of input matrix and scalar &quot; &lt;&lt; scalar &lt;&lt; &quot;:&quot; &lt;&lt; endl; for(int row = 0; row &lt; NUM_ROWS; row++) // go through rows { for(int col = 0; col &lt; NUM_COLS; col++) // go through columns { cout &lt;&lt; output[row][col] &lt;&lt; '\t'; // Comment out the above line and uncomment the line below // for a neater output we'll learn about very soon. // (Requires the &quot;iomanip&quot; header above.) //cout &lt;&lt; setw(8) &lt;&lt; output[row][col]; // print out element // lined up neatly } cout &lt;&lt; endl; } } }...
View Full Document

Page1 / 2

demo-infile-2d-array - // &amp;amp;gt;&amp;amp;gt; goes to...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online