Nothing Special   »   [go: up one dir, main page]

Programming in C++: A C++ Program Is A Collection of One or More

Download as pdf or txt
Download as pdf or txt
You are on page 1of 66

1

Computer Programming
3. The Nuts and Bolts of C++

Programming in C++
z

A C++ program is a collection of one or more


functions (or procedures)

Functions (in C++ program) are very much like functions in


mathematics
A function is like a black box
There must be a function called main( ) in every
executable C++ program
Execution always begins with the first statement in the
function main( )
Any other functions in your program are sub-programs
and are not executed until they are called (either from
main() or from functions called by main())

z
z
z

Computer Programming
3. The Nuts and Bolts of C++

Structure of main() function

Computer Programming
3. The Nuts and Bolts of C++

Preprocessor and Program Codes


#include <iostream>

preprocessor
preprocessor

int main()
{
std::cout << "Hello World!"
<< std::endl;
return 0;
}

Preprocessor: Run before compiling


Instruct the compiler on how to
compile the program
Will not generate machine codes
Start with a pound (#) symbol

The
Theactual
actual
program
program

Actual program:
Every C++ program must
have the main() function
It is the beginning point of
every C++ program

Computer Programming
3. The Nuts and Bolts of C++

Preprocessor
z
z
z
z
z

Preprocessor is called automatically each time you run


the compiler
The preprocessor looks for lines that begin with the #
symbol
If the line is found then the preprocessor modifies the
code
The compiler will compile the modified codes
In addition to #include, there is also #define, #if etc

Computer Programming
3. 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
#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.

Computer Programming
3. The Nuts and Bolts of C++

Program Codes

Think from the point of


view of the compiler.

The basic element of a program is function


A function is composed of:
1.1.Return
ReturnType
Type

2.
2.Function
Functionname
name

int main()
3.
3.Input
Inputparameters
parameters
{
std::cout << "Hello World!"
<< std::endl;
return 0;
}

4.4.Program
Programcodes
codes
enclosed
enclosedby
bythe
the
opening
and
opening andclosing
closing
braces
braces

Note: The meaning of std::cout is checked in iostream

Computer Programming
3. The Nuts and Bolts of C++

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


When executing a program, the operating system will first
call the main() function of this program
If the above main() function executes successfully, it
should return an integer 0 to the operating system
Call main()

main()
Return 0
Means everything fine on executing main()as it is the last statement

Computer Programming
3. The Nuts and Bolts of C++

Program Codes

Send
Sendthe
thestring
stringHello
Hello
World!
World!to
tostd::cout
std::cout
the
thestandard
standardoutput,
output,
defined
in
iostream
defined in iostream

int main()
{
std::cout << "Hello World!"
<< std::endl;
return 0;
Return
Returnan
aninteger
integer00to
tothe
the
}

operating
operatingsystem
system
In console mode, the standard output is just 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 in


iostream

Computer Programming
3. The Nuts and Bolts of C++

Namespaces
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 Folders and files
concept in XP
Namespace A new feature of C++
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 purpose 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.

10

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>

We
Wecan
canhave
haveour
ourown
owncout
cout
by
byputting
puttingititin
inaanamespace
namespace
defined
definedby
byourselves
ourselves

namespace myns {
int cout=0; //Integer variable
} //No semi-colon

This
Thiscout
coutrefers
refersto
to

This
Thiscout
cout
refers
refersto
tothe
the
number
number00

int main()
the
thestandard
standardoutput
output
{
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.

11

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>
namespace myns {
int cout=0;
}

Thats
Thatswhy
whyusing
usingcout
cout
without
withoutthe
theassociate
associate
namespace
namespaceisisan
anerror
error
since
sincethe
thesystem
systemdoes
doesnot
not
know
which
cout
you
know which cout youare
are
referring
referringto
to

int main()
{
std::cout << cout << std::endl;
return 0;
}

12

Computer Programming
3. 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>
using namespace std;

All
Allnames
namesthat
thatare
arenot
notaapart
partof
of
C++
C++will
willbelong
belongto
tothe
the
namespace
std,
unless
namespace std, unless
otherwise
otherwisestated
stated

int main()
{
cout << "Hello World!" << endl;
return 0;
}

No
Noneed
needto
toput
putstd
stdin
infront
frontof
ofcout
coutand
andendl
endl

13

Computer Programming
3. The Nuts and Bolts of We
C++
Wecan
canalso
alsoprint
printintegers,
integers,floatingfloating-

point
pointnumbers
numbersor
oreven
evencombination
combinationof
of

#include <iostream>
string
stringand
andintegers
integersin
instandard
standardoutput
output
using namespace std;
int main()
\n
\n--Another
Anotherway
wayto
toshow
shownewline
newline
{
escape sequence
cout << "Hello there.\n";
cout << "Here is 5: "<< 5 << "\n";
cout << "endl writes a new line to the screen.";
cout <<
\t
\tAdd
Addaatab
tabcharacter
character
Another
endl;
Anotherline
line
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" << 5.0/8 << endl;
cout << "And a very very big number:\t";
cout << 7000.0*7000 <<
endl; // (double) 7000 casting integer to double
cout << "Replace Frank with your name...\n";
cout << "Frank is a C++ programmer!\n";
return 0;
}

14

Computer Programming
3. The Nuts and Bolts of C++

Result

15

Computer Programming
3. 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 only improve 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
}

16

Computer Programming
3. The Nuts and Bolts of C++

Hello.cpp
Preprocessor // Program: Display Hello world
directives // Author(s): ENG2002
// Date: 28/8/2013
Comments
#include <iostream>
Function
named
main()
indicates
start of
program

Provides simple access


using namespace std;
otherwise, std::cout
int main() {
cout << "Hello world!" << endl;
return 0;
}
Ends execution
of main() which ends
program

Insertion
statement

Program

17

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.1a
a. Build the program in p.13. 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 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 5 to line 9 (inclusive). Is there any
change to the results output?

18

Computer Programming
3. The Nuts and Bolts of C++

Function
z
z

main is a function
What is a function?

z
z

A collection of C++ statements to carry out a specific task!

You can have more functions in your program!


How to declare a function ?

A proper name must be unique


Return type
The function body

19

Computer Programming
3. The Nuts and Bolts of C++

Example of a function
Return type

Function body

Function name

int main()
{
/* Text between these two marks are comments
*/
cout << "Hello World!\n";
return 0; // Text after that are also comments
}

20

Computer Programming
3. The Nuts and Bolts of C++

The Function DEFINITION


z

The mathematical definition of the function


f(x) = 5x 3

The C++ programmatic definition would be:


int f(int x)
{
int y = 5*x 3;
return y;
//return 5*x 3;
}

21

Computer Programming
3. The Nuts and Bolts of C++

Function Definition

ReturnDataType FunctionName ( Parameter List )


{
Statement(s)
.
.
.

int Cube ( int n )


{

header
body

return n * n * n ;
}

22

Computer Programming
3. The Nuts and Bolts of C++

More on Functions
Although a single main() function is enough for any C++
program, its a bad habit to do everything by a single function
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.

23

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>

using namespace std;

They
Theymust
must
be
bethe
the
same
same

24

//function DemonstrationFunction()
// show a useful message
Return
Returnnothing
nothing
void DemonstrationFunction()
{
cout << "In Demonstration Function\n";
cout << "Print one more line\n";
}

AAfunction
functionisisdefined
defined

//function main - prints out a message, then


//calls DeomonstrationFunction, then shows
//the second message.
AAfunction
int main()
functionisiscalled
called
{
cout << "In main\n";
DemonstrationFunction();
cout << "Back in main\n";
return 0;
}

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>

using namespace std;

The
execution
sequence
is like
that

//function DemonstrationFunction()
// show a useful message
void DemonstrationFunction()
{
cout << "In Demonstration Function\n";
cout << "Print one more line\n";
}
//function main - prints out a message, then
//calls DeomonstrationFunction, then shows
//the second message.
int main()
{
cout << "In main\n";
DemonstrationFunction();
cout << "Back in main\n";
return 0;
}

25

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>

using namespace std;

Can you write your


program like this?

int main()
{
cout << "In main\n";
DemonstrationFunction();
cout << "Back in main\n";
return 0;
}
//function DemonstrationFunction()
void DemonstrationFunction()
{
cout << "In Demonstration Function\n";
cout << "Print one more line\n";
}

26

Computer Programming
3. The Nuts and Bolts of C++

Function prototype
A prototype looks like a header but must end
with a semicolon;
and its parameter list just needs to contain the
type of each parameter.

int Cube( int );

// prototype

27

Computer Programming
3. The Nuts and Bolts of C++

Function prototype
void DemonstrationFunction();
This the function prototype
Put this before main then your function declaration
can be written after main
void DemonstrationFunction()
{
cout << "In Demonstration Function\n";
cout << "Print one more line\n";
}

28

Computer Programming
3. The Nuts and Bolts of C++

Passing Parameters to Function


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 back
the results to main()
It can be achieved by the return statement.
function(a,b)
Branch to
function(a,b)

main()
return c

29

Computer Programming
3. The Nuts and Bolts of C++

Function with input parameters


Two input parameters
of type integer
int Add (int x, int y)
{
cout << "In Add(),received "<<x<<" and "<<y<<"\n";
return(x+y);
}
Now inside the function Add, the name x refers to the first
input parameter, and y refers to the second parameter

30

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>
Input
Inputparameters
parametersneed
needto
todeclare
declaretype
type--the
the
using namespace std;
same
as
those
in
the
calling
function
same as those in the calling function
int Add (int x, int y)
{
cout << "In Add(),received "<<x<<" and "<<y<<"\n";
return(x+y);
}
Add()
Add()will
willreturn
returnan
aninteger
integer
int main()
x+y
back
to
main()
x+y back to main()
{
cout << "I'm in main()!\n";
int a,b,c;
cout << "Enter two numbers: ";
cin >> a;
Add()
Add()isiscalled
calledwith
withtwo
two
cin >> b;
parameters
parameters
cout << "\nCalling Add()\n";
c = Add(a,b);
cout << "\nBack in main().\n";
cout << "c was set to " << c;
cout << "\nExiting...\n\n";
ccholds
holdsthe
thereturn
returnvalue
valueof
of
return 0;
Add()
Add()
}

31

Computer Programming
3. 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. 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 integer back to
the calling function.

32

Computer Programming
3. The Nuts and Bolts of C++

Variable Concepts
z

Variables

Variable names (identifiers) correspond to locations in the


computer's memory
Every variable has a name, a type, a size and a value
Whenever a new value is placed into a variable, it replaces (and
destroys) the previous value. (Destructive write)
Reading variables from memory does not change them

int i = 45;
i

45
int

36443
4 bytes

variable

value
datatype

address
size

33

Computer Programming
3. The Nuts and Bolts of C++

Variables and Memory


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 char a
Memory
Address

int b

10 0A 21 3A

short int c

bool d

51

00

44 20

in hex

0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 in bin

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

34

Computer Programming
3. The Nuts and Bolts of C++

Size of Variables
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
Type
bool
unsigned short int
short int
unsigned long int
long int
unsigned int
int
char
float
double

Size
1 byte
2 bytes
2 bytes
4 bytes
4 bytes
4 bytes
4 bytes
1 byte
4 bytes
8 bytes

unsigned long long


long long

8 bytes
8 bytes

Values
true or false (1 or 0)
0 to 65,535
(216 - 1)
-32,768 to 32,767
0 to 4,294,967,295
(232 - 1)
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
-2,147,483,648 to 2,147,483,647
256 character values
(+/-)1.40x10-45 to (+/-)3.40x1038
(+/-)4.94x10-324 to (+/-)1.80x10308
0 to (264 - 1)
-263 to (263 - 1)

35

Computer Programming
3. The Nuts and Bolts of C++

Declaring Variables
Before we use a variable, we need to declare its type so
that the compiler can reserve suitable memory space for it
Variables are declared in this way:
int myVariable;
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

36

Computer Programming
3. The Nuts and Bolts of C++

Variable Declarations
type v1,v2,v3, , vn
Example:

int count;
int j;
float k;
double area;
char c;
short int x;
long int y;
unsigned int z;
int a1;

37

Computer Programming
3. The Nuts and Bolts of C++

Declaring Variables
We can declare one or more variables of the same kind at
once
int myVar1, myVar2, yourVar1, yourVar2;

It defines myVar1, myVar2, yourVar1, yourVar2 are


all 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
Does an uninitialized variable have a value?
int myVar1 = 10, myVar2(10), yourVar1, yourVar2 = 5;

38

Computer Programming
3. The Nuts and Bolts of C++

Variable Initialization
z

If a variable is not initialized, the value of


variable may be either 0 or garbage depending
on the storage class of the variable.
int count = 5;
// int count(5);
double length = 1.23;
char c = A;
// char c; c =A;
int i = 1, j, k = 5;
char c1 = B, c2 = 66;
float x = 1.23, y = 0.1;

39

Computer Programming
3. The Nuts and Bolts of C++

Maximum and Minimum


Each data type has its own maximum and minimum limits
When the value goes beyond those limits, unexpected
behavior may result
#include <iostream>
using namespace std;
int main()
{
unsigned short int smallNumber;
smallNumber = 65535; // 1111 1111 1111 1111 = 65535
cout << "small number:" << smallNumber << endl;
smallNumber++;
//1 0000 0000 0000 0000 = 0
// smallNumber = smallNumber + 1;
cout << "small number:" << smallNumber << endl;
smallNumber++;
// 0000 0000 0000 0001 = 1
cout << "small number:" << smallNumber << endl;
return 0;
}

40

Computer Programming
3. The Nuts and Bolts of C++

Maximum and Minimum


Signed integers do NOT behave in the same way
#include <iostream>
using namespace std;
int main()
{
short int smallNumber;
smallNumber = 32767; // 0111 1111 1111 1111 = 32767
cout << "small number:" << smallNumber << endl;
smallNumber++;
// 1000 0000 0000 0000 = -32768
cout << "small number:" << smallNumber << endl;
smallNumber++;
// 1000 0000 0000 0001 = -32767
cout << "small number:" << smallNumber << endl;
return 0;
}

41

Computer Programming
3. The Nuts and Bolts of C++

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
#include <iostream>
using namespace std;
int main()
{
// ASCII code of '5' is 53
char c = 53, d = '5';
// They are the same
int e = 53;
cout << "c = " << c << endl; // c = 5
cout << "d = " << d << endl; // d = 5
cout << "e = " << e << endl; // e = 53
return 0;
}

42

Computer Programming
3. The Nuts and Bolts of C++

decimal

ASCII Table
4
8

0 4 1 5 2 5 3 5 4 5 5 5 6 5 7 5 8 5 9
9

:
6
5

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

:
9
7

a 9 b 9 c 1 d 1 e 1 f 1 g 1 h 1 i 1 j
8

0
0

0
1

0
2

0
3

0
4

0
5

0
6

Details of the table can be found in many places, for instance,


http://web.cs.mun.ca/~michael/c/ascii-table.html

43

Computer Programming
3. The Nuts and Bolts of C++

Special Printing Characters


C++ compiler recognizes some special characters for
output formatting
Start with an escape character \ (e.g. \n means new line)
Character
\n
\t
\b
\"
\'
\a
\\

44

What it Means
new line
tab
backspace
double quote
single quote
bell
backslash

//using goto, not recommended

#include <iostream>
using namespace std;
int main()
{
int i = 0; char c = i;
beg: // label for goto
cout << "[ " << c << " ] = " << i << endl;
i = i + 1; c = i; // c = ++i;
if (i < 256) goto beg;
c = 'A'; cout << "c = " << c << endl;
c = 65; cout << "c = " << c << endl;
i = 'A'; cout << "i = " << i << endl;
// A == 65
cin.get();
return 0;
}

escape sequence

45

Computer Programming
3. The Nuts and Bolts of C++

Floating-point numbers
z
z
z
z

Floating-point number (real number): zero or any positive or negative


number containing a decimal point
Examples:
+10.625
5.0
-6.2
No special characters are allowed
Three floating-point data types in C++:

46

float (single precision) 7 significant digits


double (double precision) 15 significant digits
long double (same as double for Visual C++)

1.2F
1.2
1.2L

Computer Programming
3. The Nuts and Bolts of C++

Exponential Notation
z

Floating point numbers can be written in


exponential notation, where e or E stands for
exponent

10-3
10-4

6.25E-4

47

//Comparing int, double and float

#include <iostream>
using namespace std;
int main ()
{
cout.precision(20);
cout << "1/3 = " << 1/3 << endl << endl;
cout << "1.0/3 = " << 1.0/3 << "\n";
cout << "(double)1/3 = " << (double)1/3 << "\n\n";
cout << "(float)1/3 = " << (float)1/3 << "\n1.0F/3 = " << 1.0F/3 << "\n\n";
cout << "int size = " << sizeof(int) << " bytes\n";
cout << "double size = " << sizeof(double) << " bytes\n";
cout << "float size = " << sizeof(float) << " bytes\n";
cin.get(); return 0;
}

48

Computer Programming
3. 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
Literal Constants - come with the language
e.g. a number 39 (you cannot assign another value to
39)
Symbolic Constants Like variables, users define a special name as a label to it
Unlike variables, its value cannot be changed once it is
initialized.

49

Computer Programming
3. The Nuts and Bolts of C++

Defining Symbolic Constants


A symbolic constant can be defined in two ways
1. Old way - use the preprocessor command #define
#define

studentPerClass

87

No type needs to be defined for studentPerClass


Preprocessor just replaces the word
studentPerClass with 87 whenever it is found in the
source program
2. A better way - use the keyword const
const int studentPerClass = 87;
Variable studentPerClass now has a fixed value 87
It has a type now. This feature helps the compiler to
debug the program.

50

Computer Programming
3. 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 if modified.)
Improve readability
Give the value a more meaningful name
e.g. rather than writing 360, 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.

51

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>
Give
Givebetter
better
using namespace std;
readability
readability
int main()
Modifyonce
onceand
and
{
const int totalStudentNumber = 87; Modify
// Student no. must < 87
apply
applyto
towhole
whole
int num;
program
program
cout << "Enter a student number: ";
cin >> num;
if (num > totalStudentNumber)
cout << "\n Number not valid!!!\n";

cout << "\n There are " << totalStudentNumber


<< " student in this class\n";
return 0;
}

52

Computer Programming
3. The Nuts and Bolts of C++

Enumerated Constants
Enumerated constants allow one to create a new type that
contains a number of constants
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK};

