Computer Programming- Lecture 9

Post on 29-Apr-2015

5.514 views 1 download

description

Arrays and Functions

Transcript of Computer Programming- Lecture 9

1TCP1231 Computer Programming I

Lecture 9Arrays and Functions

2TCP1231 Computer Programming I

Objectives

• To Learn about arrays• Explore how to declare and manipulate data

into arrays• Understand the meaning of “array index out of

bounds”• Become familiar with the restrictions on array

processing

3TCP1231 Computer Programming I

Two kinds of Multidimensional Arrays

There are two basic ways of implementing 2-dimensional arrays:

true two-dimensional arrays, and arrays of arrays.

Some languages use one method, some another, and some both.

C++ allows both methods, and each has its advantages and disadvantages.

4TCP1231 Computer Programming I

Two kinds of Multidimensional Arrays

1. True arrays• In this case the rows are laid out sequentially in memory. • This provides simplicity in memory management and a slight

speed advantage. • This is the kind of array C/C++ creates by default.

1. Arrays of arrays• In this style each element of a one-dimensional array is a

pointer to another array. • It's a common way to create an array of C-strings. • The disadvantage is that memory management can be a little

more complex and there is a slight performance overhead.

5TCP1231 Computer Programming I

Multidimensional Array Declaration

Syntax

Type Array_Name[Size_Dim_1][Size_Dim_2] . . . [Size_Dim_Last];

Examples

char page[30][100];int matrix[2][3];double three_d_picture[10][20][30];

An array declaration, of the form shown, defines one indexed variable for each combination of array indexes. For instance, the second of the sample declarations defines the following six indexed variables for the array matrix:

matrix[0][0], matrix[0][1], matrix[0][2], matrix[1][0], matrix[1][1], matrix[0][2]

6TCP1231 Computer Programming I

Multidimensional Array Parameters

When a multidimensional array parameter is given in a function heading or function declaration, the size of the first dimension is not given, but the remaining dimension sizes must be given in square brackets. Since the first dimension size is not given, we usually need an additional parameter of type int that gives the size of this first dimension. Below is an example of a function declaration with a two-dimensional array parameter p:

void get_page(char p[][100], int size_dimension_1);

7TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main (){ int col, row; for (row=0; row <=2; row++) { for (col=0; col <=2; col++) cout << "a[" <<row << "," << col << "] "; cout << endl; } system(“pause”); return 0;}

a[0,0] a[0,1] a[0,2]a[1,0] a[1,1] a[1,2]a[2,0] a[2,1] a[2,2]

8TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main (){ int col, row; int a[3][3]; for (row=0; row <=2; row++) for (col=0; col <=2; col++) { cout << "a[" <<row << "," << col << "]= "; cin >> a[row][col]; } for (row=0; row <=2; row++) { for (col=0; col <=2; col++) cout << a[row][col] << '\t'; cout << endl; }}

Read an array of 3x3 then print its elements

a[0,0]= 5a[0,1]= -6a[0,2]= 1a[1,0]= 7a[1,1]= 88a[1,2]= 2a[2,0]= 0a[2,1]= 5a[2,2]= 9

input

5 -6 17 88 20 5 9

output

9TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main (){ int col, row, max; int a[3][3]; for (row=0; row <=2; row++) for (col=0; col <=2; col++) { cout << "a[" <<row << "," << col << "]= "; cin >> a[row][col]; } max=a[0][0]; for (row=0; row <=2; row++) for (col=0; col <=2; col++) if (max< a[row][col]) max=a[row][col]; cout << "\nMax= " << max; }

Read an array of 3x3 then print Max. No.

a[0,0]= 5a[0,1]= -6a[0,2]= 1a[1,0]= 7a[1,1]= 88a[1,2]= 2a[2,0]= 0a[2,1]= 5a[2,2]= 9

input

Max= 88output

10TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main (){ int col, row, i, j, c=0; int a[3][3], b[9]; for (row=0; row <=2; row++) for (col=0; col <=2; col++) { cout << "a[" <<row << "," << col << "]= "; cin >> a[row][col]; } for (int i=0; i<3; i++) for (int j=0; j<3; j++) { b[c]=a[i][j]; c++; }

for (int i=0 ;i<9; i++) cout << b[i] << '\t'; }

