+ All Categories
Home > Documents > COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

Date post: 12-Jan-2016
Category:
Upload: charity-grant
View: 219 times
Download: 2 times
Share this document with a friend
90
COMP103 - C++ Review 1 Variables and Special Chars (Ch. 2, 3)
Transcript
Page 1: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 1

Variablesand

Special Chars(Ch. 2, 3)

Page 2: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 2

Valid Variable NamesRules for variable names in C++ (page 33) The first character must be an alphabetic

character or underscore Consists only of alpha-numeric and underscore

characters Cannot duplicate a reserved word (see Appendix

B)

Valid Namesa PIstudent_name _PI_assign1

Invalid Names$a for2name a aint

Page 3: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 3

Important Special Characters

Return \n

Null

Single Quote

Double Quote

Backslash

As a Character In a String

‘\n’

‘\0’

‘\’’

‘\”’

‘\\’

“\n”

“”

“’”

“\””

“\\”

Page 4: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 4

Constant declarations

Constants are used to store values that never change during the program execution.

Using constants makes programs more readable and maintainable.

Syntax: const <type> <identifier> = <expression>;

Examples: const double US2HK = 7.8;

//Exchange rate of US$ to HK$ const double HK2TW = 3.98;

//Exchange rate of HK$ to TW$ const double US2TW = US2HK * HK2TW;

//Exchange rate of US$ to TW$

Page 5: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 5

Variables are used to store values that can be changed during the program execution.

A variable is best thought of as a container for a particular type of data/value.

You must specify the variables type when you declare it

Syntax: < type > < identifier >;

< type > < identifier > = < expression >;

Examples: int sum;int i = j = 0;int total = 3445;char answer = 'y';double temperature = -3.14;

Variable declarations

Page 6: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 6

Variables are not automatically initialized. For example, after declaration

int sum;

the value of the variable sum can be anything (garbage).

Thus, it is good practice to initialize variables when they are declared.

A variable has a type and it can contain only values of that type. For example, a variable of the type int can only hold integer values.

Once a value has been placed in a variable it stays there until the program deliberately alters it.

Variable declarations

Page 7: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 7

Character data

A variable or a constant of char type can hold an ASCII character (see Appendix A of the textbook).

When initializing a constant or a variable of char type, or when changing the value of a variable of char type, the value is enclosed in single quotation marks.

Examples: const char star = '*';

char letter, one = '1';

Page 8: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 8

Decisions(Ch. 5)

Page 9: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 9

The Basic if Statement

Syntaxif(Expression)

Action If the Expression is true

then execute Action Action is either a single

statement or a group of statements within braces

Expression

Action

true false

Page 10: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 10

Choice (if) Example: find the absolute

valueif (value < 0)

value = -value; Can put multiple action

statements within bracesif <it's raining> {

<take umbrella><wear raincoat>

}

Page 11: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 11

Sorting Two Numbers

int value1;int value2;int temp;cout << "Enter two integers: ";cin >> value1 >> value2;if(value1 > value2){temp = value1;value1 = value2;value2 = temp;

}cout << "The input in sorted order: " << value1 << " " << value2 << endl;

Page 12: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 12

Relational Operators

Relational operators are used to compare two valuesMath C++ Plain English= == equals [example: if(a==b) ]

BUT (a=b) means put the value of b into a< < less than <= less than or equal to> > greater than >= greater than or equal to != not equal to

Page 13: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 13

A Boolean Type C++ contains a type named bool

which can have one of two values true (corresponds to non-zero value) false (corresponds to zero value)

Boolean operators can be used to form more complex conditional expressions The AND operator is && The OR operator is || The NOT operator is !

Warning & and | are bitmap operators

Page 14: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 14

More Operator Precedence Precedence of operators (from highest

to lowest) Parentheses ( … ) Unary operators ! Multiplicative operators * / % Additive operators + - Relational ordering < <= >= > Relational equality == != Logical and && Logical or || Assignment =

Page 15: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 15

Examples of bool

Assignments to bool type variablesbool P = true;bool Q = false;bool R = true;bool S = P && Q; // Fbool T = !Q || R; // T bool U = !(R && !Q); // F

Page 16: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 16

Operator Precedence: Examples

Examples

5 != 6 || 7 <= 3

is equivalent to

(5 !=6) || (7 <= 3)

5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24

is TRUE

Page 17: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 17

The if-else Statement

Syntaxif (Expression)

Action1

else

Action2

If Expression is true

then execute Action1

otherwise execute Action2

Expression

Action1 Action2