Makes COLOR the name of the new type


Set RED = 0, BLUE = 1, GREEN = 2,
WHITE = 3, BLACK = 4
enum {RED, BLUE, GREEN, WHITE, BLACK};

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

Makes COLOR2 the name of the new type


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

53

Computer Programming
3. The Nuts and Bolts of C++

#include

<iostream>
using namespace std;
int main()
a. Build the project and note
{
const int Sunday = 0;
the result
const int Monday = 1;
const int Tuesday = 2;
const int Wednesday = 3; b. Use enumerated constants
const int Thursday = 4;
method to simplify the
const int Friday = 5;
program
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;
}

54

Exercise 3.2

Computer Programming
3. The Nuts and Bolts of C++

A Typical Program
function

function

function

#include <iostream>
int abc (...)
{
... ;
return ... ;
}
int cde (...)
{
... ;
return ... ;
}
int main()
{
...;
return 0;
}

statements

55

Computer Programming
3. The Nuts and Bolts of C++

Statements
A C++ program comprises a number of functions
A function comprises a number of statements
A statement can be as simple as
x = a + b;

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

A statement must end with a semicolon ;


In a statement, space carries nearly no information
x = a + b;

56

x =

Computer Programming
3. The Nuts and Bolts of C++

Expressions
A statement comprises one or many expressions
Anything that returns a value is an expression
Examples of expressions
3.2
// Returns the value 3.2
studentPerClass // Returns a constant, say 87
x = a + b
// Here, two expressions
// Return a + b and 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
For example,
y = x = a + b;

