Computer Programming - Welcom to COMP's Personal …csrluk/eng236/Ch3ar.pdf · 3. The Nuts and...

100
3. The Nuts and Bolts of C++ Computer Programming Computer Programming Computer Programming Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++

Transcript of Computer Programming - Welcom to COMP's Personal …csrluk/eng236/Ch3ar.pdf · 3. The Nuts and...

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

1

Learning the C++ language

3. The Nuts and Bolts of C++

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.1 Revisit HelloWorld

2

3.1 Revisit HelloWorld

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

int main(){

std::cout << "Hello World!" << std::endl;

PreprocessorPreprocessor

The actual programThe actual program

Preprocessor and Program Codes

3

<< std::endl;return 0;

}

programprogram

• Preprocessor:

• Instruct the compiler on how to compile the program

• Will NOT generate machine codes

• Start with a pound (#) symbol

• Actual program:

• Every C++ program must have the main()

function

• It is the beginning point of every C++ program

Read before compiling

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Preprocessor#include <iostream>

• When compiling a file, we need to obtain the definitions of some terms in the program codes

• These definitions are recorded in some header files

• These files are shipped with the compiler or other resources

4

• These files are shipped with the compiler or other resources

• #include tells the compiler where to find the header files

and insert this file to that location of the program

e.g. #include <iostream> tells the compiler it should get the file iostream through the default path

e.g. #include "myfile" tells the compiler it should get the file myfile in the current folder.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Program Codes• The basic element of a program is function

• A function is composed of:

1. Return Type1. Return Type 2. Function name2. Function name

Think from the point of view

of the compiler.

5

int main(){std::cout << "Hello World!"

<< std::endl;return 0;

}

3. Input parameters3. Input parameters

4. Program codes enclosed by the opening and closing braces

4. Program codes enclosed by the opening and closing braces

Note: The meaning of std::cout is checked in the file iostream in the preprocesor.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Call main()

• The main() function is the beginning point of a

program

• When executing a program, the operating system will firstcall the main() function of this program

• If the above main() function executes successfully, it

should return an integer 0 to the operating system

6

main()

Call main()

Return 0

It means everything fine on executing main() as it is

the last statement.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

int main(){

std::cout << "Hello World!"<< std::endl;

return 0;

Send the string Hello World! to std::cout ,

i.e. the standard output, defined in iostream

Send the string Hello World! to std::cout ,

i.e. the standard output, defined in iostream

Return an integer 0 to the Return an integer 0 to the

Program Codes

7

return 0;}

Return an integer 0 to the operating systemReturn an integer 0 to the operating system

• In console mode, the standard output is the console, i.e. the Command Prompt window

• In C++, character string is represented by a sequence of characters enclosed by " "

• std::endl means newline (or Enter), also defined iniostream

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• std::cout and std::endl means that we are referring to the cout and endl of the std namespace

• The std namespace is defined in iostream

• Namespace – A new feature of C++

Namespaces

Folders and files

concept in Windows

8

• Design to help programmers develop new software components without generating naming conflicts

• Naming conflict – A name in a program that may be used for different purposes by different people

• cout and endl are NOT a part of C++, people can use

these two names for any purpose; not necessarily referring to standard output and newline.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

namespace myns {int cout=0; //Integer variable

} //No semi-colon

int main()

We can have our own cout

by putting it in a namespace defined by ourselves

We can have our own cout

by putting it in a namespace defined by ourselves

This cout refers to

the standard output

This cout refers to

the standard output

This cout

refers to the number 0

This cout

refers to the number 0

9

int main(){

std::cout << myns::cout << std::endl;return 0;

}

• In fact, another definition of cout can be found in iostream

• The result of this program is a number 0 shown on the standard output.

the standard outputthe standard output

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

namespace myns {int cout=0;

}

That’s why using cout

without the associate

namespace is an errorsince the system does not know which cout you are

referring to

That’s why using cout

without the associate

namespace is an errorsince the system does not know which cout you are

referring to

10

int main(){

std::cout << cout << std::endl;return 0;

} �

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• It may be a bit cumbersome to write the namespace of names every time

• A short form is to use the using statement

#include <iostream> All names that are NOT a part of All names that are NOT a part of

11

#include <iostream>

using namespace std;

int main(){

cout << "Hello World!" << endl;return 0;

}

All names that are NOT a part of C++ will belong to the namespace std, unless

otherwise stated.

All names that are NOT a part of C++ will belong to the namespace std, unless

otherwise stated.

No need to put std in front of cout and endl.No need to put std in front of cout and endl.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int main(){

cout << "Hello there.\n";cout << "Here is 5: "<< 5 << "\n";cout << "endl writes a new line to the screen.";cout <<

endl;

We can also print integers, floating-point numbers or even combination of string and integers in standard output

We can also print integers, floating-point numbers or even combination of string and integers in standard output

\n - Another way to show newline\n - Another way to show newline

\t - Add a tab character\t - Add a tab characterAnother lineAnother line

escape sequence

12

endl;cout << "Here is a very big number:\t" << 70000 << endl;cout << "Here is the sum of 8 and 5:\t" << 8+5 << endl;cout << "Here's a fraction:\t\t" << (float) 5/8 << endl;cout << "And a very very big number:\t";cout << (double) 7000*7000 <<

endl; //casting integer to doublecout << "Replace Frank with your name...\n";cout << "Frank is a C++ programmer!\n";return 0;

}

\t - Add a tab character\t - Add a tab characterAnother lineAnother line

Ex. 3.1a

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Result

13

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Comments• A program needs to be well commented to explain the important points of the program

• Adding comments in the program will not affect the program execution but improve readability

14

readability

• Comments can be added in two ways:#include <iostream>using namespace std;int main(){/* Text between these two marks are comments*/

cout << "Hello World!\n";return 0; // Text after that are also comments

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.1a

a. Build the program in p.12. Note the output on the console.

b. Add one statement to the program which will show your name and age in a single sentence. The name should

p.12

15

name and age in a single sentence. The name should be shown as a character string. The age should be shown as an integer.

c. Use the comment symbols /* and */ to comment the

statements from line 4 to line 8 (inclusive). Is there any change to the results output?

Ex. 3.1b

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Although a single main() function is enough for any C++

program, it’s a bad habit to do everything by a single function

• C++ allows nesting of functions to facilitate "divide and

More on Functions

16

• C++ allows nesting of functions to facilitate "divide and conquer" of jobs

• The function main() can call other functions to help it

complete a task

• When a function is called, the program branches off from the normal program flow

• When the function returns, the program goes back to where it left before.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Mr A wants to decorate his house

Call his friend B to help mowing

Call his

1

2

17

Return him the mowed lawn

Call his friend C to help painting

Return him the painted house Call a function is just

similar to asking somebody to help!

Call a function is just similar to asking somebody to help!

3

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

using namespace std;//function DemonstrationFunction()// show a useful messagevoid DemonstrationFunction(){

cout << "In Demonstration Function\n";cout << "Print one more line\n";

}