true false

Page 18: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 18

The if-else Statement

if <it's sunny>{<go to beach with sun block>

} else{

<take umbrella>}

Page 19: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 19

Finding the Big One

int value1;

int value2;

int larger;

cout << "Enter two integers: ";

cin >> value1 >> value2;

if (value1 > value2)

larger = value1;

else

larger = value2;

cout << "Larger is: " << larger << endl;

Page 20: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 20

if-else-if StatementsF

F

F

F

T

T

T

T

Page 21: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 21

if-else-if Statementsif <Mon, Wed>{

<goto COMP 103>

}

else if <Tue>{

<goto Lab>

}

else if <12noon or 7PM>{

<eat>

}

else{

<sleep>

}

Page 22: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 22

if-else-if Statement

if(score >= 90)

cout << "Grade = A" << endl;

else if(score >= 80)

cout << "Grade = B" << endl;

else if(score >= 70)

cout << "Grade = C" << endl;

else if(score >= 60)

cout << "Grade = D" << endl;

else

cout << "Grade = F" << endl;

Page 23: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 23

switch StatementEquivalent to the previous if-else-ifswitch(score/10){case 10:case 9: cout << "Grade = A" << endl;

break;case 8: cout << "Grade = B" << endl;

break;case 7: cout << "Grade = C" << endl;

break;case 6: cout << "Grade = D" << endl;

break;default: cout << "Grade = F" << endl;

}

Page 24: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 24

Nested if StatementsNested means that one complete

statement is inside another

if <it's Monday>{

if <it's 1:00pm>{

if <it's raining>{

<bring umbrella>

}

<go to COMP 103>

}

<call your friends>

}

Page 25: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 25

“ Dangling Else” Problem

What is the value of c after the following is executed? int a=-1, b=1, c=1;

if(a>0)

if(b>0)

c = 2;

else

c = 3;

C++ groups a dangling else with the most recent if (answer: c=1).

Page 26: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 26

Functions(Ch. 4)

Page 27: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 27

Advantages of Functions

A complex problem is often easier to solve by dividing it into several smaller parts, each of which can be solved by itself.

These parts are called functions in C++ Functions make programs easier to

understand. Functions make programs easier to modify. Functions can be called several times in

the same program, allowing the code to be reused.

Page 28: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 28

Function Input and Output

Function ResultParameters

Page 29: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 29

Functions in a Program

C++ programs usually have the following form:

// include statements // function prototypes // main() function // user-defined functions

Page 30: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 30

Function Prototype

The function prototype declares the interface, or input and output parameters of the function, leaving the implementation for the function definition.

The function prototype has the following syntax: <type> <function name>(<type list>);

Example: A function that prints the card (J) given the card number (11) as input:

void printcard(int num);(This is a void function - a function that does not return a

value)

Page 31: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 31

Function Definition

The function definition can be placed anywhere in the program after the function prototypes.

You can place a function definition in front of main(). In this case there is no need to provide a function prototype for the function, since the function is already defined before its use.

A function definition has following syntax: <type> <function name>(<parameter list>){

<local declarations> <sequence of statements>

}

Page 32: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 32

Function Call

A function call has the following syntax:

<function name>(<parameter list>)

There is a one-to-one correspondence between the parameters in a function call and the parameters in the function definition.

Page 33: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 33

Printing Cards (void function)

The main() program which calls printcard()

#include <iostream>using namespace std;void printcard(int); // function prototypeint main(){

int c1, c2, c3, c4, c5;// pick cards. . . // print cardsprintcard(c1);printcard(c2);printcard(c3);printcard(c4);printcard(c5);// find score// print score

}

Page 34: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 34

Printing CardsA function that prints the card (J) given the

card number (11) as input:

void printcard(int cardnum){ if(cardnum==1)

cout << "A"; else if(cardnum>=2 && cardnum<=10)

cout << cardnum; else if(cardnum==11)

cout << "J"; else if(cardnum==12)

cout << "Q"; else if(cardnum==13)

cout << "K";}

Page 35: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 35

Absolute Value (returns int)

#include <iostream> int absolute(int x); // function prototype int main(){

int x, y, diff; cout << "Enter two integers: "; cin >> x >> y; diff = absolute(x - y); cout << "The absolute diff is " << diff << endl;

return 0;} // Define a function to take absolute value of an int int absolute(int x){

if (x >= 0) return x; else return -x; }

Page 36: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 36

Passing Parameters by Value

A function returns a single result (assuming the function is not a void function)

One of the statements in the function body should have the form:

return <expression>; The value passed back by return should have the

same type as the function.

Page 37: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 37

Pass by Value

Changes to the parameters inside the function body have no effect outside of the function.

• Different location in memory

Page 38: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 38

Pass by Value: Example 1

For example, consider the following code: int sum(int a, int b){

a = a + b; return a; } void main(){ int x, y, z; x = 3; y = 5; z = sum(x,y); }

What is the value of x, y, and z at the end of the main() program?

Page 39: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 39

Pass by Value: Example 1

The answer: 3, 5, and 8. (x,y,z)

Even though the value of parameter a is changed, the corresponding value in variable x does not change.

This is why this is called pass by value.

The value of the original variable is copied to the parameter, but changes to the value of the parameter do not affect the original variable.

In fact, all information in local variables declared within the function will be lost when the function terminates.

The only information saved from a pass by value function is in the return statement.

Page 40: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 40

Pass by Value: Example 2

void Increment(int Number) { Number = Number + 1;

cout << "Number =" << Number << endl;}

void main() { int I = 10;

cout << "I is: " << I << endl;Increment(I);

cout << "I is: " << I << endl;}

Page 41: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 41

Passing Parameters by Reference

To have a function with multiple outputs, we have to use pass by reference.

Reference (address) of parameter is passed to the function, instead of its value.

If the function changes the parameter value, the changes will be reflected in the program calling it.

How to pass parameters by reference:<type>& <variable>, ... , <type>& <variable>

Page 42: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 42

Pass by Reference: Example

The correct implementation of the Increment function #include <iostream>

using namespace std;

void Increment(int& Number){

Number = Number + 1;

cout << "Number: " << Number << endl; // 11 }

void main(){ int I = 10;

Increment(I);

cout << "I is: " << I << endl; // 11

} Pass-by-Reference-1.cpp

Page 43: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 43

Example: Exchange two numbers

If we use pass by value, it will not work!!!

• a and num1 are in the same location in memory

• Also b and num2

Page 44: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 44

Pass by value and by reference

Page 45: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 45

Loops(Ch. 6)

Page 46: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 46

Iterative Constructs

Provide Ability to control how many times a

statement list is executed Three constructs

while statement for statement do-while statement

Page 47: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 47

The while Statement Syntax

while (Expression)

Action How it works:

If Expression is true then execute Action

Repeat this process until Expression evaluates to false

Action is either a single statement or a group of statements within braces

Expression

Action

true false

Page 48: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 48

Example: N! (while)

int number, factorial, n;cout << "Enter number: ";cin >> number;factorial = 1;n = 1;while(n <= number){factorial *= n;

n++;}cout << "The factorial of " << number << " is " << factorial << endl;

Page 49: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 49

The for StatementSyntax

for (ForInit; ForExpression; PostExpression)

Action

How it works: Execute “ForInit” statement As long as “ForExpression”

is true Execute Action Execute PostExpression

ForExpression

Action

true false

ForInit

PostExpression

Page 50: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 50

Example: N! (for)

int number, factorial, n;

cout << "Enter number: ";

cin >> number;

factorial = 1;

for (n=1; n<=number; n++)

factorial *= n;

cout << "The factorial of " << number

<< " is " << factorial << endl;

Page 51: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 51

The Do-While Statement

Syntaxdo Action

while (Expression)

How it works: Execute Action if “Expression” is true then

execute Action again Repeat this process until

Expression evaluates to false

Action is either a single statement or a group of statements within braces

Action

true

false

Expression

Page 52: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 52

Example: N! (do-while)

int number, factorial, n;cout << "Enter number: ";cin >> number;factorial = 1;n = 1;do{factorial *= n;

n++;}while(n <= number);cout << "The factorial of " << number << " is " << factorial << endl;

Page 53: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 53

Which Loop to Use?

For loop Usually best for sums, products, and counting

loops.While loop You want to repeat an action without knowing

exactly how many times it will be repeated. There are situations when the action should

not be executed. Do-while loop The action should always be executed at least

once. Otherwise, the do-while loops and while loops

are used in similar situations.

Page 54: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 54

How to Stop a Loop

Known number of iterations before the loop stops (for)

Test for a user-controlled condition before or after each iteration (while, do-while)

Use the break command.

Page 55: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 55

Stop a loop: break

The break command is the same as the one used previously in switch.

break leaves the current loop immediately. It is recommended that break be used for situations where the loop needs to be terminated immediately (e.g., due to user intervention or if a fatal error occurs).

Use with care !!

Page 56: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 56

Example: Maximum (while with break)

int value; //input valueint max=0; //maximum valuewhile(true){

cout << "Enter a value (-1 to stop): ";

cin >> value;if(value > max)

max = value;if(value==-1)

break;}cout << "The maximum value found is "