// assign y to the value of x which


// is equal to the sum of a and b

57

Computer Programming
3. The Nuts and Bolts of C++

Any expression can be an operand

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,
Operators
+
*
/
%

Meaning

Examples

Add
Subtract
Multiply
Divide
modulus
remainder

x
x
x
x
x

=
=
=
=
=

a
a
a
a
a

+
*
/
%

b;
b;
b;
b;
b;

//
//
//
//
//

x
x
x
x
x

=
=
=
=
=

7
-1
12
0 (why?)
3 (why?)

3 modulo 4 is 3

58

Computer Programming
3. The Nuts and Bolts of C++

Arithmetic Operators
z

Binary Operator (two operands)


+
/

(addition)
(division)

(subtraction)
(modulus, remainder)

* (multiplication)
(no ** )

Unary Operator (single operands)


-

(no + )

Example:

int i=1, j=2, k=3, x;


x=i+2*j-22/k;
x=-1+j;
x=1+-j;
x=+i+j;
x=22%k;
float f=1.5, g=0.5, y;
y=2.5*f+4.0*g;
Exercise: Try -5%3 -5%-3 5%-3

(x=1 + 4 -7 = -2)
(x= 1)
(x= -1)
(x=3)
(x= 1, remainder)
(y=5.75)

(hint: -5/3=-1 -5/-3=1 5/-3=-1 and R=x-y*i)