Return nothingReturn nothing

They must They must A function is definedA function is defined

18

}

//function main - prints out a message, then//calls DemonstrationFunction(), then shows//the second message.int main(){

cout << "In main\n";DemonstrationFunction();cout << "Back in main\n";return 0;

}

A function is calledA function is called

They must be the same

They must be the same

A function is definedA function is defined

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

using namespace std;//function DemonstrationFunction()// show a useful messagevoid DemonstrationFunction(){

cout << "In Demonstration Function\n";cout << "Print one more line\n";

}

The execution sequenceis like that

19

}

//function main - prints out a message, then//calls DemonstrationFunction(), then shows//the second message.int main(){

cout << "In main\n";DemonstrationFunction();cout << "Back in main\n";return 0;

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• To let the called function really help the main(), sometimes parameters are passed from main() to the called

function

• After finishing the computation, the function should pass

Passing Parameters to Function

20

• After finishing the computation, the function should pass back the results to main()

• It can be achieved by the return statement.

main()Branch to

function(a,b)

function(a,b)

return c

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Mr A wants to decorate his house

Call his friend B to help mowingand give him a mowing machine

Call his friend C to

1

2

21

Return him the mowed lawn

friend C to help painting and give him the paint brush

Return him the painted house

If you want your friend to help, you'd better give him the tool.

If you want your friend to help, you'd better give him the tool.

3

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int Add (int x, int y){ cout << "In Add(),received "<<x<<" and "<<y<<"\n";

return(x+y);}int main(){

cout << "I'm in main()!\n";

Add() returns an integer x+y back to main()

Add() returns an integer x+y back to main()

Input parameters need to declare type -the same as those in the calling functionInput parameters need to declare type -the same as those in the calling function

22

cout << "I'm in main()!\n";int a,b,c;cout << "Enter two numbers: ";cin >> a;cin >> b;cout << "\nCalling Add()\n";c = Add(a,b);cout << "\nBack in main().\n";cout << "c was set to " << c;cout << "\nExiting...\n\n";return 0;

}

c holds the return value of Add()

c holds the return value of Add()

Add() is called with

two parameters

Add() is called with

two parameters

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.1b

a. Build the program in the last slide. Note the output on the console.

b. Modify main() to calculate the square of c.

Ex. 3.1a

23

b. Modify main() to calculate the square of c. Add one more function called Square() to achieve this. The Square() function will take

the square of the parameter that is passed to it. It will return the result in the form of an integerback to the calling function.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.2 Variables and Constants

24

3.2 Variables and Constants

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• A variable is actually a place to store information in a computer

• It is a location (or series of locations) in the memory

• The name of a variable can be considered as a label of that piece of memory

Variables and Memory

25

label of that piece of memory

0000 0001 0010 0011 0100 0101 0110 0111 1000 1001Address

Memory

Variables char a int b short int c bool d

10 0A 21 3A 51 44 20 00

One address for one byte, i.e. 8 bits of memory.

in hex

in bin

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• In memory, all data are groups of '1' and '0', byte by byte

• Depending on how we interpret the data, different types of variables can be identified in the memory

Size of Variables

Typebool

Size1 byte

Valuestrue or false (1 or 0) p.29

p.30

26

boolunsigned short intshort intunsigned long intlong intunsigned intintchar floatdouble

1 byte2 bytes2 bytes4 bytes4 bytes4 bytes4 bytes1 byte4 bytes8 bytes

true or false (1 or 0)0 to 65,535 (i.e. 216-1)-32,768 to 32,7670 to 4,294,967,295 (i.e. 232-1)-2,147,483,648 to 2,147,483,6470 to 4,294,967,295-2,147,483,648 to 2,147,483,647256 character values(+/-)1.2e-38 to (+/-)3.4e38(+/-)2.2e-308 to (+/-)1.8e308

p.29

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Before we use a variable, we need to declare its type so that the computer can reserve suitable memory space for it

• Variables are declared in this way:

Declaring Variables

27

• Variables are declared in this way:

• It defines myVariable to be an integer. Hence 4 bytes

will be reserved for its storage in memory

• The name of the variable is case sensitive, hence

myVariable is NOT the same as myvariable

int myVariable;

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• We can declare one or more variables of the same type at once

• It defines myVar1, myVar2, yourVar1, yourVar2 are all

integers

Declaring Variables

int myVar1, myVar2, yourVar1, yourVar2;