<< " is " << max << endl;

Page 57: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 57

Common Loop Errorswhile(balance != 0.0);{

balance = balance - amount;} This will lead to an infinite loop!

for(n=1; n<=count; n++);{

cout << "hello" << endl;} "hello" only printed once!

while(balance != 0.0){balance = balance - amount;

} balance may not become equal zero due to

numerical inaccuracies

Page 58: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 58

Nested Loops

// Program to output the // multiplication tableint i; //Outer loop counter

int j; //Inner loop counter

for(i=1; i<=10; i++){for(j=1; j<=10; j++)

cout << i*j << " ";cout << endl;

}

Output1 2 3 4 5 6 7 8 9 102 4 6 8 10 12 14 16 18

203 6 9 12 15 18 21 24 27

30…

Nested loops are loops within loops.

Page 59: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 59

Recursion(Ch.6, Section 6-9)

Page 60: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 60

Recursion Recursion is one way to decompose a task into

smaller subtasks. The smallest example of the same task has a

non-recursive solution.

Example: The factorial functionn! = n * (n-1) * (n-2) * ... * 1orn! = n * (n-1)! and 1! = 1

A recursive solution may be simpler to write (once you get used to the idea) than a non-recursive solution.

But a recursive solution may not be as efficient as a non-recursive solution of the same problem.

Page 61: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 61

Recursion General Form

How to write recursively?

int rec(parameters){

if(stopping condition)

return stopping value;

value = rec(revised parameters);

return value;

}

Page 62: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 62

Example: N! Recursion

int fac(int n){int product;if(n <= 1)

return 1;product = n * fac(n-1);return product;

}

void main(){int number = 3;

cout << fac(number) << endl;}

Page 63: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 63

Execution trace fac(3) :

3 <= 1 ? No.

product3 = 3 * fac(2)fac(2) :

2 <= 1 ? No.

product2 = 2 * fac(1)fac(1) :

1 <= 1 ? Yes.return 1

product2 = 2 * 1 = 2

return product2

product3 = 3 * 2 = 6

return product3

fac(3) has the value 6

Page 64: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 64

Arrays

Programming

Page 65: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 65

Arrays An array is a collection of data elements that are of

the same type (e.g., a collection of integers, collection of characters, collection of doubles).

Page 66: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 66

Arrays 1-dimensional array.

3-dimensional array (3rd dimension is the day).

Oct 15

Oct 16

Oct 14

Page 67: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 67

Array Declaration – 1 Dimension

Syntax: <type> <arrayName>[<dimension>]

Page 68: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 68

Subscripting – 1 Dimension

// array of 10 uninitialized ints

int A[10];

A[3] = 1;

int x = A[3];

-- -- 1--A -- -- ---- -- --

4 5 6 3 0 2 8 9 7 1

A[4] A[5] A[6]A[3]A[0] A[2] A[8]A[9]A[7]A[1]

1

-- -- --

--

--

Page 69: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 69

Array Initialization – 1 Dimension

Page 70: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 70

Example Definitions – 1 Dimension

Supposeconst int N = 20;const int M = 40;const int MaxStringSize = 80;const int MaxListSize = 1000;

Then the following are all legal array definitions.int A[10]; // array of 10 intschar B[MaxStringSize]; // array of 80 charsdouble C[M*N]; // array of 800 doublesint Values[MaxListSize];// array of 1000 ints

Page 71: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 71

const int N=10;int A[N];int SmallestValueSoFar, i;

... // A[] is input by user

SmallestValueSoFar = A[0];for (i=1; i<N; i++)

if (A[i] < SmallestValueSoFar)SmallestValueSoFar = A[i];

Example: Smallest Value (1-dimension)

Page 72: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 72

2-D Array Example

int table[5][4];

Page 73: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 73

Passing Arrays to Functions

(Ch.8, p.388-397)

Programming

Page 74: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 74

Passing Array Elements

Individual elements can be passed to a function like ordinary values.

Page 75: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 75

Passing Arrays as Parameters

Arrays can be passed to functions in their entirety.

All that is required is the address of the first element and dimensions of the array.

The remainder of the array will be passed by reference automatically.

Using “[ ]” in the formal parameter specification indicates that the variable is an array.

Page 76: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 76

Example: Multiple an array by 2

Page 77: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 77