Mixed data types will be discussed later

Ans: -2 -2 2

59

Computer Programming
3. The Nuts and Bolts of C++

Mixed Type Arithmetic


z

Rule #1
char, short
float

Rule #2 (double long unsigned int)

60

int
double

If either operand is double, the other is converted to double, and


the result is double
Otherwise, if either operand is long, the other is converted to
long, and the result is long
Otherwise, if either operand is unsigned, the other is converted
to unsigned, and the result is unsigned
Otherwise, the operand must be int

Computer Programming
3. The Nuts and Bolts of C++

Mixed Type Arithmetic


z

Assign real to int

Assign int value to real

Cut off fractional part of real


Put decimal point at end, converts method of storage to
exponential binary form

Modify with cast operators

Change type of expression


Keyword
static_cast<type>expression
Old form:
(type) expression

1.1 + 3/4 == 1.1 + 0 == 1.1


1.1 + (double)3 /4 == 1.1 + static_cast<double>(3) /4 == 1.85

61

Computer Programming
3. The Nuts and Bolts of C++

Integer and Floating Point Divisions

#include <iostream> x, y of main() are not x, y of intDiv(int, int)


using namespace std;
Casting
void intDiv(int x, int y)
Casting
{
int z = x/y;
Ask
Askthe
thecompiler
compilerto
totemporarily
temporarily
cout << "z: " << z << endl; consider x as a floating point
consider x as a floating point
}
no.,
no.,i.e.
i.e.5.0
5.0in
inthis
thiscase
case
void floatDiv(int x, int y)
{
float a = (float)x;
// old style
float b = static_cast<float>(y); // ANSI style
float c = a/b;
cout << "c: " << c << endl;
}
Only
Onlygive
giveinteger
integer
int main()
{
int x = 5, y = 3; division
divisionresult,
result,i.e.
i.e.11
intDiv(x,y);
floatDiv(x,y);
Give
Givefloating
floatingpoint
point
return 0;
division
result,
}
division result,i.e.
i.e.1.66...
1.66...

62

Computer Programming
3. The Nuts and Bolts of C++

Shorthand of Expressions
For some commonly used expressions, there are some
shorthands
c = c + 1;

c += 1;

c++;

++c; //increment

c = c - 1;

c -= 1;

c--;

--c; //decrement

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; c=c+1;
a = ++c;

// a = 6, c = 6

c=c+1; a=c;

as ++c first and then a = c

63

Computer Programming
3. The Nuts and Bolts of C++

Precedence and Parentheses


Mathematical operations are basically performed from left
to right
It follows the normal mathematical precedence that
multiplication / division first and addition / subtraction
next
Hence
x = 5 + 3 * 8;

// x = 29

since we evaluate 3 * 8 first

To change the precedence, we can use parentheses


x = (5 + 3) * 8; // x = 64

since we evaluate 5 + 3 first

Parentheses can be nested as in normal arithmetic


x = 5 * ((3 + 2) + 3 * 2);

64

// x = 5 * (5 + 6) = 55

Computer Programming
3. The Nuts and Bolts of C++

Rules of Operator Precedence


1.
2.
3.
4.
5.

Parentheses are applied first. If an expression contains nested parentheses, the


innermost pair is evaluated first. If there are several pairs of parentheses on the same
level (that is, not nested), they are evaluated left to right.
Unary plus (+) and minus (-) are applied next. If an expression contains several
unary plus and minus operators, these operators are applied from right to left.
Multiplication (*), division (/) and remainder (%) are applied next. If an expression
contains several multiplication, division and remainder operations, these operators are
applied from left to right.
Addition (+) and subtraction (-) are applied next. If an expression contains several
addition and subtraction operations, these operators are applied from left to right.
Assignment (=) is applied last. This operator has the lowest precedence so far. If an
expression contains several assignment operators, these operators are applied from
right to left.

Figure 3.15 Rules of operator precedence.

Precedence is the order in which operators are applied


Redundant parentheses make expressions easier to read

65

Computer Programming
3. 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)
Operators
==
!=
>
>=
<
<=

66

Meaning

Examples

Equals
Not Equals
Greater than
Greater than
or equals
Less than
Less than
or equals

100
100
100
100

== 50;
!= 50;
> 50;
>= 50;

//
//
//
//

100 < 50;


100 <= 50;

return
return
return
return

false
true
true
true

// return false
// return false

Computer Programming
3. The Nuts and Bolts of C++

Relational Operators
z

Binary Operators
==

!=
<
>
<=
>=
Result is a integer: 1
means true
0
means false
Declare logical type variable and constants using bool
No space between the operators

Example:

Meaning

equal
not equal
greater
less
greater equal
less equal

==
!=
>
<
>=
<=

Expression
5
5
5
5
5
5

== 3
!= 3
> 3
< 3
>= 3
<= 3

Result
0
1
1
0
1
0

int i=10, j=10, k=1;


i + j <= 3 + k

67

Computer Programming
3. The Nuts and Bolts of C++

Applications of Relational Operators


