Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a...

23
Lecture 1 -- 1 Computer Science I - Martin Hardwick Function Prototypes Sometimes we want to use a function before it is defined. If so we define a function prototype. This is the same as defining the function but we end the header with a semicolon. Later in the program we define the function using the normal syntax. I.E. {} follows the header #include <iostream> using namespace std; // Function prototypes int readData(int &a, int &b int &c); int addData(int a, int b, int c, int d, int e, int f, int &x, int &y, int &z); int main() { int a, b, c; int d, e, f; int r, s, t; readData (a, b, c); readData (d, e, f); addData (a, b, c, d, e, f, r, s, t);

Transcript of Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a...

Page 1: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 1Computer Science I - Martin Hardwick

Function Prototypes

Sometimes we want to use a function before it is defined.

If so we define a function prototype.

This is the same as defining the function but we end the header with a semicolon.

Later in the program we define the function using the normal syntax.

I.E. {} follows the header

#include <iostream>using namespace std;

// Function prototypesint readData(int &a, int &b int &c);int addData(int a, int b, int c,

int d, int e, int f, int &x, int &y, int

&z);int main(){

int a, b, c;int d, e, f;int r, s, t;

readData (a, b, c);readData (d, e, f);addData (a, b, c, d, e, f, r, s, t);

return;}// code for readData, addData goes

here

Page 2: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 2Computer Science I - Martin Hardwick

Adding Matrices

1 2 34 5 67 8 90 1 2

1 1 12 2 23 3 34 4 4

2 3 4 5 7 810 11 12 4 5 6

+ =

Matrix 1 Matrix 2 Sum ofMatrices1 and 2

Add corresponding elements of Matrix 1 and Matrix 2 to produce the Sum matrix.

To add two matrices, they must have the same number of rows and columns.

Page 3: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 3Computer Science I - Martin Hardwick

Adding Matrices (1)

#include <iostream>using namespace std;

// Function prototypesvoid readMatrix(int matrix[ ][100],

int rows, int cols);void addMatrix( int mat1[ ][100],

int mat2[ ][100], int sum[ ][100],

int rows, int cols);int main()//PURPOSE: test readMatrix &

addMatrix//PRECONDITIONS: none//POSTCONDITIONS: ret 0 if success{

// First matrixint matrix1[100][100];

// Second matrixint matrix2[100][100];

We will represent a table / matrix / spreadsheet in a C++ program as a two-dimensional array.

A two-dimensional array is declared similarly to a one-dimensional array, but you must specify the maximum number of rows and columns.

In this program, we read two matrices and compute their sum in a third matrix.

We need two functions: readMatrix – prompt the

user for the data to put in a matrix

addMatrix – sum two matrices putting the result in a third

Remember: arrays are always passed by reference (you don’t use the & symbol)

Page 4: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 4Computer Science I - Martin Hardwick

Two-Dimensional Arrays

Example: int tab[3][4];

The first subscript is the row number, starting at 0.

The second subscript is the column number, starting at 0.

All the elements of a two-dimensional array are the same type.

An element in a two-dimensional array can be used anywhere an ordinary variable can be used.

The subscripts can be expressions whose values are used to identify a particular array element.

tab[0][0] tab[0][1] tab[0][2] tab[0][3]

tab[1][0] tab[1][1] tab[1][2] tab[1][3]

tab[2][0] tab[2][1] tab[2][2] tab[2][3]

Page 5: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 5Computer Science I - Martin Hardwick

Adding Matrices (2)

// Sum of matricesint sum[100][100];

// Matrix sizeint rows, cols;

// Loop variablesint i,j;

// Read size of matricescout << "Enter number of rows: ";cin >> rows;cout<<"Enter number of columns: ";cin >> cols;

// Read matricesreadMatrix(matrix1, rows, cols);readMatrix(matrix2, rows, cols);

We may not use the entire array each time the program runs.

we use the upper left corner of the array

variable rows tells us how many rows we are using

variable cols tells us how many columns we are using

When passing a two-dimensional array to a function, just use the name of the array without subscripts as the argument.

Page 6: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 6Computer Science I - Martin Hardwick

Adding Matrices (3)

// Add matricesaddMatrix(matrix1, matrix2, sum,

rows, cols);

// Display sum of matricescout << endl