Convert Tow-Dimensional Array a(3x3) to One Dimensional Array b(9)

a[0,0]= -5a[0,1]= 4a[0,2]= 97a[1,0]= -6a[1,1]= 5a[1,2]= -8a[2,0]= -1a[2,1]= 44a[2,2]= 2

input

output

-5 4 97 -6 5 -8 -1 44 2

11TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main () { int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}}; int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ; int i, j, c[4][3];

for (i=0; i<4; i++) for ( j=0; j<3; j++) c[i][j]= a[i][j] + b[i][j];

for (i=0; i<4; i++) { for ( j=0; j<3; j++) cout << c[i][j] << '\t'; cout << endl; } system(“pause”); return 0;}

C(4x3) equal A (4x3) + B (4x3)

23 5 21-3 27 3372 -1 17 -2 26

12TCP1231 Computer Programming I

#include <iostream>using namespace std;

int main () { int a[4][3]= {{12, 4, 9}, { -5, 3, 1}, { 9, 2, -2}, {3, 2, 22}}; int b[4][3]= {{11, 1, 12},{ 2, 24, 32}, {63, -3, 3}, {4, -4, 4}} ; int i, j, c[4][3]; for (i=0; i<4; i++) for ( j=0; j<3; j++) c[i][j]= a[i][j] + b[i][j];

cout << "\n***** A ******\n"; for (i=0; i<4; i++) { for ( j=0; j<3; j++) cout << a[i][j] << '\t'; cout << endl; }

C(4x3) equal A (4x3) + B (4x3)

cout << "\n***** B ******\n"; for (i=0; i<4; i++) { for ( j=0; j<3; j++) cout << b[i][j] << '\t'; cout << endl; } cout << "\n******C ******\n"; for (i=0; i<4; i++) { for ( j=0; j<3; j++) cout << c[i][j] << '\t'; cout << endl; }}

**** A *****12 4 9-5 3 19 2 -23 2 22

***** B *****11 1 122 24 3263 -3 34 -4 4

***** C *****23 5 21-3 27 3372 -1 17 -2 26

13TCP1231 Computer Programming I

Functions

What is a function?• A program can be thought of as consisting

subparts, such as obtaining the input data, calculating the output data and displaying the output data.

• C++, like most programming languages, has facilities to name and code each of these subparts separately.

• In C++ these subparts are called functions.

14TCP1231 Computer Programming I

Predefined Functions

15TCP1231 Computer Programming I

//Computes the size of a dog house that can be purchased given the//user’s budget#include <iostream>#include <cmath>using namespace std;

int main(){

const double COST_PER_SQ_FT = 10.50;double budget, are, length_side;

cout << "Enter rhe amount budgeted for your dog house $";cin >> budget;

area = budget/COST_PER_SQ_FT;length_side = sqrt(area);

cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);cout << "For a price of $" << budget << endl << "I can build for you a luxurious square dog house\n" << "that is " << length_side << "feet on each side.\n";

return 0;

}

Enter the amount budgeted for your dog house: $ 25.00For a price of $ 25.00I can build you a luxurious square dog housethat is 1.54 feet on each side.

16TCP1231 Computer Programming I

• We can define our own functions, either in the same file as the main part of our program of in a separate file so that the functions can be used by several different programs.

Programmer-Defined Functions

17TCP1231 Computer Programming I

FunctionsThere are two components to define a function:

1. Function declaration (or function prototype)* Shows how the function is called* Must appear in the code before the function can be called* Normally placed before the main part of your program

2. Function definition (or function body)* Describes how the function does its task* Can appear before or after the function is called* Normally placed after the main part of your program or in a separate file.

18TCP1231 Computer Programming I

• Syntax:

data_type Function_Name(Parameter_List);

double total(int number, double price);// Compute total cost including 5% sales tax on// number_par items at cost of price_par each

function name formal parameters namedata type parameters type

parameter list

;

Function Declaration

19TCP1231 Computer Programming I

function header

double total(int number, double price) { double tax= 0.05; double subtotal;

subtotal= number * price_par - tax; return subtotal;}

functionbody

return statement

Function Definition