Relational operators are often used with if statement
The if statement provides branching of the program
execution depending on the conditions
int bigNumber = 10, smallNumber = 5;
bool bigger = bigNumber > smallNumber; //bigger = true
if (bigger)
{

doSomeThing();

68

Or
Oryou
youcan
cansimply
simplywrite:
write:
if
if (bigNumber
(bigNumber >> smallNumber)
smallNumber)
{{
doSomeThing();
doSomeThing();
}}

Computer Programming
3. 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

Examples

AND
OR
NOT

expression1 && expression2


expression1 || expression2
!expression

int bigNum = 10, smallNum = 5;


if (bigNum < 10 && smallNum > 0)
{
}

doSomeThing();

Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called??? NO

69

Computer Programming
3. The Nuts and Bolts of C++

int bigNum = 10, smallNum = 5;

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


{

doSomeThing();

Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called??? YES

int bigNum = 10, smallNum = 5;


if (!(bigNum > smallNum))
{

doSomeThing();

Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called???
NO

70

Computer Programming
3. The Nuts and Bolts of C++

Logical (Boolean) Operators


z

Binary Operators
&& (and)

Example:

|| (OR)

Unary Operator

Expression
Result
1
5||3
! (not)
1
5||0
1
5&&3
z Operand should be int
0
5&&0
Use float, result may be affected by round off error
0
i&&j (if i=0, j=0)
1
i&&j+1 (if i=5, j=0)
nonzero (true)
zero (false)
!5
0
z Result is int
!0
1
!i (if i=5)
1 (true)
0 (false)
0
Express connected by && or || are evaluated from left to right, and evaluation stops as soon as the
truth or falsehood of the result is known. i.e. expr1 && expr2 is not equal to expr2 &&
expr1. This is called short-circuit evaluation.
inward == 0 normally be written as !inward

Example:
3<7<5
3 < 7 && 7 < 5
(3 < 7) < 5
1 && 0

1<5

1
0

71

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.3
The 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
a. Build the project and
note the result. Does it
perform correctly?
b. If not, fix the problem
and re-build the
program

72

#include <iostream>
using namespace std;
int main()
{ int a, b, c;
cout << "Enter 3 numbers: \n";
cin >> a;
cin >> b;
cin >> c;
if (c = (a+b));
{
cout << "c = a+b\n";
}
return 0;
}

Computer Programming
3. The Nuts and Bolts of C++

Control of Program Flow


Normal program execution is performed from top-todown and 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
if ... else
if (cond)
{
doA();
}
else
{
doB();
}

//
//
//
//

if the cond
is true,
then do doA()
else do doB()

switch ... case ... break


switch (expression)
{
case value1: doA();
break;
case value2: doB();
break;
}

73

Computer Programming
3. The Nuts and Bolts of C++

The if / else Selection Structure


z

Compound statement:

Set of statements within a pair of braces


Example:
if ( grade
cout <<
else {
cout <<
cout <<
}

>= 60 )
"Passed.\n";
"Failed.\n";
"You must take this course again.\n";

Without the braces,


if ( grade >= 60 )
cout << "Passed.\n";
else
cout << "Failed.\n";
cout << "You must take this course again.\n" ;

the statement
cout << "You must take this course again.\n" ;

would be executed under every condition.

74

Computer Programming

3. The
Nuts and Bolts of C++
#include
<iostream>
using namespace std;
int main()
Nested if ... else
{ int firstNum, secondNum = 10; Nested if ... else
cout << "Please enter: \n";
cin >> firstNum;
cout << "\n\n";
if (firstNum >= secondNum)
{}
{} can
can be
be omitted
omitted
{
if ((firstNum% secondNum) == 0)
for
single
statement
{
if (firstNum == secondNum)
for single statement
cout << "They are the same!\n";
else
cout << "They are evenly divisible!\n";
}
else
cout << "They are not evenly divisible!\n";
}
else
cout << "Hey! The second no. is larger!\n";
return 0;
}

75

Computer Programming
3. The Nuts and Bolts of C++

Using braces with if else


#include <iostream>
Whats
Whatswrong
wrongwith
withthis
thisprogram?
program?
using namespace std;
How
Howdo
doyou
yousolve
solvethe
theproblem?
problem?
int main()
{
int x;
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;
}

76

Computer Programming
3. The Nuts and Bolts of C++

Equality (==) vs. Assignment (=) Operators


z

Dangerous error

Does not ordinarily cause syntax errors


Any expression that produces a value can be used in control structures
Nonzero values are true, zero values are false
Example: using ==:
if ( payCode == 4 )
cout << "You get a bonus!\n";
z

Checks paycode, if it is 4 then a bonus is awarded

Example: replacing == with =:


if ( payCode = 4 )
cout << "You get a bonus!\n";
z
z

This sets paycode to 4


4 is nonzero, so expression is true, and bonus awarded no matter what the
paycode was

Logic error, not a syntax error

77

Computer Programming
3. The Nuts and Bolts of C++

Multiple-Selection Structure: switch


z

switch

Useful when a variable or expression is tested for all the values it can assume and
different actions are taken

Format

true

case 1

case 1

break

action(s)

switch ( value ){

false

case 1:
Actions; break;
case 2:
Actions; break;
default:
actions
}
break; exits from structure

case 2 true
false

case 2

break

action(s)

Series of case labels and an optional


default case

case n

true

false

case n

break

action(s)

default

action(s)

78

Computer Programming
3. The Nuts and Bolts of C++

switch
if (burger == 1) {
unit_price = 8.5;
}
else if (burger == 2) {
unit_price = 12;
}
else if (burger == 3){
unit_price = 15.3;
}
else {
cout<<error \n;
}

switch(burger){
case 1 : unit_price = 8.5;
break;
case 2 : unit_price = 12;
break;
case 3: unit_price = 15.3;
break;
default :
cout<<error \n;
// break; optional
}

79

Computer Programming
3. The Nuts and Bolts of C++

switch case break


#include <iostream>
Only
Onlyaccept
acceptnumber
numberor
orexpression
expression
using namespace std;
that
returns
a
number
that returns a number
int main()
{
unsigned short int number;
cout << "Enter a number between 1 and 5: ";
cin >> number;
Seethe
thedifferences
differencesbetween
betweenbreak
breakand
andwithout
withoutbreak
break
switch (number) See
{ case 0:
cout << "Too small, sorry!";
break;
case 3:
cout << "Excellent!\n";
//falls through
case 2:
cout << "Masterful!\n";
//falls through
case 1:
cout << "Incredible!\n";
break;
default:
cout << "Too large!\n";
break;
}
cout << "\n\n";
return 0;
Do
Dothe
thedefault
defaultififall
alltests
testsfail
fail
}

80

Computer Programming
3. The Nuts and Bolts of C++

Implement switch with if else


switch case statement can be implemented by the
if else statement but with more complicated
structure
if (num == 0)
However,
cout << "Too small, sorry!";
switch
else
case can only { if (num == 3 || num == 2 || num ==
{
cout << "Incredible!\n";
be applied to
if (num == 3 || num == 2)
simple
{
cout << "Masterful!\n";
numerical tests
if (num == 3)
cout << "Excellent!\n";
}
}
else
cout << "Too large!\n";
}

1)

81

Computer Programming
3. The Nuts and Bolts of C++

Looping
Many programming problems are solved by repeatedly
acting on the same data
The method for achieving repeated execution is by looping
C++ provides many approaches to implement 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

82

// use when the testing parameters are


// simple

Computer Programming
3. The Nuts and Bolts of C++

while Loop
int count ;
count = 4;

// initialize loop variable

while (count > 0)


{
cout << count << endl ;

// test expression

count -- ;
}
cout << Done << endl ;

// repeated action
// update loop variable

83

Computer Programming
3. The Nuts and Bolts of C++

while Loops
while loops do the looping until the testing condition fails
#include <iostream>
using namespace std;
int main()
Test
Testcondition
condition(tested
(testedvariable
variablemust
mustchange
changeinside
insidethe
theloop)
loop)
{
int counter = 0;
//initialize counter
while (counter<5)
{
counter++;
//top of the loop
cout << "counter: " << counter << "\n";
}
cout << "Complete. Counter: " << counter << ".\n";
return 0;
}

Repeat
Repeatthis
thispart
partuntil
untilcounter
counter>=
>=55

84

Computer Programming
3. The Nuts and Bolts of C++

More complicated while Loops


while loops can be used with a more complicated testing
condition
#include <iostream>
using namespace std;
int main()
{ unsigned 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++;
33tests
testsfor
foreach
eachloop
loop
large -= 2;
}
Testing
Testingparameters
parametersare
are
return 0;
updated
in
every
loop
}
updated in every loop

85

Computer Programming
3. The Nuts and Bolts of C++

Repetition Structure: do/while


z

The do/while repetition structure

Similar to the while structure

do/while is a post-test condition. The body of the loop is


performed at least once.
z

All actions are performed at least once

Format:
do {
statement;
} while ( condition );
Example:

action(s)

true
condition

Prints the integers from 1 to 10.


(letting counter = 1):

false

do {
cout << counter << , ;
} while (++counter <= 10);

86

Computer Programming
3. 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>
Hello
Hellowill
willbe
beshown
shownat
at
using namespace std;
least
int main()
leastonce
onceeven
evenififuser
user
enters
0
for
counter
{
int counter;
enters 0 for counter
cout << "How many hellos? ";
cin >> counter;
do
{
cout << "Hello\n";
counter--;
}
while (counter > 0);
cout << "Counter is: " << counter << endl;
return 0;

87

Computer Programming
3. The Nuts and Bolts of C++

Repetition Structure: for


z

for loops syntax


for ( initialization ; loopContinuationTest ; increment )
statement
Example: Prints the integers from one to ten

for ( counter = 1; counter <= 10; counter++ )


cout << counter << endl;
z

For loops can usually be rewritten as while loops:


No semicolon
(;) after last
expression

initialization;
while ( loopContinuationTest ) {
statement;
increment;
}
z

Initialization and increment

Can be comma-separated list of statements


Example:
for ( i = 0, j = 0;
cout << j + i;

88

j + i <= 10; j++, i++)

Computer Programming
3. The Nuts and Bolts of C++

for loops
In many loops, we initialize a testing parameter, modify
the value of the parameter and test the parameter
It can be done in a single line by a for loop
#include <iostream>
using namespace std;
int main()
{
Initialize
Initialize Test
Test Modify
Modify
int counter;
for (counter=0; counter<5; counter++)
cout << "Looping! "; //counter then increment
cout << "\nCounter: " << counter << ".\n";
return 0;
}

89

Computer Programming
3. The Nuts and Bolts of C++

Different varieties of for loops


#include <iostream>
Multiple
using namespace std;
Multipleinitialization
initializationand
andincrements
increments
int main()
{
for (int i=0, j=0; i<3; i++, j++)
cout << "i: " << i << " j: " << j << endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
Null
Nullinitialization
initializationand
andincrements
increments
{
int counter = 0;
for (; counter < 5;)
{ counter++;
cout<<"Looping! ";
}
cout << "\nCounter: " << counter << ".\n";
return 0;
}

90

Computer Programming
3. 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;
for (;;) // a for loop that doesn't end
{
if (counter < max) // test
{
cout << "Hello!\n";
Empty
for
loop
counter++;
// increment
Empty for loop
}
else
break; //end for loop
}
return 0;
}

91

Computer Programming
3. 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
Execution
#include <iostream>
Executionof
ofcontinue
continuewill
willskip
skipthe
thefollowing
following
using namespace std;
part
of
the
loop
but
not
leaving
the
part of the loop but not leaving theloop
loop
int main()
{ int counter;
for (counter=0; counter<5; counter++)
{
cout << "Looping! counter is " << counter <<"\n";
if ((counter%2) == 1) //odd number
continue;
cout << "Counter is an even number.\n";
}
return 0;
}

92

Computer Programming
3. The Nuts and Bolts of C++

The break and continue Statements


z

break

Causes immediate exit from a while, for, do/while or switch


structure
Program execution continues with the first statement after the
structure
Common uses of the break statement
z
z

Escape early from a loop


Skip the remainder of a switch structure

continue

Skips the remaining statements in the body of a while, for or


do/while structure
z

while and do/while


z

Proceeds with the next iteration of the loop


Loop-continuation test is evaluated immediately after the continue
statement is executed

for
z

Increment expression is executed, then the loop-continuation test is


evaluated

93

Computer Programming
3. The Nuts and Bolts of C++

continue Statement
while (expr) {
statement

continue;
skip statement

for (expr1; expr2; expr3) {


statement

continue;
statement
skip

do {
statement

continue;
statement
skip

} while(expr)

94

Computer Programming
3. The Nuts and Bolts of C++

break Statement
while (expr) {
statement;

if (expr)
break;
statements;
}
statement;

for (expr1; expr2; expr3) {


statement

if (expr)
break;
statements;
}
statements;

switch (i) {
case 1:
statement_1;
case 2:
statement_2;
case 3:
statement_3;
break;
case 4:
statement_4;
}
statements;

95

Computer Programming
3. The Nuts and Bolts of C++

Nested Loop
initialize outer loop
while ( outer loop condition )

...
initialize inner loop
while ( inner loop condition )
{
inner loop processing and update
} // end inner loop

...
} // end outer loop

96

Computer Programming
3. The Nuts and Bolts of C++

Nested for loops


#include <iostream>
using namespace std;
int main()
{
int rows, columns;
char theChar;
cout << "How many rows? ";
More
cin >> rows;
explanation
cout << "How many columns? ";
on next page
cin >> columns;
cout << "What characters? ";
cin >> theChar;
for (int i=0; i<rows; i++)
{
for (int j=0; j<columns; j++)
Nested
Nestedfor
for
cout << theChar;
loop
loop
cout << "\n";
Will
}
Willbe
beexecuted
executed
return 0;
(rows
(rowscolumns)
columns)
}

times
times

97

Computer Programming
3. The Nuts and Bolts of C++

for (int i=0; i<rows; i++)


Assumption:
Assumption: {
for (int j=0; j<columns; j++)
rows
rows==22
cout << theChar;
columns
columns==33
cout << "\n";
theChar
=
x
theChar = x }
Value
Valueof
ofi,
i,jj
i
i
i
i
i
i
i
i
i

=
=
=
=
=
=
=
=
=

98

0
0
0
0
0
0
0
0
0

j
j
j
j
j
j
j
j
j

=
=
=
=
=
=
=
=
=

?
0
0
1
1
2
2
3
3

i
i
i
i
i
i
i
i
i
i

=
=
=
=
=
=
=
=
=
=

1
1
1
1
1
1
1
1
1
2

j
j
j
j
j
j
j
j
j
j

=
=
=
=
=
=
=
=
=
=

3
0
0
1
1
2
2
3
3
3

Output
Outputon
onthe
thescreen:
screen:
xxx
xxx

Computer Programming
3. The Nuts and Bolts of C++

If a variable is defined in the initialization part of the for loop,


the variable will no longer exist on leaving the for loop.

It is not an error for old


C++ compilers.

99

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.4
For the program on p. 96
a. Build the project and note the result.
b. Try to rewrite the program using nested while
loops instead of the nested for loops. Which
program is more complicated?

100

Computer Programming
3. The Nuts and Bolts of C++

Functions - Revisit

input
A function is, in effect, a subprogram that can act on
data and return a value output
When the name of the function is encountered in the
program, the function is called
When the function returns, execution resumes on the
next line of the calling function
Callingfunc()
{ Statements;
funcA();
Statements;
funcB();
Statements;
}

Return value

funcA()
is void
{ Statements;
return;
}
funcB()
{ Statements;
return;
}

101

Computer Programming
3. The Nuts and Bolts of C++

Function Body
return type

function name

unsigned short int


{

FindArea (int length, int width)

// Opening brace
Statements;
return (return_value);

type of input
parameters

name of input
parameters

// Closing brace

return value

102

Computer Programming
3. The Nuts and Bolts of C++

Why do we need functions?

Reason 1

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;
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

103

Computer Programming
3. The Nuts and Bolts of C++

The same
program will
be much
longer without
function
Can be even
longer if the
same
operation is
done in other
part of the
program

104

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;
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

Computer Programming
3. The Nuts and Bolts of C++

Reason 2

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;
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;
}

In this
program, it is
easily seen that
3 floating-point
divisions are to
be done
Not the case of
the previous
program
without the
function.

105

Computer Programming
3. The Nuts and Bolts of C++

Declaring Functions
In C++, anything that is not a part of the C++ language
needs to be declared
Function prototype
However, a function need NOT be separately declared if
it is placed before the functions that will call it
#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;
}

106

Since
SinceDemoFunction()
DemoFunction()
isisplaced
placedbefore
beforemain(),
main(),
ititneed
neednot
notbe
beseparately
separately
declared
declared
DemoFunction()
DemoFunction()can
can
be
used
directly
be used directly

Computer Programming
3. The Nuts and Bolts of C++

However, it is a bad programming practice to require


functions to appear in a particular order because
It is difficult for code maintenance (too restrictive)
Two functions may call each other (typically inside some
loop)
void FuncA()
{ :
FuncB();
:
}
void FuncB()
{ :
FuncA();
:
}

Which
Whichone
oneshould
should
be
beplaced
placedfirst?
first?

107

Computer Programming
3. 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
and include it in the file in which the function is used
Function
FunctionPrototype
Prototype
unsigned short int
return type

108

FindArea(int, int);
function name

type of input
parameters

Computer Programming
3. The Nuts and Bolts of C++

#include <iostream>
using namespace std;
int Area(int length, int width); // function prototype
int main()
{
int lengthOfYard;
Although
Althoughititisisnot
not
int widthOfYard;
necessary,
adding
necessary, addingthe
the
int areaOfYard;
name
of
the
parameters
cout << "\nHow wide is your yard? "; name of the parameters
makes
makesthe
theprototype
prototype
cin >> widthOfYard;
easierto
toread
read
cout << "\nHow long is your yard? "; easier
cin >> lengthOfYard;
areaOfYard = Area(lengthOfYard,widthOfYard);
cout << "\nYour yard is ";
cout << areaOfYard;
Area()
Area()isisplaced
placedafter
after
cout << " square feet \n\n";
main().
Note
the
name
return 0;
main(). Note the name
of
}
ofthe
theparameters
parametersare
are
int Area(int yardLength, int yardWidth)
NOT
the
same
as
the
NOT the same as the
{
return yardLength * yardWidth;
prototype
prototype
}

Declaring Functions

109

Computer Programming
3. The Nuts and Bolts of C++

Assume
Assumethe
thefile
filearea.h
area.hhas
hasthe
thefollowing
followingstatement
statement
and
is
at
the
same
folder
as
main()
and is at the same folder as main()
int Area(int length, int width); // function prototype

#include <iostream>
#include "area.h"
// function prototype
using namespace std;
ItItisisequivalent
equivalentto
toplace
placethe
the
int main()
content
of
area.h
to
here
content of area.h to here
{
:
areaOfYard = Area(lengthOfYard,widthOfYard);
:
return 0;
}
int Area(int yardLength, int yardWidth)
{
return yardLength * yardWidth;
}

110

Computer Programming
3. 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. iostream

In different .cpp files

One line of #include


Vs many lines

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.

111

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.5
1) For the program on p.102, add the function prototype
such that we can place the function floatDiv() after
main().
2) Modify the program you've developed in 1) as follows:
Remove the function prototype
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.109
Achieve the same result as 1).