28

integers

• Some names are keywords of the C++ language that cannot be used as variable names

e.g. return, while, for, if, etc.

• We can even initialize the value of the variables when making the declaration

int myVar1 = 10, myVar2, yourVar1, yourVar2 = 5;

Does an uninitialized variable have a value?

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;

Maximum and Minimum

• Each data type has its own maximum and minimum limits

• When the value goes beyond those limits, unexpected behavior may result

p.26

29

using namespace std;int main(){ unsigned short int smallNumber;

smallNumber = 65535; // 1111 1111 1111 1111 = 65535cout << "small number:" << smallNumber << endl;smallNumber++; //1 0000 0000 0000 0000 = 0cout << "small number:" << smallNumber << endl;smallNumber++; // 0000 0000 0000 0001 = 1cout << "small number:" << smallNumber << endl;return 0;

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int main()

Maximum and Minimum

• Signed integers do NOT behave in the same way

p.26

30

int main(){

short int smallNumber;smallNumber = 32767; // 0111 1111 1111 1111 = 32767cout << "small number:" << smallNumber << endl;smallNumber++; // 1000 0000 0000 0000 = -32768cout << "small number:" << smallNumber << endl;smallNumber++; // 1000 0000 0000 0001 = -32767cout << "small number:" << smallNumber << endl;return 0;

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>

Characters• Besides numbers, C++ also has a data type called char, i.e. character

• If a variable is declared as char, the compiler will

consider the variable as an 8-bit ASCII character

31

#include <iostream>using namespace std;int main(){ // ASCII code of '5' is 53

char c = 53, d = '5'; // They are the sameint e = 53;cout << "c = " << c << endl; // c = 5cout << "d = " << d << endl; // d = 5cout << "e = " << e << endl; // e = 53return 0;

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

ASCII Table480 491 502 513 524 535 546 557 568 579

:

6 A 6 B 6 C 6 D 6 E 7 F 7 G 7 H 7 I 7 J

decimal

32

65A 66B 67C 68D 69E 70F 71G 72H 73I 74J

:

97a 98b 99c 100

d 101

e 102

f 103

g 104

h 105

i 106

j

Details of the table can be found in many places, for instance, http://web.cs.mun.ca/~michael/c/ascii-table.html

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Special Printing Characters• C++ compiler recognizes some special charactersfor output formatting

• Start with an escape character \ (e.g. \n means

new line)

Character What it Means

33

Character\n\t\b\"\'\?\\

What it Meansnew linetabbackspacedouble quotesingle quotequestion markbackslash

escape sequence in a string

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Constants

• Unlike variables, the values of constants CANNOT be changed

• The value of a constant will be fixed until the end of the program

• There are two types of constants

34

• There are two types of constants

Literal Constants - come with the language

e.g. a number 39 (you cannot assign another value to 39)

Symbolic Constants -

Like variables, we define a special name as a label to it

Unlike variables, its value cannot be changed once it is initialized.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• A symbolic constant can be defined in two ways

1. Old way - use the preprocessor command #define

• No type needs to be defined for studentPerClass

Defining Symbolic Constants

#define studentPerClass 87

35

• No type needs to be defined for studentPerClass

• The preprocessor just replaces the word studentPerClass with

87 wherever it is found in the source program

2. A better way - use the keyword const

• The data studentPerClass now has a fixed value 87

• It has a type now. This feature helps the compiler to debug the program.

const unsigned short int studentPerClass = 87;

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Why do we need Constants?

• Help debugging the program

Compiler will automatically check if a constant is modified by the program later (and reports it as an error if modified.)

36

• Improve readability

Give the value a more meaningful name; e.g. rather than writing 360, we can use degreeInACircle

• Easy modification

If a constant really needs to be changed, we only need to change a single line in the source program.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int main(){ const int totalStudentNumber = 87;

// Student no. num must < 87int num;cout << "Enter a student number: ";cin >> num;

• Give better readability

• Modify once and apply to whole program

• Give better readability

• Modify once and apply to whole program

37

cin >> num;if (num > totalStudentNumber)

cout << "\n Number not valid!!!\n";

cout << "\n There are " << totalStudentNumber<< " student in this class\n";

return 0;}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Enumerated constants allow one to create a new type that contains a number of constants

• Makes COLOR the name of the new type

• Set RED = 0, BLUE = 1, GREEN = 2, WHITE = 3, BLACK

Enumerated Constants

enum COLOR { RED, BLUE, GREEN, WHITE, BLACK};

38

• Set RED = 0, BLUE = 1, GREEN = 2, WHITE = 3, BLACK = 4

• Another example

• Makes COLOR2 the name of the new type

• Set RED = 100, BLUE = 101, GREEN = 500, WHITE = 501, BLACK = 700

enum COLOR2 {RED=100, BLUE, GREEN=500, WHITE, BLACK=700};

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int main(){ const int Sunday = 0;

const int Monday = 1;const int Tuesday = 2;const int Wednesday = 3;const int Thursday = 4;

Exercise 3.2a.Build the project and note the result

b.Use enumerated constants method to

39

const int Thursday = 4;const int Friday = 5;const int Saturday = 6;int choice;cout << "Enter a day (0-6): ";cin >> choice;if (choice == Sunday || choice == Saturday)

cout << "\nHave a nice weekend!\n";else

cout << "\nToday is not holiday yet.\n";return 0;

}

constants method to simplify the program

Ex.3.3

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.3 Expressions and Statements

40

3.3 Expressions and Statements

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>int abc (...){

... ;return ... ;

}

A Typical Program

function statements

41

}int cde (...){

... ;return ... ;

}int main(){

...;return 0;

}

function

function

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• A C++ program comprises a number of functions

• A function comprises a number of statements

• A statement can be as simple as

Statements

x = a + b;

42

• It can be as complicated as

• A statement must end with a semicolon ;

• In a statement, space carries nearly no information

x = a + b;

if (choice == Sunday || choice == Saturday)cout << "\nYou're already off on weekends!\n";

x = a + b; ⇔⇔⇔⇔ x = a + b ;

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Expressions

• A statement comprises one or many expressions

• Anything that returns a value is an expression, e.g.

3.2; // Returns the value 3.2

43

studentPerClass; // Returns a constant, say 87

x = a + b; // Here, TWO expressions

// Return a + b, return the value of a variable x

• Since x = a + b is an expression (i.e. return a

value) , it can certainly be assigned to another variable, e.g.

y = x = a + b; /* Assign y to the value of x which is assigned to the sum of a and b */

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Operators• An expression often comprises one of more operators

• The assignment operator '=' assigns a value to a variable or constant, e.g. x = 39;

• Several mathematical operators are provided by C++

• Let a be 3, b be 4 and x is declared as an integer,

44

• Let a be 3, b be 4 and x is declared as an integer,

Operators Meaning+ Add- Subtract* Multiply/ Divide % Modulus

Examplesx = a + b; // x = 7x = a - b; // x = -1x = a * b; // x = 12x = a / b; // x = 0 (why?)x = a % b; // x = 3 (why?)

3 modulo 4 is 3

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Integer and Floating Point Divisions#include <iostream>using namespace std;void intDiv(int x, int y){ int z = x/y;

cout << "z: " << z << endl;}void floatDiv(int x, int y)

