Title: Wavelet transform And Its Applications to Image Processing
1Learning the C language 3. The Nuts and Bolts
of C
2What you have learned last week?
- Built (compiling and linking) a simple C
program under the Visual Studio environment. - Source code, object code, and executable code
- Encountered syntax errors.
- Compile-time errors are useful.
- Run-time errors
- Debugging process
- Debugging all kinds of errors
3What you have learned last week?
- Executed the program in the console mode.
- Many command-line applications are known as
console applications. - Installed Visual Studio at your own PC.
- Reading
43.1 Revisit HelloWorld
5A simple program
include ltiostreamgt int main() stdcout ltlt
"Hello World!" ltlt stdendl return 0
6Elements of a C program
- A main() function
- A program consists of many functions.
- It is expected to return an integer value.
- Inputs and outputs
- Standard output stream (stdcout)
- Standard input stream (stdcin)
- Insert a new-line character (stdendl)
- Standard library
- It is a collection of classes and functions, such
as iostream. - Data type character strings and the new-line
character - Operators ltlt is an insertion operator.
- Statements
7Preprocessor and Program Codes
include ltiostreamgt int main() stdcout ltlt
"Hello World!" ltlt stdendl return 0
Preprocessor
The actual program
- 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
8Preprocessor
include ltiostreamgt
- 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 ltiostreamgt 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.
9Program Codes
Think from the point of view of the compiler.
- The basic element of a program is function
- A function is composed of
1. Return Type
2. Function name
int main() stdcout ltlt "Hello World!" ltlt
stdendl return 0
3. Input parameters
4. Program codes enclosed by the opening and
closing braces
Note The meaning of stdcout is checked in the
file iostream in the preprocesor.
10- 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.
11Program Codes
Send the string Hello World! to stdcout the
standard output, defined in iostream
int main() stdcout ltlt "Hello World!" ltlt
stdendl return 0
Return 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 " " - stdendl means newline (or Enter), also defined
in iostream
12Namespaces
- stdcout and stdendl 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
- 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.
Folders and files concept in Windows
13We can have our own cout by putting it in a
namespace defined by ourselves
include ltiostreamgt namespace myns int
cout0 //Integer variable //No semi-colon int
main() stdcout ltlt mynscout ltlt
stdendl return 0
This cout refers to the number 0
This cout refers to the standard output
- 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.
14Thats why using cout without the associate
namespace is an error since the system does not
know which cout you are referring to
include ltiostreamgt namespace myns int
cout0 int main() stdcout ltlt cout ltlt
stdendl return 0
?
15- It may be a bit cumbersome to write the namespace
of names every time - A short form is to use the using statement
All names that are NOT a part of C will belong
to the namespace std, unless otherwise stated
include ltiostreamgt using namespace std int
main() cout ltlt "Hello World!" ltlt endl return
0
No need to put std in front of cout and endl
16We can also print integers, floating- point
numbers or even combination of string and
integers in standard output
include ltiostreamgt using namespace std int
main() cout ltlt "Hello there.\n" cout ltlt
"Here is 5 "ltlt 5 ltlt "\n" cout ltlt "endl writes
a new line to the screen." cout
ltlt endl cout ltlt "Here is a very big
number\t" ltlt 70000 ltlt endl cout ltlt "Here is
the sum of 8 and 5\t" ltlt 85 ltlt endl cout ltlt
"Here's a fraction\t\t" ltlt (float) 5/8 ltlt
endl cout ltlt "And a very very big
number\t" cout ltlt (double) 70007000
ltlt endl //casting integer to double cout ltlt
"Replace Frank with your name...\n" cout ltlt
"Frank is a C programmer!\n" return 0
\n - Another way to show newline
escape sequence
\t - Add a tab character
Another line
Ex. 3.1a
17Result
18Comments
- 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 - Comments can be added in two ways
- Comments can be added in two ways
include ltiostreamgt using namespace std int
main() / Text between these two marks are
comments / cout ltlt "Hello World!\n" return
0 // Text after that are also comments
19Exercise 3.1a
p.16
a. Build the program in p.16. 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 4 to line 8 (inclusive). Is
there any change to the results output?
Ex 3.1b
20More 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.
21Mr. A wants to decorate his house
2
Call his friend B to help mowing
1
Call his friend C to help painting
Return him the mowed lawn
Return him the painted house
3
Call a function is just similar to asking
somebody to help!
22include ltiostreamgt using namespace
std //function DemonstrationFunction() // show a
useful message void DemonstrationFunction() cou
t ltlt "In Demonstration Function\n" cout ltlt
"Print one more line\n" //function main -
prints out a message, then //calls
DeomonstrationFunction, then shows //the second
message. int main() cout ltlt "In
main\n" DemonstrationFunction() cout ltlt "Back
in main\n" return 0
23include ltiostreamgt using namespace
std //function DemonstrationFunction() // show a
useful message void DemonstrationFunction() cou
t ltlt "In Demonstration Function\n" cout ltlt
"Print one more line\n" //function main -
prints out a message, then //calls
DeomonstrationFunction, then shows //the second
message. int main() cout ltlt "In
main\n" DemonstrationFunction() cout ltlt "Back
in main\n" return 0
The execution sequence is like that
24Passing 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
25Mr. A wants to decorate his house
Call his friend B to help mowing and give him a
mowing machine
2
1
Call his friend C to help painting and give him
the paint brush
Return him the mowed lawn
Return him the painted house
If you want your friend to help, you'd better
give him the tool!
3
26include ltiostreamgt using namespace std int Add
(int x, int y) cout ltlt "In Add(),received
"ltltxltlt" and "ltltyltlt"\n" return(xy) int
main() cout ltlt "I'm in main()!\n" int
a,b,c cout ltlt "Enter two numbers " cin gtgt
a cin gtgt b cout ltlt "\nCalling Add()\n" c
Add(a,b) cout ltlt "\nBack in main().\n" cout
ltlt "c was set to " ltlt c cout ltlt
"\nExiting...\n\n" return 0
Input parameters need to declare type - the same
as those in the calling function
Add() returns an integer xy back to main()
Add() is called with two parameters
c holds the return value of Add()
27Exercise 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.
283.2 Variables and Constants
29Variables 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 int b short int c
bool d
Memory
10
0A
21
3A
51
44
20
00
in hex
Address
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
in bin
One address for one byte, i.e. 8 bits.
30Size 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
p.35
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
Values true or false (1 or 0) 0 to 65,535 (i.e.
216-1) -32,768 to 32,767 0 to 4,294,967,295 (i.e.
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.2e-38 to
(/-)3.4e38 (/-)2.2e-308 to (/-)1.8e308
p.34
31Exercise 3.2a
a. Build the project and note the results. b. Add
lines for bool, unsigned int, unsigned long int,
and unsigned int.
include ltiostreamgt using namespace std int
main() cout ltlt "The size of an int is\t\t"
ltlt sizeof(int) ltlt " bytes.\n" cout ltlt "The
size of a short int is\t" ltlt sizeof(short) ltlt "
bytes.\n" cout ltlt "The size of a long int
is\t" ltlt sizeof(long) ltlt " bytes.\n" cout
ltlt "The size of a char is\t\t" ltlt
sizeof(char) ltlt " bytes.\n" cout ltlt "The
size of a float is\t\t" ltlt sizeof(float) ltlt "
bytes.\n" cout ltlt "The size of a double is\t"
ltlt sizeof(double) ltlt " bytes.\n" return 0
32Declaring 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
- 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
33Declaring Variables
- We can declare one or more variables of the same
type at once - 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
int myVar1, myVar2, yourVar1, yourVar2
int myVar1 10, myVar2, yourVar1, yourVar2 5
Does an uninitialized variable have a value?
34Maximum and Minimum
p.30
- Each data type has its own maximum and minimum
limits - When the value goes beyond those limits,
unexpected behavior may result
include ltiostreamgt using namespace std int
main() unsigned short int smallNumber smallNum
ber 65535 // 1111 1111 1111 1111
65535 cout ltlt "small number" ltlt smallNumber ltlt
endl smallNumber //1 0000 0000 0000 0000
0 cout ltlt "small number" ltlt smallNumber ltlt
endl smallNumber // 0000 0000 0000 0001
1 cout ltlt "small number" ltlt smallNumber ltlt
endl return 0
35Maximum and Minimum
p.30
- Signed integers do NOT behave in the same way
include ltiostreamgt using namespace std int
main() short int smallNumber smallNumber
32767 // 0111 1111 1111 1111 32767 cout ltlt
"small number" ltlt smallNumber ltlt
endl smallNumber // 1000 0000 0000 0000
-32768 cout ltlt "small number" ltlt smallNumber ltlt
endl smallNumber // 1000 0000 0000 0001
-32767 cout ltlt "small number" ltlt smallNumber ltlt
endl return 0
36Characters
- 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 ltiostreamgt using namespace std int
main() // ASCII code of '5' is 53 char c 53,
d '5' // They are the same int e
53 cout ltlt "c " ltlt c ltlt endl // c 5 cout
ltlt "d " ltlt d ltlt endl // d 5 cout ltlt "e "
ltlt e ltlt endl // e 53 return 0
37ASCII Table
decimal
48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 56 8 57 9
65 A 66 B 67 C 68 D 69 E 70 F 71 G 72 H 73 I 74 J
97 a 98 b 99 c 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/asc
ii-table.html
38Special 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 \" \' \? \\
What it Means new line tab backspace double
quote single quote question mark backslash
escape sequence in a string
39Constants
- 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, the user define a special name
as a label to it - Unlike variables, its value cannot be changed
once it is initialized.
40Defining Symbolic Constants
- 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
- 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.
define studentPerClass 87
const unsigned short int studentPerClass 87
41Why 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.) - 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.
42include ltiostreamgt using namespace std int
main() const int totalStudentNumber 87 //
Student no. num must lt 87 int num cout ltlt
"Enter a student number " cin gtgt num if (num
gt totalStudentNumber) cout ltlt "\n Number not
valid!!!\n" cout ltlt "\n There are " ltlt
totalStudentNumber ltlt "
student in this class\n" return 0
- Give better readability
- Modify once and apply to whole program
43Enumerated Constants
- 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 4 - Another example
- Makes COLOR2 the name of the new type
- Set RED 100, BLUE 101, GREEN 500, WHITE
501, BLACK 700
enum COLOR RED, BLUE, GREEN, WHITE, BLACK
enum COLOR2 RED100, BLUE, GREEN500, WHITE,
BLACK700
44Exercise 3.2
include ltiostreamgt 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 const int Friday
5 const int Saturday 6 int choice cout ltlt
"Enter a day (0-6) " cin gtgt choice if
(choice Sunday choice Saturday) cout
ltlt "\nHave a nice weekend!\n" else cout ltlt
"\nToday is not holiday yet.\n" return 0
a. Build the project and note the result b. Use
enumerated constants method to simplify the
program
Ex.3.3
453.3 Expressions and Statements
46A Typical Program
include ltiostreamgt int abc (...) ...
return ... int cde (...) ... return
... int main() ... return 0
function
statements
function
function
47Statements
- A C program comprises a number of functions
- A function comprises a number of statements
- A statement can be as simple as
- 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
ltlt "\nYou're already off on weekends!\n"
x a b
?
x a b
48Expressions
- A statement comprises one or many expressions
- Anything that returns a value is an expression,
e.g. - 3.2 // Returns the value 3.2
- 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 to y the value of x
which is equal to the sum of a and b /
49Operators
- An expression often comprises one of more
operators - The assignment operator '' assigns a value or
constant to a variable, 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 Add - Subtract
Multiply / Divide modulus
Examples x a b // x 7 x a - b // x
-1 x a b // x 12 x a / b // x 0
(why?) x a b // x 3 (why?)
3 modulo 4 is 3
50Integer and Floating Point Divisions
x, y of main() are not x, y of intDiv(int, int)
include ltiostreamgt using namespace std void
intDiv(int x, int y) int z x/y cout ltlt "z
" ltlt z ltlt endl void floatDiv(int x, int
y) float a (float)x // old style float b
static_castltfloatgt(y) // ANSI style float c
a/b cout ltlt "c " ltlt c ltlt endl int
main() int x 5, y 3 intDiv(x,y) floatDiv
(x,y) return 0
Casting Ask the compiler to temporarily consider
x as a floating point no., i.e. 5.0 in this case
Only give integer division result, i.e. 1
Give floating point division result, i.e. 1.66...
51Short Hand of Expressions
- 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
- 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
52Precedence 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 - 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
53Exercise 3.3a
include ltiostreamgt int main() int myAge
39 // initialize two integers int
yourAge 39 cout ltlt "I am " ltlt myAge ltlt "
years old.\n" cout ltlt "You are " ltlt yourAge
ltlt " years old\n" myAge //
postfix increment yourAge // prefix
increment cout ltlt "One year passes...\n"
cout ltlt "I am " ltlt myAge ltlt " years old.\n"
cout ltlt "You are " ltlt yourAge ltlt " years
old\n" cout ltlt "Another year passes\n"
cout ltlt "I am " ltlt myAge ltlt " years old.\n"
cout ltlt "You are " ltlt yourAge ltlt " years
old\n" cout ltlt "Let's print it again.\n"
cout ltlt "I am " ltlt myAge ltlt " years old.\n"
cout ltlt "You are " ltlt yourAge ltlt " years
old\n" return 0
54Relational Operators
- Besides arithmetic operations, we can perform
relational operations with C. - A number of relational operators are defined in
C. - Each relational operator returns a bool result
(true or false). - In C, zero is considered false, and all other
values are considered true. - True is usually represented by 1.
55Relational Operators
56Applications 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 gt smallNumber //bigger
true - if (bigger)
- doSomeThing()
-
Or you can simply write if (bigNumber gt
smallNumber) doSomeThing()
57Logical Operators
- Logical operators do logical operations for bool
variables - Each logical operation returns a bool result
(true or false)
Operators Meaning AND OR ! NOT
Examples expression1 expression2 expression1
expression2 !expression
int bigNum 10, smallNum 5 if (bigNum lt 10
smallNum gt 0) doSomeThing()
Would doSomeThing() be called???
NO
58int bigNum 10, smallNum 5 if ((bigNum lt 10
smallNum gt 0) bigNum gt smallNum) doSomeT
hing()
F
T
Would doSomeThing() be called???
YES
int bigNum 10, smallNum 5 if (!(bigNum gt
smallNum)) doSomeThing()
Would doSomeThing() be called???
NO
59Exercise 3.3
Ex.3.2
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
include ltiostreamgt using namespace std int
main() int a, b, c cout ltlt "Enter 3
numbers \n" cin gtgt a cin gtgt b cin gtgt
c if (c (ab)) cout ltlt "c ab\n"
return 0
603.4 Program Flow Control
61Control of Program Flow
- Normal program execution is performed from
top-to-down 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 (cond) // if cond doA() // is
true, // then do doA() else // else
do doB() doB()
if ... else
switch ... case ... break
switch (expression) case value1 doA()
break case value2 doB() break
62include ltiostreamgt using namespace std int
main() int firstNum, secondNum 10 cout
ltlt "Please enter \n" cin gtgt firstNum
cout ltlt "\n\n" if (firstNum gt secondNum)
if ((firstNum secondNum) 0) if
(firstNum secondNum) cout ltlt "They are the
same!\n" else cout ltlt "They are evenly
divisible!\n" else cout ltlt "They are not
evenly divisible!\n" else cout ltlt "Hey!
The second no. is larger!\n" return 0
Nested if ... else
can be omitted.
63Using braces with if else
Whats wrong with this program? How do you solve
the problem?
include ltiostreamgt using namespace std int
main() int x cout ltlt "Enter a number x lt 10
or x gt 100 " cin gtgt x cout ltlt "\n" if (x
gt 10) if (x gt 100) cout ltlt "More than 100,
thanks!\n" else // not the else
intended! cout ltlt "Less than 10,
thanks!\n" return 0
64switch case break
include ltiostreamgt using namespace std int
main() unsigned short int number cout ltlt
"Enter a number between 1 and 5 " cin gtgt
number switch (number) case 0 cout ltlt
"Too small, sorry!" break case 3 cout ltlt
"Excellent!\n" //falls through case 2 cout ltlt
"Masterful!\n" //falls through case 1 cout ltlt
"Incredible!\n" break default cout ltlt "Too
large!\n" break cout ltlt "\n\n"
return 0
Only accept number or expression that returns a
number
Note the differences between break and no break
Do default if all tests fail
65Implement switch with if else
- switch case statement can be implemented by the
if else statement but with more complicated
structure
- However, switch case can only be applied to
data value tests
if (num 0) cout ltlt "Too small,
sorry!" else if (num 3 num 2 num
1) cout ltlt "Incredible!\n" if
(num 3 num 2) cout ltlt
"Masterful!\n" if (num 3)
cout ltlt "Excellent!\n" else
cout ltlt "Too large!\n"
66Looping
- Many programming problems are solved by
repeatedly acting on the same data - The method for achieving repeated execution is by
looping - 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
67while Loop
- while loops do the looping until the testing
condition fails
include ltiostreamgt using namespace std int
main() int counter 0 //initialize
counter while (counterlt5) counter //top
of the loop cout ltlt "counter " ltlt counter ltlt
"\n" cout ltlt "Complete. Counter " ltlt
counter ltlt ".\n" return 0
Test condition (tested variable must change
inside the loop)
5
Repeat this part until counter gt 5
68More complicated while Loop
- while loops can be used with a more complicated
testing condition
include ltiostreamgt using namespace std int
main() unsigned long small, large unsigned
short const MAXSMALL 65535 cingtgtsmall
cingtgtlarge while (small lt large large gt 0
small lt MAXSMALL) if (small 5000
0) cout ltlt ".\n" // write a dot every
5000 small large - 2 return 0
3 tests for each loop
Testing parameters are updated in every loop
69do 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 ltiostreamgt using namespace std int
main() int counter cout ltlt "How many hellos?
" cin gtgt counter do cout ltlt
"Hello\n" counter-- while (counter gt
0) cout ltlt "Counter is " ltlt counter ltlt
endl return 0
Hello will be shown at least once even if the
user enters 0 for counter
70for loop
- In many loops, we initialize a testing parameter,
test the parameter, and modify the value of the
parameter AFTER doing the processing. - It can be done in a single line by a for loop
include ltiostreamgt using namespace std int
main() int counter for (counter0
counterlt5 counter) cout ltlt "Looping! "
//counter then increment cout ltlt "\nCounter "
ltlt counter ltlt ".\n" return 0
Initialize
Modify
Test
5
71Different varieties of for loops
include ltiostreamgt using namespace std int
main() for (int i0, j0 ilt3 i,
j) cout ltlt "i " ltlt i ltlt " j " ltlt j ltlt endl
return 0
Multiple initialization and increments
include ltiostreamgt using namespace std int
main() int counter 0 for ( counter lt
5) counter//BEFORE coutltlt"Looping! "
cout ltlt "\nCounter " ltlt counter ltlt
".\n" return 0
Null initialization and increments
72Different varieties of for loops
include ltiostreamgt using namespace std int
main() int counter 0 // initialization
int max cout ltlt "How many hellos?" cin
gtgt max for () // a for loop that doesn't
end if (counter lt max) // test cout
ltlt "Hello!\n" counter //
increment else break //end for loop
return 0
Empty for loop
73continue 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 ltiostreamgt using namespace std int
main() int counter for (counter0
counterlt5 counter) cout ltlt "Looping!
counter is " ltlt counter ltlt"\n" if ((counter2)
1) //odd number continue cout ltlt
"Counter is an even number.\n" return
0
Execution of continue will skip the following
part of the loop but NOT leaving the loop
74Nested for loops
include ltiostreamgt using namespace std int
main() int rows, columns, i, j char
theChar cout ltlt "How many rows? " cin gtgt
rows cout ltlt "How many columns? " cin gtgt
columns cout ltlt "What characters? " cin gtgt
theChar for (i0 iltrows i) for (j0
jltcolumns j) cout ltlt theChar cout ltlt
"\n" return 0
Ex 3.4
More explanation on next page
Nested for loop
Will be executed (rows ? columns) times
75for (i0 iltrows i) for (j0 jltcolumns
j) cout ltlt theChar cout ltlt "\n"
Assumption rows 2 columns 3 theChar a
Values of i, j
i 0 j ?
i 1 j 3
Output on the screen
i 0 j 0
i 1 j 0
i 0 j 1
i 1 j 1
i 0 j 2
i 1 j 2
i 0 j 3
i 1 j 3
i 2 j 3
76- 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 Visual Studio .NET 2003.
77Exercise 3.4
Ex 3.5
For the program on p. 74 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?
p. 74
783.5 Functions
79Functions - 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 on
the next line of the calling function.
input
output
funcA() Statements return
Callingfunc() Statements funcA()
Statements funcB() Statements
funcB() Statements return
80Function Body
type of input parameters
return type
function name
unsigned short int FindArea (int length, int
width)
// Opening brace Statements return
(return_value) // Closing brace
name of input parameters
return value
81Ex 3.5
Why do we need functions?
Reason 1
- Functions help us shorten our program by re-using
the program codes.
include ltiostreamgt using namespace std void
floatDiv(int x, int y) float a
(float)x float b static_castltfloatgt(y) f
loat c a/b cout ltlt "c " ltlt c ltlt 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
82- The same program will be much longer without
calling functions - Can be even longer if the same operation is done
in other parts of the program.
int main() int w 7, x 5, y 3, z 2
float a, b, c a (float)w b
static_castltfloatgt(x) float c a/b cout
ltlt "c " ltlt c ltlt endl a (float)x b
static_castltfloatgt(y) float c a/b cout
ltlt "c " ltlt c ltlt endl a (float)y b
static_castltfloatgt(z) float c a/b cout
ltlt "c " ltlt c ltlt endl return 0
16 lines
83Reason 2
- Functions make our program much easier to read
- 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.
void floatDiv(int x, int y) float a
(float)x float b static_castltfloatgt(y) f
loat c a/b cout ltlt "c " ltlt c ltlt endl int
main() int w 7, x 5, y 3, z
2 floatDiv(w,x) floatDiv(x,y) floatDiv(y,z)
return 0
84Declaring Functions
Function prototype
- In C, anything that is not a part of the C
language needs to be declared - However, a function need NOT be separately
declared if it is placed before the functions
that will call it.
include ltiostreamgt using namespace std void
DemoFunction() cout ltlt "In Demo
Function\n" int main() cout ltlt "In
main\n" DemoFunction() cout ltlt "Back in
main\n" return 0
- Since DemoFunction() is placed before main(), it
need NOT be separately declared - DemoFunction() can be used directly.
85- 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 one should be placed first?
86- 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 Prototype
unsigned short int FindArea(int, int)
return type
function name
type of input parameters
87Declaring Functions
include ltiostreamgt using namespace std int
Area(int length, int width) // function
prototype int main() int lengthOfYard int
widthOfYard int areaOfYard cout ltlt "\nHow
wide is your yard? " cin gtgt widthOfYard cout
ltlt "\nHow long is your yard? " cin gtgt
lengthOfYard areaOfYard Area(lengthOfYard,widt
hOfYard) cout ltlt "\nYour yard is " cout ltlt
areaOfYard cout ltlt " square feet \n\n" return
0 int Area(int yardLength, int
yardWidth) return yardLength yardWidth
Although it is not necessary, adding the name of
the parameters makes the prototype easier to read
Area() is defined after main(). Note the name of
the parameters need NOT be the same as the
prototype
88Ex 3.5
Assume the file area.h has the following
statement and is at the same folder as main()
int Area(int length, int width) // function
prototype
include ltiostreamgt include "area.h" // function
prototype using namespace std int
main() areaOfYard Area(lengthOfYard,widthOf
Yard) return 0 int Area(int yardLength,
int yardWidth) return yardLength yardWidth
It is equivalent to place the content of area.h
to here
89Function 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
- 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.
One line of include Vs many lines
In different .cpp files
90Ex 3.4
Exercise 3.5
P.81
- For the program on p.81, add the function
prototype such that we can place the function
floatDiv() after main() - Modify the program you've developed in 1) as
follows - Remove the function prototype
- 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.88 - Achieve the same result as 1).
P.88
913.6 Variables of Functions
92- 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 - 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?
93Local Variables
include ltiostreamgt using namespace std float
Convert(float) //function prototype int
main() float TempFer float TempCel
10 TempFer 100 TempCel Convert(TempFer)
cout ltlt TempCel ltlt endl return 0 float
Convert(float Fer) float Cel Cel ((Fer -
32) 5) / 9 return Cel
- A function can define local variables for
temporary use.
- Local variables are only visible within the
function defining them.
94- Cel in main()is different from the Cel in
Convert() although their names are the same.
include ltiostreamgt using namespace std float
Convert(float) int main() float
TempFer float Cel 10 TempFer 100 Cel
Convert(TempFer) cout ltlt Cel ltlt endl return
0 float Convert(float Fer) float Cel Cel
((Fer - 32) 5) / 9 return Cel
- Actually for each function, a separate piece of
memory is allocated to the local variables of
each function, disregarding their name.
95include ltiostreamgt using namespace std float
Convert(float) int main() float
TempFer float Cel 10 TempFer
100 CelConvert(TempFer) cout ltlt Cel ltlt
endl return 0
float Convert(float Fer) float Cel Cel
((Fer - 32) 5) / 9 return Cel
Variables
Memory
37.7
96Parameter 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.
97Global Variables
include ltiostreamgt using namespace std int
Convert(float) //function prototype
changed float Cel // Global variable int
main() float TempFer cout ltlt "Please enter
the temperature in Fahrenheit " cin gtgt
TempFer Convert(TempFer) //No need to collect
the return value cout ltlt "\nHere's the
temperature in Celsius " cout ltlt Cel ltlt
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.
98Scope 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 ltiostreamgt using namespace std void
myFunc() int x 8 cout ltlt "\nIn myFunc,
local x " ltlt x ltlt endl cout ltlt "\nIn
block in myFunc, x is " ltlt x int x 9
//This x is not the same as the previous x cout
ltlt "\nVery local x " ltlt x cout ltlt
"\nOut of block, in myFunc, x " ltlt x ltlt
endl int main() myFunc() return 0
Be careful!
x 8
x 8
x 9
x 8
99Default 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'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.
100Default Parameters
You may use other names
include ltiostreamgt 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 ltlt "First volume equals "
ltlt volume ltlt "\n" volume volumeCube(length,
width) cout ltlt "Second volume equals " ltlt
volume ltlt "\n" volume volumeCube(length) cou
t ltlt "Third volume equals " ltlt volume ltlt
"\n" return 0 int volumeCube(int length,
int width, int height) return
(lengthwidthheight)
volume 100 502 10000
volume 100 501 5000
volume 100 251 2500
Once a default value is assigned, the parameters
following must have default values.
101Overloading 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)
- 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
3 different functions
Differ by just the return type is NOT allowed
102include ltiostreamgt using namespace std int
intDouble(int) float floatDouble(float) int
main() int myInt 6500, doubledInt float myFl
oat 0.65, doubledFloat doubledInt
intDouble(myInt) doubledFloat
floatDouble(myFloat) cout ltlt "doubledInt " ltlt
doubledInt ltlt "\n" cout ltlt " doubledFloat "
ltlt doubledFloat ltlt "\n" return 0 int
intDouble(int original) return
2original float floatDouble(float
original) return 2original
- 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
103include ltiostreamgt using namespace std int
Double(int) float Double(float) int
main() int myInt 6500, doubledInt float myFl
oat 0.65, doubledFloat doubledInt
Double(myInt) doubledFloat Double(myFloat) c
out ltlt "doubledInt " ltlt doubledInt ltlt
"\n" cout ltlt " doubledFloat " ltlt doubledFloat
ltlt "\n" return 0 int Double(int
original) return 2original float
Double(float original) return 2original
Ex 3.6c
Overloading
104Exercise 3.6a
void myFunc() int x 8 cout ltlt "\nIn
myFunc, local x " ltlt x ltlt endl cout ltlt
"\nIn block in myFunc, x is " ltlt x int x
9 cout ltlt "\nVery local x " ltlt x
cout ltlt "\nOut of block, in myFunc, x " ltlt x ltlt
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 ltiostreamgt using namespace std void
myFunc() int main() myFunc() return 0
105Exercise 3.6b
A for loop is used instead as follows
void myFunc() int x 8 cout ltlt "\nIn
myFunc, local x " ltlt x ltlt endl for (int x
10 xgt0 x--) cout ltlt "\nInside for loop x "
ltlt x cout ltlt "\nIn block in myFunc, x is "
ltlt x ltlt 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.
106Exercise 3.6c
P. 103
Based on the program in p. 103, 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.
107Acknowledgments
- The slides are based on the sets developed by Dr.
Frank Leung (EIE) and Dr Rocky Chang (COMP).