112

Computer Programming
3. The Nuts and Bolts of C++

In C++, there are 3 types of variables that a function may


make use of:
Where do variables locate in your machine?
Passed parameters and return parameter(s)
The links between the called
function and the calling function
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

113

Computer Programming
3. The Nuts and Bolts of C++

Variable Scope
z
z

z
z

114

Local variables: variables declared within a


function
Such variables have local scope; they can be
used only within the function in which they are
declared
Global variables: variables declared outside
any function
Such variables have global scope; they can be
used by all functions that occur after their
declaration

Computer Programming
3. The Nuts and Bolts of C++

Variable Scope
Global variable

Local variable

The three storage


areas created by
a C++ Program.
Local variable

115

Computer Programming
3. The Nuts and Bolts of C++

Local Variables
#include <iostream>
using namespace std;
float Convert(float); //function prototype
int main()
AAfunction
{
float TempFer;
functioncan
candefine
definelocal
local
float TempCel = 10;
variables
for
temporary
variables for temporaryusage
usage
TempFer = 100;
TempCel = Convert(TempFer);
cout << TempCel << endl;
Local
return 0;
Localvariables
variablesare
areonly
only
}
visible
visiblewithin
withinthe
thefunction
function
float Convert(float Fer)
defining
definingthem
them
{
float Cel;
Cel = ((Fer - 32) * 5) / 9;
return Cel;
}