<< "Sum of the matrices:" << endl;

for (i=0; i<rows; i=i+1) { for (j=0; j<cols; j=j+1) {

cout << "\t" << sum[i][j]; } cout << endl;}

return 0;}

When using two-dimensional arrays, it is common to use nested for loops to process all the elements in an array.

the outer loop ranges over the rows of the array

the inner loop ranges over the elements in one row

When displaying the array, note that a tab is used to force the display into columns.

Note also that the endl is done inside the outer loop, but outside the inner loop.

this starts a new line for every row of the array

Page 7: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 7Computer Science I - Martin Hardwick

Adding Matrices (4)

void readMatrix(int matrix[ ][100], int rows, int cols)

//PURPOSE: get matrix data from user//PRECONDITIONS: 0 < rows < number // of rows, and 0 < cols < number of // columns//POSTCONDITIONS: data put in matrix{

int i,j; // loop variables

cout << "Enter data for matrix with" << rows << " rows and " << cols << " columns:" << endl;

for (i=0; i<rows; i++) {for (j=0; j<cols; j++) {

cin >> matrix[i][j];}

}}

This function prompts the user for data to read into a two-dimensional array.

When a parameter is a two-dimensional array, do not specify the number of rows.

but you must specify the number of columns

Parameters rows and cols are needed so that the function knows how many rows and columns of data to read.

Note the nested for loops again.

Page 8: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 8Computer Science I - Martin Hardwick

Adding Matrices (5)

void addMatrix( int mat1[ ][100], int mat2[ ][100],

int sum[ ][100], int rows, int cols)

//PURPOSE: add to matrices//PRECONDITIONS: 0 < rows <

number // of rows, and 0 < cols < number

of // columns//POSTCONDITIONS: matrix sum // contains mat1 + mat2{

int i,j; // loop variables

for (i=0; i<rows; i++) {for (j=0; j <= cols; j++) {

sum[i][j] = mat1[i][j] + mat2[i]

[j];}

}}

This function adds to matrices (parameters 1 and 2), putting the sum in a third matrix (parameter 3).

When adding matrices, you add corresponding elements.

Again, note the use of nested for loops to process all elements in the arrays.

Page 9: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 9Computer Science I - Martin Hardwick

Output Of Program

Page 10: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 10Computer Science I - Martin Hardwick

Heat Flow (1)

#include <iostream>#include <cmath>#include <fstream>#include <iomanip>#include "Canvas.h"#include "Colors.h"using namespace std;

int main ()//PURPPOSE: simulate heat flow in a // metal plate//PRECONDITIONS: none//POSTCONDITIONS: create a file // named report.txt and graphical// display with final temperatures

{

// grid of nodes representing platefloat plate[100][100];

Problem Statement:

We will use an iterative technique to solve this problem.

finite-element analysis

100 degrees

100 degrees

10 d

egre

es

10 degrees

What is thetemperaturehere ?

Page 11: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 11Computer Science I - Martin Hardwick

Solution Technique

Compute the new temperature of each interior point as the average of its four neighbors’ temperatures.

Repeat until the temperatures at each node do not change much.

100 degrees

100 degrees

10 d

egre

es 10 degrees

Ti , j

T i , j

T i , j + 1

T i + 1 , j

T i - 1 , j

T i , j - 1

T i + 1, j + T i, j + 1 + T i - 1, j + T i, j - 1

4T i, j =

Page 12: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 12Computer Science I - Martin Hardwick

Heat Flow (2)

int i,j; // loop variablesfloat temp; // temp at edge of platefloat maxchg; // max temp change during iterationfloat tolerance; // tolerance for stable tempsfloat prev; // previous temp at nodeint size; // size of plate in nodesint numits; // number of iterationsfloat maxtemp; // maximum tempfloat mintemp; // minimum tempfloat temprange; // temp range size for coloringfloat sqrsize; // size of square in pixelsint x,y; // location of square in pixelsint tempcat; // temperature color categoryCanvas display(400, 400, 0, 0); // canvas for display of tempscolor c; // color for a squareofstream reportfile; // file for final report

Page 13: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 13Computer Science I - Martin Hardwick

Heat Flow (3)

// Get size of platecout << "Enter size of plate in nodes: ";cin >> size;

// Get temperatures at edges of platecout << "Enter temperature at top: ";cin >> temp;for (i=0; i<size; i=i+1) {

plate[0][i] = temp;}cout << "Enter temperature at bottom: ";cin >> temp;for (i=0; i<size; i=i+1) {

plate[size-1][i] = temp;}cout << "Enter temperature at left side: ";cin >> temp;for (i=0; i<size; i=i+1) {

plate[i][0] = temp;}