CastingAsk the compiler to temporarily consider x as a floating point no., i.e. 5.0 in

this case

CastingAsk the compiler to temporarily consider x as a floating point no., i.e. 5.0 in

this case

x, y of main() are not x, y of intDiv(int, int)

45

void floatDiv(int x, int y){ float a = (float)x; // old style

float b = static_cast<float>(y); // ANSI stylefloat c = a/b;cout << "c: " << c << endl;

}int main(){ int x = 5, y = 3;

intDiv(x,y);floatDiv(x,y);return 0;

}

Only give integer division result, i.e. 1Only give integer division result, i.e. 1

Give floating point division result, i.e. 1.66...Give floating point division result, i.e. 1.66...

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• For some commonly used expressions, there are some short hands

c = c + 1; ⇔⇔⇔⇔ c += 1; ⇔⇔⇔⇔ c++; ⇔⇔⇔⇔ ++c; //increment

c = c - 1; ⇔⇔⇔⇔ c -= 1; ⇔⇔⇔⇔ c--; ⇔⇔⇔⇔ --c; //decrement

c = c + 2; ⇔⇔⇔⇔ c += 2;

Short Hand of Expressions

c = c + 2; ⇔⇔⇔⇔ c += 2;

c = c - 3; ⇔⇔⇔⇔ c -= 3;

c = c * 4; ⇔⇔⇔⇔ c *= 4; // there is no c** or c//,

c = c / 5; ⇔⇔⇔⇔ c /= 5; // since it is meaningless

• Let c be an integer with value 5. Note that

a = c++; // a = 5, c = 6 as a = c first and then c++

a = ++c; // a = 6, c = 6 as ++c first and then a = c

46

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Mathematical operations are basically performed from left to right

• It follows the normal mathematical precedence that multiplication/division first and addition/subtraction next, hence

Precedence and Parentheses

47

hence

• To change the precedence, we can use parentheses

• Parentheses can be nested as in normal arithmetic

x = 5 + 3 * 8; // x = 29 since we evaluate 3 * 8 first

x = (5 + 3) * 8; // x = 64 since we evaluate 5 + 3 first

x = 5 * ((3 + 2) + 3 * 2); // x = 5 * (5 + 6) = 55

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Relational Operators• Besides arithmetic operations, we can also perform relational operations with C++

• A number of relational operators are defined in C++

• Each relational operator returns a bool result (true or

false)

48

Operators Meaning== Equals!= Not Equals> Greater than>= Greater than

or equals< Less than<= Less than

or equals

Examples100 == 50; // return false100 != 50; // return true100 > 50; // return true100 >= 50; // return true

100 < 50; // return false100 <= 50; // return false

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Relational operators are often used with if

statement

• The if statement provides branching of the

program execution depending on the conditions

Applications of Relational Operators

49

int bigNumber = 10, smallNumber = 5;

bool bigger = bigNumber > smallNumber; //bigger = true

if (bigger)

{ doSomeThing();

}

Or you can simply write:

if (bigNumber > smallNumber){ doSomeThing();}

Or you can simply write:

if (bigNumber > smallNumber){ doSomeThing();}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Logical Operators• Logical operators do logical operations for bool variables

• Each logical operation returns a bool result (true or false)

Operators Meaning&& AND|| OR

Examplesexpression1 && expression2expression1 || expression2

50

|| OR! NOT

expression1 || expression2!expression

int bigNum = 10, smallNum = 5;

if (bigNum < 10 && smallNum > 0)

{ doSomeThing();

}Would doSomeThing()

be called???

Would doSomeThing()

be called??? NO

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

int bigNum = 10, smallNum = 5;

if ((bigNum < 10 && smallNum > 0) || bigNum > smallNum)

{ doSomeThing();

}Would doSomeThing()

be called???

Would doSomeThing()

be called???

F T

YES

51

int bigNum = 10, smallNum = 5;

if (!(bigNum > smallNum))

{ doSomeThing();

}Would doSomeThing()

be called???

Would doSomeThing()