116

Computer Programming
3. The Nuts and Bolts of C++

Cel
Celin
inmain()is
main()isdifferent
different
from
the
Cel
in
Convert()
from the Cel in Convert()
although
althoughtheir
theirname
nameisisthe
the
same.
same.

#include <iostream>
using namespace std;
float Convert(float);
int main()
{
float TempFer;
float Cel = 10;
Actually
Actuallyfor
foreach
eachfunction,
function,aa
TempFer = 100;
separate
separatepiece
pieceof
ofmemory
memoryisis
Cel = Convert(TempFer);
allocated
cout << Cel << endl;
allocatedto
tothe
thelocal
localvariables
variables
return 0;
of
ofeach
eachfunction
functiondisregarding
disregarding
}
their
name.
their name.
float Convert(float Fer)
{
float Cel;
Cel = ((Fer - 32) * 5) / 9;
return Cel;
}

117

Computer Programming
3. 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;
return 0;
37.7
}

float Convert(float Fer)


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

main()
Variables
Memory

118

TempFer Cel
100

37.7
10

Convert()
For return Fer
37.7

100

Cel
37.7

Computer Programming
3. 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 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

119

Computer Programming
3. The Nuts and Bolts of C++

Parameter Passing - by Value


z

Variables a and x use different memory cells.