A temperature at the edge of the plate applies uniformly to the entire edge of the plate.

all nodes along the edge must be set to this temperature

Each for loop iterates over the nodes along one of the edges.

one of the arrays subscripts is constant throughout the loop

Page 14: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 14Computer Science I - Martin Hardwick

Heat Flow (4)

cout << "Enter temp at right side: ";cin >> temp;for (i=0; i<size; i=i+1) {

plate[i][size-1] = temp;}

// Initialize rest of plate to zerofor (i=1; i<size-1; i=i+1) {

for (j=1; j<size-1; j=j+1) {plate[i][j] = 0.0;

}}

// Get tolerance for stable tempscout << "Get tolerance for "

<< "stable temps: ";cin >> tolerance;

The nodes along the edges remain fixed at the input temperatures.

The remaining interior nodes must be initialized to 0.

The program will iterate, computing new temperatures for the nodes until the temperatures at the nodes stabilize.

they change by less than a user-specified tolerance from one iteration until the next

Page 15: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 15Computer Science I - Martin Hardwick

Heat Flow (5)

// Iterate until temperatures stabilizemaxchg = tolerance + 1;numits = 0;while (maxchg > tolerance) {

// Recompute temps at all nodes// Find largest temp changemaxchg = 0;for (i=1; i<size-1; i=i+1) { for (j=1; j<size-1; j=j+1) {

prev = plate[i][j];

plate[i][j] = (plate[i-1][j] + plate[i][j+1] +plate[i+1][j] + plate[i][j-1])/4;

if (fabs(prev-plate[i][j])>maxchg) { maxchg = fabs(prev-plate[i][j]); }

} } numits = numits + 1;}

The for loops compute the new temperature at each interior node.

The if statement saves the largest change in temperature across all the nodes during one iteration.

The while loop continues the iteration until the maximum temperature change is less than the user-specified tolerance.

Page 16: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 16Computer Science I - Martin Hardwick

Heat Flow (6)

// Generate report with resultsreportfile.open("report.txt");reportfile << setprecision(1)

<< setiosflags(ios::fixed);reportfile << "Stable Temps Are:"

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

for (j=0; j<size; j=j+1) { reportfile <<setw(6)<< plate[i][j];}reportfile << endl;

}reportfile << endl << endl;reportfile << "Number of iterations: "

<< numits << endl;

Save the final temperature at each node in a report file.

Format the report file so that the temperatures appear as a table in the same shape as the grid of nodes.

this is done with the setw(), setprecision() and setiosflags() function calls

note that the endl is outside the inner loop but inside the outer loop as in our earlier example

The report file also includes the number of iterations that were necessary for the temperatures to stabilize.

Page 17: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 17Computer Science I - Martin Hardwick

Heat Flow (7)

// Find min and max temperaturesmaxtemp = plate[0][0];mintemp = maxtemp;for (i=0; i<size; i=i+1) {

for (j=0; j<size; j=j+1) { if (plate[i][j] > maxtemp) { maxtemp = plate[i][j]; } if (plate[i][j] < mintemp) {

mintemp = plate[i][j]; }}

}temprange = (maxtemp - mintemp)/8;

// Size of plot squaresqrsize = 400/size;

We want to draw a picture of the plate using different colors to show the different temperatures.

We need to determine the appropriate temperature scale.

find the min and max final temperature

divide the range by 8 since we will use eight colors

We will represent each node as a square of color.

the picture will be 400 pixels big, so divide 400 by the number of nodes along an edge to compute the square size

Page 18: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 18Computer Science I - Martin Hardwick

Heat Flow (8)

// Draw colored square for each nodey = 0;for (i=0; i<size; i=i+1) {