The const type modifier

If the function must not change any element of the array then const should be used in the formal parameter specification of that array.

Page 78: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 78

Passing Multidimensional Arrays

How to pass a multidimensional array to a function:

void displayBoard(int b[][4]);// function prototype requires variable name for arrays

void main(){int board [4][4];...displayBoard(board);...

}void displayBoard(int b[][4]){ // could also be: void displayBoard(int b[4][4]){// but NOT: void displayBoard(int b[][]){

...}

When passing a multidimensional array, only the size of the 1st dimension is optional, the 2nd, 3rd, etc. dimensions must be specified.

Page 79: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 79

Programming

Structures(Ch.11, p.567)

Page 80: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 80

Structures A structure is a collection of related data items,

possibly of different types. In C++, structure is a user defined type, called struct. A struct is heterogeneous (of different types of data)

whereas an array is homogeneous (of same type of data)

Examples: Student record

student id, name, major, gender, start year, … Bank account:

account number, name, currency, balance, … Address book:

name, address, telephone number, … In database applications, structures are called

records.

Page 81: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 81

struct basics

Definition of a structure:struct <struct-type>{

<type> <identifier_list>;<type> <identifier_list>;...

} ;

Example:struct Date {

int day;int month;int year;

} ;

The “Date” structure

has 3 members,

day, month & year.

Each identifierdefines a memberof the structure.

Page 82: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 82

struct examples

Example:struct BankAccount{

char Name[15];int AcountNo[10];double balance;Date Birthday;

};

Example:struct StudentRecord{

char Name[15];int Id;char Dept[5];char Gender;

};

The “StudentRecord” structure has 4

members.

The “BankAcount” structure has simple, array and structure

types as members.

Page 83: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 83

struct basics

Declaration of a variable of struct type:

<struct-type> <identifier_list>;

Example:StudentRecord Student1, Student2;

Student1 and Student2 are variables of StudentRecord type.

Student1 Student2Name

Id Gender

Dept

Name

Id Gender

Dept

Page 84: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 84

Chan Tai Man

12345 M

COMP

Example 1: struct basics

The members of a struct type variable are accessed with the dot (.) operator:

<struct-variable>.<member_name>;

Example:strcpy(Student1.Name, "Chan Tai Man");Student1.Id = 12345;strcpy(Student1.Dept, "COMP");Student1.gender = 'M';cout << "The student is ";switch (Student1.gender){

case 'F': cout << "Ms. "; break;case 'M': cout << "Mr. "; break;

}cout << Student1.Name << endl;

Student1

Name

Id Gender

Dept

Page 85: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 85

Chan Tai Man

12345 M

COMP

Example 2: struct-to-struct assignment

The value of one struct type variable can be assigned to another variable of the same struct type.

Example:strcpy(Student1.Name,

"Chan Tai Man");Student1.Id = 12345;strcpy(Student1.Dept, "COMP");Student1.gender = 'M';

Student2 = Student1;

Student1

Chan Tai Man

12345 M

COMPStudent2

Page 86: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 86

Example 3: Nested structures

We can nest structures inside structures.

Examples:struct point{

double x, y;};point P;

struct line{point p1, p2;

};line L;

struct triangle{ point p1, p2, p3;

};triangle T;

(P.x, P.y)

(L.p1.x, L.p1.y)

(L.p2.x, L.p2.y)

(T.p2.x, T.p2.y)

(T.p1.x, T.p1.y)

(T.p3.x, T.p3.y)

Page 87: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 87

Example 4: Nested structures

We can nest structures inside structures.

struct line{point p1, p2;

};line L; (L.p1.x, L.p1.y)

(L.p2.x, L.p2.y)

line

p1 p2

x y x y

Page 88: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 88

Arrays of structures

An ordinary array: One type of data

An array of structs: Multiple types of data in each array element.

0 1 2 … 98 99

0 1 2 … 98 99

Page 89: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 89

Arrays of structures Example:

StudentRecord Class[100];strcpy(Class[98].Name, "Chan Tai Man");Class[98].Id = 12345;strcpy(Class[98].Dept, "COMP");Class[98].gender = 'M';Class[0] = Class[98];

. . .

0 1 2 … 98 99

Chan Tai Man

12345 M

COMP

Page 90: COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)

COMP103 - C++ Review 90

Arrays inside structures

We can use arrays inside structures. Example:struct square{

point vertex[4];};square Sq;

Assign values to Sq using the given square

(4, 3) (10, 3)

(4, 1) (10, 1)

x y x y x y x y


Recommended