different
copies

120

Computer Programming
3. The Nuts and Bolts of C++

Parameter Passing - by Reference


z

Variables a and x share the same memory cell.

same
copy

121

Computer Programming
3. The Nuts and Bolts of C++

Global Variables
#include <iostream>
using namespace std;
int Convert(float); //function prototype changed
float Cel; // Global variable
int main()
{
float TempFer;
cout << "Please enter the temperature in Fahrenheit: ";
cin >> TempFer;
Convert(TempFer); //No need to collect the return value
cout << "\nHere's the temperature in Celsius: ";
cout << Cel << endl;
return 0;
Global
Globalvariable
variableare
arevisible
visible
}
to
int Convert(float Fer)
toall
allfunctions
functions
{
Must
be
Must becarefully
carefullyused
used
Cel = ((Fer - 32) * 5) / 9; Make your program
Make your program
return 0;
difficult
difficultto
todebug.
debug.
}

122

Computer Programming
3. The Nuts and Bolts of C++

Scope of Variables

It is a rule of thumb 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;
Be careful!
void myFunc()
xx==88
{ int x = 8;
cout << "\nIn myFunc, local x: " << x << endl;
{
xx==88
cout << "\nIn block in myFunc, x is: " << x;
int x = 9; //This x is not the same as the previous x
cout << "\nVery local x: " << x;
xx==99
}
cout << "\nOut of block, in myFunc, x: " << x << endl;
}
int main()
xx==88
{
myFunc();
return 0;
}

123

Computer Programming
3. 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 myFunction()
should pass an integer to it
The only exception is if the function prototype 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 :
myFunction( ); myFunction(50);

124

Computer Programming
3. The Nuts and Bolts of C++

Default Parameters
You
Youmay
mayuse
useother
othernames
names
#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";
volume = volumeCube(length, width);
cout << "Second volume equals: " << volume << "\n";
volume = volumeCube(length);
cout << "Third volume equals: " << volume << "\n";
return 0;
volume
volume==100
100 volume
volume==100
100
volume ==100
100 volume
}
502= 10000
501 = 5000
251 = 2500
502= 10000

501 = 5000

int volumeCube(int length, int width, int height)


{
return (length*width*height);
}

251 = 2500

Once
Onceaadefault
defaultvalue
valueisisassigned,
assigned,the
theparameters
parametersfollowing
followingmust
musthave
havedefault
defaultvalues.
values.

125

Computer Programming
3. 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);
3 different
Differ by just the
int myFunction (long, long);
functions
return type is NOT
long
myFunction
(long);
allowed
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

126

Computer Programming
3. 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);
cout << "doubledInt: " << doubledInt << "\n";
cout << " doubledFloat : " << doubledFloat << "\n";
return 0;
The
Theobjective
objectiveof
of both
bothfunctions
functions
}
is
to
double
the
passed
int intDouble(int original)
is to double the passed
parameter
{
return 2*original;
parameter
}
It looks much better to have a
float floatDouble(float original) It looks much better to have a
single
singlefunction
functionname
namebut
but
{
return 2*original;
different
parameter
types
different parameter types
}

Overloading
Overloadingallows
allowsus
usto
todo
doso
so

127

Computer Programming
3. 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);
doubledFloat = Double(myFloat);
cout << "doubledInt: " << doubledInt << "\n";
cout << " doubledFloat : " << doubledFloat << "\n";
return 0;
}
int Double(int original)
{
return 2*original;
}
Overloading
Overloading
float Double(float original)
{
return 2*original;
}

128

Computer Programming
3. The Nuts and Bolts of C++

Parameter Passing Passed by Reference


#include <iostream>
using namespace std;
void Double(int& original);
void Double(float& original);
int main()
{
int
myInt = 6500;
float myFloat = 0.65;
Double(myInt);
Double(myFloat);
cout << "doubledInt: " << myInt << "\n";
cout << " doubledFloat : " << myFloat << "\n";
return 0;
}
void Double(int& original)
{
original = 2*original;
}
Overloading
Overloading
void Double(float& original)
{
original = 2*original;
}

129

Computer Programming
3. The Nuts and Bolts of C++

Recursive Function
Example: factorials: 5! = 5 * 4 * 3 * 2 * 1
z
z

5! = 5 * 4!
4! = 4 * 3!

1
n! =
n(n 1)!

n=0
n>0

Can compute factorials recursively


Solve base case (1! = 0! = 1) then plug in
z
z

2! = 2 * 1! = 2 * 1 = 2;
3! = 3 * 2! = 3 * 2 = 6;

long factorial(int n)
{
if (n == 0)
return 1;
else
return n * factorial(n-1);

130

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.6a
void 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;
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;
}

131

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.6b
A for loop is used instead as follows:
void myFunc()
{
int x = 8;
cout << "\nIn myFunc, local x: " << x << endl;
for (int x = 10; x>0; x--)
cout << "\nInside for loop x: " << x;
cout << "\nIn block in 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.

132

Computer Programming
3. The Nuts and Bolts of C++

Exercise 3.6c
Based on the program in p. 127, write a program that
1. Ask the user to input one integer, one floating 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 function square()
that return the square of the number the user
inputs.

You might also like