be called??? NO

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int main(){ int a, b, c;

cout << "Enter 3 numbers: \n";

Exercise 3.3The following program asks the user to enter 3 numbers. If the sum of the first two is equal to the last one, a message is printed to the console

Ex.3.2

52

cout << "Enter 3 numbers: \n";cin >> a;cin >> b;cin >> c;if (c = (a+b));{ cout << "c = a+b\n";}return 0;

}

is printed to the console

a. Build the project and note the result. Doesit perform correctly?

b. If not, fix the problem and re-build the program

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.4 Program Flow Control

53

3.4 Program Flow Control

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Control of Program Flow• Normal program execution is performed from top to downand one statement by one statement

• Often, the program modifies the program flow depending on some conditions set by the programmer or user

• C++ provides many approaches to control program flow

54

if (cond) // if cond{ doA(); // is true,} // then do doA()else // else do doB(){ doB();}

if ... else

• C++ provides many approaches to control program flow

switch (expression){ case value1: doA();

break;case value2: doB();

break;}

switch ... case ... break

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++#include <iostream>

using namespace std;int main(){ int firstNum, secondNum = 10;

cout << "Please enter: \n";cin >> firstNum;cout << "\n\n";if (firstNum >= secondNum){ if ((firstNum % secondNum) == 0)

{ if (firstNum == secondNum)

Nested if ... elseNested if ... else

{} can be omitted.{} can be omitted.

55

{ if (firstNum == secondNum)cout << "They are the same!\n";

elsecout << "They are evenly divisible!\n";

}else

cout << "They are not evenly divisible!\n";}else

cout << "Hey! The second no. is larger!\n";return 0;

}

Use IndentationUse Indentation

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Using braces with if … else#include <iostream>using namespace std;int main(){

int x;cout << "Enter a number x < 10 or x > 100: ";

What’s wrong with this program?How do you solve the problem?What’s wrong with this program?How do you solve the problem?

56

cout << "Enter a number x < 10 or x > 100: ";cin >> x;cout << "\n";

if (x >= 10)if (x > 100)

cout << "More than 100, thanks!\n";else // not the else intended!

cout << "Less than 10, thanks!\n";

return 0;}

??

{

}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

switch … case … break#include <iostream>using namespace std;int main(){ unsigned short int number;

cout << "Enter a number between 1 and 5: ";cin >> number;switch (number)

Only accept number or expression that returns a number

Only accept number or expression that returns a number

Note the differences between break and no breakNote the differences between break and no break

57

switch (number){ case 0: cout << "Too small, sorry!";

break;case 3: cout << "Excellent!\n"; //falls throughcase 2: cout << "Masterful!\n"; //falls throughcase 1: cout << "Incredible!\n";

break;default: cout << "Too large!\n";

break;}cout << "\n\n";return 0;

} Do default if all tests failDo default if all tests fail

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Implement switch with if … else

if (num == 0)cout << "Too small, sorry!";

else

• switch … case statement can be implemented by the if … else statement but with more

complicated structure

• However, switch …

58

else{ if (num == 3 || num == 2 || num == 1)

{ cout << "Incredible!\n";if (num == 3 || num == 2){ cout << "Masterful!\n";

if (num == 3)cout << "Excellent!\n";

}}else

cout << "Too large!\n";}

switch … case can only

be applied to data value tests

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Looping• Many programming problems are solved by repeatedly acting on the same variables

• The method for achieving repeated execution is by looping

• C++ offers many approaches to realize looping

59

• C++ offers many approaches to realize looping

• if … goto // old way, strongly NOT recommended

• while loop // use when the testing parameters are

// complicated

• do-while loop // use when the repeated part is

// expected to be executed at least once

• for loop // use when the testing parameters are

// simple

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

while Loop

#include <iostream>using namespace std;int main(){

• while loops do the looping until the testing condition

fails

Test condition (tested variable must change inside the loop)Test condition (tested variable must change inside the loop)

60

{int counter = 0; //initialize counterwhile (counter<5){

counter++; //top of the loopcout << "counter: " << counter << "\n";

}cout << "Complete. Counter: " << counter << ".\n";return 0;

} Repeat this part until counter >= 5Repeat this part until counter >= 5 5

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

More complicated while Loop• while loops can be used with a more

complicated testing condition

#include <iostream>using namespace std;int main(){ unsigned long small, large;

61

{ unsigned long small, large;unsigned short const MAXSMALL = 65535 ;cin>>small; cin>>large; while (small < large && large > 0 && small < MAXSMALL){

if (small % 5000 == 0)cout << ".\n"; // write a dot every 5000

small++;large -= 2;

}return 0;

}

3 tests for each loop3 tests for each loop

Testing parameters are updated in every loopTesting parameters are updated in every loop

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

do … while• while loops do the test first and then the loop

• Sometimes we would like to have the loop to be done at least once. In this case, do … while can be used

#include <iostream>using namespace std; Hellowill be shown at Hellowill be shown at

62

using namespace std;int main(){ int counter;

cout << "How many hellos? ";cin >> counter;do{ cout << "Hello\n";

counter--;} while (counter > 0);cout << "Counter is: " << counter << endl;return 0;

}

Hellowill be shown at

least once even if the user enters 0 for counter

Hellowill be shown at

least once even if the user enters 0 for counter

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

for loop• In many loops, we initialize a testing parameter, test the parameter, and modify the value of the parameter AFTERdoing the processing.

• It can be done in a single line by a for loop

#include <iostream>

63

#include <iostream>using namespace std;int main(){

int counter;for (counter=0; counter<5; counter++)

cout << "Looping! "; //counter then increment

cout << "\nCounter: " << counter << ".\n";return 0;

}

InitializeInitialize ModifyModifyTestTest

5

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Different varieties of for loops#include <iostream>using namespace std;int main(){ for (int i=0, j=0; i<3; i++, j++)