x = 0;for (j=0; j<size; j=j+1) {

// Determine color of square tempcat = (plate[i][j] – mintemp)

/temprange; switch (tempcat) {

case 0: c = BLACK;break;

case 1: c = PURPLE;break;

case 2: c = DARKBLUE;break;

case 3: c = BLUE;break;

case 4: c = CYAN;break;

Nested for loops are used to draw a colored rectangle for each node.

The color of a node is determined by deciding which temperature range the node falls into.

A switch statement then selects the appropriate color for that temperature range.

Page 19: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 19Computer Science I - Martin Hardwick

Heat Flow (9)

case 5: c = GREEN;break;

case 6: c = YELLOW;break;

case 7: c = RED;break;

case 8: c = WHITE; }

// Draw the colored square display.SetColor(c); display.DrawRectangle(

Point(x,y), Point(x+sqrsize,y+sqrsize)); x = x + sqrsize;}

y = y + sqrsize;}

display.runUntilEscape();return 0;

}

The SetColor operator for the Canvas object is used to set the appropriate color for the next node.

The DrawRectangle operator for the Canvas object is used to draw the colored square for a node.

The loops end by incrementing x and y to the coordinates of the square for the next node.

Page 20: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 20Computer Science I - Martin Hardwick

Running the Program

100 degrees

100 degrees

10 d

egre

es 10 degrees

20 nodes per edge

Temperature change tolerance is 0.001

Page 21: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 21Computer Science I - Martin Hardwick

Report File Contents

The Stable Temperatures Are: 10.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 ... 10.0 55.0 72.8 81.1 85.6 88.3 90.0 91.1 91.8 92.1 92.1 91.8 91.1 ... 10.0 37.2 55.0 66.0 73.0 77.6 80.6 82.6 83.9 84.4 84.4 83.9 82.6 ... 10.0 28.9 44.0 55.0 62.9 68.4 72.3 74.9 76.6 77.4 77.4 76.6 74.9 ... 10.0 24.4 37.0 47.1 55.0 60.9 65.2 68.3 70.2 71.1 71.1 70.2 68.3 ... 10.0 21.7 32.4 41.6 49.1 55.0 59.5 62.7 64.8 65.8 65.8 64.8 62.7 ... 10.0 20.0 29.3 37.7 44.7 50.5 55.0 58.3 60.4 61.5 61.5 60.4 58.3 ... 10.0 18.9 27.3 35.0 41.7 47.3 51.7 55.0 57.1 58.2 58.2 57.1 55.0 ... 10.0 18.2 26.1 33.4 39.8 45.2 49.5 52.8 55.0 56.0 56.0 55.0 52.8 ... 10.0 17.9 25.5 32.6 38.8 44.2 48.5 51.7 53.9 55.0 55.0 53.9 51.7 ... 10.0 17.9 25.5 32.6 38.8 44.2 48.5 51.7 53.9 55.0 55.0 53.9 51.7 ... 10.0 18.2 26.1 33.4 39.8 45.2 49.5 52.8 55.0 56.1 56.1 55.0 52.8 ... 10.0 18.9 27.3 35.0 41.7 47.3 51.7 55.0 57.1 58.2 58.2 57.1 55.0 ... 10.0 20.0 29.3 37.7 44.7 50.5 55.0 58.3 60.4 61.5 61.5 60.4 58.3 ... 10.0 21.7 32.4 41.6 49.1 55.0 59.5 62.7 64.8 65.8 65.8 64.8 62.7 ... 10.0 24.4 37.0 47.1 55.0 60.9 65.2 68.3 70.2 71.1 71.1 70.2 68.3 ... 10.0 28.9 44.0 55.0 62.9 68.4 72.3 75.0 76.6 77.4 77.4 76.6 75.0 ... 10.0 37.2 55.0 66.0 73.0 77.6 80.6 82.6 83.9 84.4 84.4 83.9 82.6 ... 10.0 55.0 72.8 81.1 85.6 88.3 90.0 91.1 91.8 92.1 92.1 91.8 91.1 ... 10.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 ...

Number of iterations: 286

Page 22: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 22Computer Science I - Martin Hardwick

Picture Of The Final Temperatures

Page 23: Lecture 1 -- 1Computer Science I - Martin Hardwick Function Prototypes rSometimes we want to use a function before it is defined. rIf so we define a function.

Lecture 1 -- 23Computer Science I - Martin Hardwick

Final Temperatures (Grid Size 100 x 100)