• Syntax:data_type Function_Name(Parameter_List);

20TCP1231 Computer Programming I

#include <iostream>using namespace std;

double total_cost(int number_par, double price_par);//Computes the total cost, including 5% sales tax, on number_par//items at a cost of price_par each.

int main(){

double price, bill;int number;

cout << "Enter the number of items purchased: ";cin >> number;cout << "Enter the price per item $";cin >> price;

bill = total_cost(number, price);

cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(2);cout << number << " items at " << "$" << price << " each.\n” << "Final bill, including tax, is $" << bill << endl;

return 0;}

double total_cost(int number_par, double price_par){

const double TAX_RATE = 0.05; //5% sales taxdouble subtotal;

subtotal = price_par * number_par;return (subtotal + subtotal*TAX_RATE);

}

Enter the number of items purchased: 2Enter the price per item: $10.102 items at $10.10 each.Final bill, including tax, is $21.21

function declaration

function call

function heading

function bodyfunction definition

21TCP1231 Computer Programming I

The Return Statement

• A return statement consists of the keyword return followed by an expression.

• When a return statement is executed, the function call ends

• Returns the value calculated by the function

• A void function is does not necessarily contain a return statement, however it may optionally have one or more return statement.

22TCP1231 Computer Programming I

The Return Statement

• Syntax return expression;

• expression performs the calculation or

• expression is a variable containing the calculated value

• Example return (subtotal + subtotal * tax);

or

return subtotal + subtotal * tax;

23TCP1231 Computer Programming I

Function Call

• A function call is an expression consisting of the function name followed by arguments enclosed in parentheses.

• If there is more than one argument, the arguments are separated by commas.

• A function call is an expression that can be used like any other expression of the type specified for the value returned by the function.

24TCP1231 Computer Programming I

The Function Call

bill = total(number, price);

arguments listfunction name

return value assigned to bill

Syntax

Function_Name(Argument_List);

where the Argument_list is a comma-separated list of arguments:

Argument_1, Argument_2, . . ., Argument_Last

Examples

25TCP1231 Computer Programming I

Void-Function

What is a void-function?

• Subtasks are implemented as functions in C++.

• In C++, a function must either return a single value or return no values at all.

• A function that returns no value is called a void function.

26TCP1231 Computer Programming I

Void-Function

void Function_Name(Parameter_List);

There are two main differences between void-function

definitions and the definitions of functions that return one value:

1. Keyword void replaces the data type of the function

2. No return statement

27TCP1231 Computer Programming I

Syntax for a void Function Declaration

void Function Declaration

void Function_Name(Parameter_List);Function_Declaration_Comment

void Function Definition

void Function_Name(Parameter_List){

Declaration_1Declaration_2. . .Declaration_LastExecutable_Statement_1Executable_Statement_2. . . Executable_Statement_Last

}

void print (int number, double price){ double tax= 0.05; double subtotal;

subtotal= number * price_par - tax; cout << subtotal;}

print (average, min, max);

arguments listfunction name

body

function header

28TCP1231 Computer Programming I

#include <iostream>using namespace std;

int sqr(int x) // to duplicate a number{ int y; y= x*x; return y;}int main (){ int a, b; a=3; b=sqr(a); cout << a << '\t' <<b; system(“pause”); return 0;}

Multiply a number by itself

3 9

29TCP1231 Computer Programming I

#include <iostream>using namespace std;

double XtothepowerN(int x, int n) // to find X to the power of n{ double p=1;

for (int i=1; i<= n; i++) p=p * x; return p;}int main (){ int b;

b=XtothepowerN(3,4); cout << "the result is " << b; return 0;}

x to the power of n

the result is 81

30TCP1231 Computer Programming I

A function is like a small program

• To understand functions, keep the following three points in mind:

– A function definition is like a small program and calling the function is the same thing as running this “small program”.

– A function uses formal parameters, rather than cin, for input. The arguments to the function are the input and they are plugged in for the formal parameters.

– A function does not normally send any output to the screen, but it does send a kind of “output” back to the program. The function returns a value, which is like the “output” for the function. The function uses a return statement instead of a cout statement for this “output”.

31TCP1231 Computer Programming I

THE END