cout << "i: " << i << " j: " << j << endl;return 0;

}

Multiple initialization and incrementsMultiple initialization and increments

64

}

#include <iostream>using namespace std;int main(){ int counter = 0;

for (; counter < 5;){ counter++;//BEFORE

cout<<"Looping! ";}cout << "\nCounter: " << counter << ".\n"; return 0;

}

Null initialization and incrementsNull initialization and increments

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Different varieties of for loops#include <iostream>using namespace std;int main(){ int counter = 0; // initialization

int max;cout << "How many hellos?"; cin >> max;

65

cin >> max;for (;;) // a for loop that doesn't end{ if (counter < max) // test

{ cout << "Hello!\n";counter++; // increment

}else

break; //end for loop}return 0;

}

Empty for loopEmpty for loop

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

continue and break• Keywords continue and break allow one to change the

program flow during looping

• Should be used with caution since it will make the program hard to understand owing to the sudden change of direction

#include <iostream>Execution of continue will skip the following Execution of continue will skip the following

66

#include <iostream>using namespace std;int main(){ int counter;

for (counter=0; counter<5; counter++){ cout << "Looping! counter is " << counter <<"\n";

if ((counter%2) == 1) //odd numbercontinue;

cout << "Counter is an even number.\n";}return 0;

}

Execution of continue will skip the following

part of the loop but NOT leaving the loop

Execution of continue will skip the following

part of the loop but NOT leaving the loop

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Nested for loops#include <iostream>using namespace std;int main(){ int rows, columns, i, j;

char theChar;cout << "How many rows? ";cin >> rows; More

Ex 3.4

67

cin >> rows;cout << "How many columns? ";cin >> columns;cout << "What characters? ";cin >> theChar;for (i=0; i<rows; i++){ for (j=0; j<columns; j++)

cout << theChar;cout << "\n";

}return 0;

}

Nested for loop

Nested for loop

explanation

on next page

Will be executed (rows×××× columns) times

Will be executed (rows×××× columns) times

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Values of i, jValues of i, j

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

cout << theChar;cout << "\n";

}

Assumption:rows = 2columns = 3theChar = a

Assumption:rows = 2columns = 3theChar = a

68

Output on the screen:Output on the screen:

i = 0 j = ?i = 0 j = 0

ai = 0 j = 0i = 0 j = 1 ai = 0 j = 1i = 0 j = 2

a

i = 0 j = 2i = 0 j = 3

i = 1 j = 3i = 1 j = 0

i = 1 j = 1

i = 1 j = 3

i = 1 j = 2

i = 1 j = 0

ai = 1 j = 1

a

i = 1 j = 2

a↵↵↵↵

i = 0 j = 3

↵↵↵↵

i = 1 j = 3i = 2 j = 3

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

� If a variable is defined in the initialization part of the forloop, the variable will no longer exist on leaving the for loop.

69

It is not an error for Visual Studio .NET 2003.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.4

For the program on p. 67

a.Build the project and note the result.

b.Try to rewrite the program using nested

Ex 3.5

p. 67

70

b.Try to rewrite the program using nested while loops instead of the nested for

loops. Which program is more complicated?

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.5 Functions

71

3.5 Functions

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Functions - Revisit• A function is, in effect, a subprogram that can act on data and return a value

• When the name of the function is encountered in the program, the function is called

• When the function returns, execution resumes

input output

72

• When the function returns, execution resumes on the next line of the calling function.

Callingfunc(){ Statements;

funcA();Statements;funcB();Statements;

}

funcA(){ Statements;

return;}

funcB(){ Statements;

return;}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Function Body

unsigned short int FindArea (int length, int width)

return type function name

type of input parameters

{ // Opening brace

73

name of input parameters

{ // Opening braceStatements;

return (return_value);

} // Closing brace

return value

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Why do we need functions?• Functions help us shorten our program by re-using the program codes.

#include <iostream>using namespace std;void floatDiv(int x, int y){ float a = (float)x;

Reason 1

Ex 3.5

74

{ float a = (float)x;float b = static_cast<float>(y);float c = a/b;cout << "c: " << c << endl;

}int main(){ int w = 7, x = 5, y = 3, z = 2;

floatDiv(w,x);floatDiv(x,y);floatDiv(y,z);return 0;

}

13 lines

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• The same program will be much longer without calling functions

int main(){ int w = 7, x = 5, y = 3, z = 2;float a, b, c;a = (float)w;b = static_cast<float>(x);float c = a/b;cout << "c: " << c << endl;

75

• Can be even longer if the same operation is done in other parts of the program.

cout << "c: " << c << endl;a = (float)x;b = static_cast<float>(y);float c = a/b;cout << "c: " << c << endl;a = (float)y;b = static_cast<float>(z);float c = a/b;cout << "c: " << c << endl;return 0;

}

17 lines

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Functions make our program much easier to read

void floatDiv(int x, int y){ float a = (float)x;

float b = static_cast<float>(y);float c = a/b;

• In this program, it is easily seen that 3 floating-point divisions are to

Reason 2

76

float c = a/b;cout << "c: " << c << endl;

}int main(){ int w = 7, x = 5, y = 3, z = 2;

floatDiv(w,x);floatDiv(x,y);floatDiv(y,z);return 0;

}

divisions are to be done

• Not the case of the previous program without the function.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Declaring Functions• In C++, anything that is not a part of the C++ language needs to be declared

• However, a function need NOT be separately declared ifit is placed before the functions that will call it.

#include <iostream>

Function prototype

77

#include <iostream>using namespace std;void DemoFunction(){ cout << "In Demo Function\n";}

int main(){ cout << "In main\n";

DemoFunction();cout << "Back in main\n";return 0;

}

• Since DemoFunction() is placed before main(), it

need NOT be separately declared

• DemoFunction() can be

used directly.

• Since DemoFunction() is placed before main(), it

need NOT be separately declared

• DemoFunction() can be

used directly.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• However, it is a bad programming practice to require functions to appear in a particular orderbecause

• It is difficult for code maintenance (too restrictive)

• Two functions may call each other (typically inside some loop).

78

loop).

void FuncA(){ :

FuncB();:

}void FuncB(){ :

FuncA();:

}

Which one should be placed first?Which one should be placed first?

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• Functions are usually declared by either one of the two ways:

• Write the prototype of the function at the beginning of the file in which the function is used

• Put the prototype of the function into a header file

79

• Put the prototype of the function into a header fileand include it in the file in which the function is used.

Function PrototypeFunction Prototype

unsigned short int FindArea(int, int);

return type function name type of input parameters

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Declaring Functions#include <iostream>using namespace std;int Area(int length, int width); // function prototypeint main(){ int lengthOfYard;

int widthOfYard;int areaOfYard;cout << "\nHow wide is your yard? ";cin >> widthOfYard;

Although it is not necessary, adding the name of the parameters makes the prototype easier

Although it is not necessary, adding the name of the parameters makes the prototype easier

80

cin >> widthOfYard;cout << "\nHow long is your yard? ";cin >> lengthOfYard;areaOfYard = Area(lengthOfYard,widthOfYard);cout << "\nYour yard is ";cout << areaOfYard;cout << " square feet \n\n";return 0;

}int Area(int yardLength, int yardWidth){ return yardLength * yardWidth;}

the prototype easier to readthe prototype easier to read

Area() is defined after main(). Note

the name of the parameters need NOT be the same as the prototype

Area() is defined after main(). Note

the name of the parameters need NOT be the same as the prototype

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>#include "area.h" // function prototype

int Area(int length, int width); // function prototype

Assume the file area.h has the following statement and is at the same folder as main()Assume the file area.h has the following statement and is at the same folder as main()

Ex 3.5

81

#include "area.h" // function prototypeusing namespace std;int main(){ :

areaOfYard = Area(lengthOfYard,widthOfYard);:return 0;

}

int Area(int yardLength, int yardWidth){ return yardLength * yardWidth;}

It is equivalent to place the content of area.h to hereIt is equivalent to place the content of area.h to here

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Function Prototypes in Header file• Advantage: if a particular set of function prototypes is often used in different programs, we need not declare them every time they are needed

• E.g. iostreamIn different .cpp files One line of #include

vs many lines

82

• E.g. iostream

� Contains prototypes of many functions that are related to the manipulation of I/O stream

� Is needed in most programs that need I/O like cout, cin, etc.

� Should be included at the beginning of most programs; otherwise, we need to type all prototypes in every program.

vs many lines

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.51) For the program on p.74, add the function prototype

such that we can place the function floatDiv() aftermain()

2) Modify the program you've developed in 1) as follows:

• Remove the function prototype

P.74

Ex 3.4

83

• Use Notepad to prepare a file named floatDiv.h that

contains just one statement: the function prototype of floatDiv()

• Store the file floatDiv.h in the same folder as your C++

file

• Include this header file at the beginning of the program as the example in p.81

• Achieve the same result as 1). P.81

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

3.6 Variables of Functions

84

3.6 Variables of Functions

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

• In C++, there are 3 types of variables that a function may make use of:

• Passed parameters and return parameter(s)

� The links between the called

function and the calling function

85

• Local variable � Visible only within a function

� For temporary local storage

• Global variable � Visible to ALL functions in the

program

� An old and dangerous way to communicate between functions

Where are variables located in your machine?

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Local Variables#include <iostream>using namespace std;

float Convert(float); //function prototypeint main(){ float TempFer;

float TempCel = 10;

• A function can define local variables for temporary use.

86

float TempCel = 10;TempFer = 100;TempCel = Convert(TempFer);cout << TempCel << endl;return 0;

}float Convert(float Fer){ float Cel;

Cel = ((Fer - 32) * 5) / 9;return Cel;

}

• Local variables are only visible within the function defining them.

variables for temporary use.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;float Convert(float);int main(){ float TempFer;

float Cel = 10;TempFer = 100;

• Cel in main() is different from the Cel in Convert() although

their names are the same.

• Actually for each function, a separate piece of memory is

• Actually for each function, a separate piece of memory is

87

TempFer = 100;Cel = Convert(TempFer);cout << Cel << endl;return 0;

}float Convert(float Fer){ float Cel;

Cel = ((Fer - 32) * 5) / 9;return Cel;

}

separate piece of memory is allocated to the local variables of each function, disregarding their name.

separate piece of memory is allocated to the local variables of each function, disregarding their name.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;float Convert(float);int main(){ float TempFer;

float Cel = 10;TempFer = 100;Cel=Convert(TempFer);cout << Cel << endl;

float Convert(float Fer){ float Cel;

Cel = ((Fer - 32) * 5) / 9;return Cel;

}

88

cout << Cel << endl;return 0;

}

Memory

Variables

100 10 37.710037.7

main()

TempFer Cel

Convert()

Fer CelFor return

37.7

37.7

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Parameter Passing – Passed by

Value

• It is seen in the previous example that parameters are passed by value

• Only a copy of the parameter value is passed to the

89

• Only a copy of the parameter value is passed to the called function

• What the called function does to the passed parameters have nothing to do with the original one, since they are just two variables (and occupying different memory, even when their names are the same)

• However, such behavior sometimes is not preferred. In that case, we need the passed by reference parameter, which will be covered in the section of Pointers.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Global Variables#include <iostream>using namespace std;int Convert(float); //function prototype changedfloat Cel; // Global variableint main(){ float TempFer;

cout << "Please enter the temperature in Fahrenheit: ";

90

cout << "Please enter the temperature in Fahrenheit: ";cin >> TempFer;Convert(TempFer); //No need to collect the return valuecout << "\nHere's the temperature in Celsius: ";cout << Cel << endl;return 0;

}int Convert(float Fer){

Cel = ((Fer - 32) * 5) / 9;return 0;

}

• Global variable are visible to all functions

• Must be carefully used• Make your program difficult to debug.

• Global variable are visible to all functions

• Must be carefully used• Make your program difficult to debug.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Scope of Variables• It is a rule that variables defined within a pair of braces are visible only to the statements in that braces after the variable is defined.

#include <iostream>using namespace std;void myFunc(){ int x = 8;

x = 8x = 8

Be careful!

91

cout << "\nIn myFunc, local x: " << x << endl;{

cout << "\nIn block in myFunc, x is: " << x;int x = 9; //This x is not the same as the previous xcout << "\nVery local x: " << x;

}cout << "\nOut of block, in myFunc, x: " << x << endl;

}int main(){ myFunc();

return 0;}

x = 8x = 8

x = 9x = 9

x = 8x = 8

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Default Parameters

• Calling function should pass parameters of exactly the same types as those defined in the prototype of the called function

long myFunction(int); //function prototype

It means that any function that calls should

92

It means that any function that calls myFunction() should

pass an integer to it

• The only exception is if the function prototype's parameter has a default value

long myFunction(int x = 50); //default value

If the calling function does not provide a parameter, 50 will be automatically used.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int volumeCube(int, int width = 25, int height = 1);int main(){ int length = 100, width = 50, height = 2, volume;

volume = volumeCube(length, width, height);cout << "First volume equals: " << volume << "\n";

Default ParametersYou may use other namesYou may use other names

93

cout << "First volume equals: " << volume << "\n";volume = volumeCube(length, width);cout << "Second volume equals: " << volume << "\n";volume = volumeCube(length);cout << "Third volume equals: " << volume << "\n";return 0;

}

int volumeCube(int length, int width, int height){ return (length*width*height);}

volume = 100

××××50××××2= 10000

volume = 100

××××50××××1 = 5000

volume = 100

××××25××××1 = 2500

Once a default value is assigned, the parameters following must have default values.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Overloading Functions

• C++ allows overloading of function, i.e. create more than one function with the same name

e.g. int myFunction (int, int);

int myFunction (long, long);long myFunction (long);

3 different functions

Differ by just the

return type is NOT

94

long myFunction (long);

When a function calls myFunction(), the compiler checks

the number and type of the passed parameters to determine which function should be called

• Function overloading is also called polymorphism

•Poly means many, morph means form

•A polymorphic function is many-formed

return type is NOT

allowed

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int intDouble(int);float floatDouble(float);int main(){ int myInt = 6500, doubledInt;

float myFloat = 0.65, doubledFloat;doubledInt = intDouble(myInt);doubledFloat = floatDouble(myFloat);

95

doubledFloat = floatDouble(myFloat);cout << "doubledInt: " << doubledInt << "\n";cout << " doubledFloat : " << doubledFloat << "\n";return 0;

}int intDouble(int original){ return 2*original;}float floatDouble(float original){ return 2*original;}

• The objective of both functions is to double the passed parameter

• It looks much better to have a single function name but different parameter types

• Overloading allows us to do so

• The objective of both functions is to double the passed parameter

• It looks much better to have a single function name but different parameter types

• Overloading allows us to do so

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

#include <iostream>using namespace std;int Double(int);float Double(float);int main(){ int myInt = 6500, doubledInt;

float myFloat = 0.65, doubledFloat;doubledInt = Double(myInt);

Ex 3.6c

96

doubledInt = Double(myInt);doubledFloat = Double(myFloat);cout << "doubledInt: " << doubledInt << "\n";cout << " doubledFloat : " << doubledFloat << "\n";return 0;

}int Double(int original){ return 2*original;}float Double(float original){ return 2*original;}

Overloading

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.6avoid myFunc(){ int x = 8;

cout << "\nIn myFunc, local x: " << x << endl;

cout << "\nIn block in myFunc, x is: " << x;int x = 9;cout << "\nVery local x: " << x;

97

cout << "\nVery local x: " << x;

cout << "\nOut of block, in myFunc, x: " << x << endl;}

The main() on the right is used to call myFunc() above. Build the

program. What is the error message when compiling? Why? Correct the error accordingly.

#include <iostream>using namespace std;void myFunc();int main(){ myFunc();

return 0;}

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.6bA for loop is used as follows:

void myFunc(){

int x = 8;cout << "\nIn myFunc, local x: " << x << endl;for (int x = 10; x>0; x--)

98

for (int x = 10; x>0; x--)cout << "\nInside for loop x: " << x;

cout << "\nIn myFunc, x is: " << x << endl;}

Do you think there is error message when compiling?

What is the scope of the variables defined in the initialization part of the for loop?

Verify it by building the program.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Exercise 3.6c

• Based on the program in p. 96, write a program that

1. Ask the user to input one integer, one floating point number, and one double number (what

P. 96

99

point number, and one double number (what are the differences between an integer, floating point number and double number?)

2. Design a series of overloaded functionsquare() that return the square of the number

the user inputs.

3. The Nuts and Bolts of C++

Computer ProgrammingComputer ProgrammingComputer ProgrammingComputer Programming3. The Nuts and Bolts of C++

Slides

� The powerpoint slides are provided by Dr Frank Leung, EIE.

100