Programming in C++: A C++ Program Is A Collection of One or More
Programming in C++: A C++ Program Is A Collection of One or More
Programming in C++: A C++ Program Is A Collection of One or More
Computer Programming
3. The Nuts and Bolts of C++
Programming in C++
z
z
z
z
Computer Programming
3. The Nuts and Bolts of C++
Computer Programming
3. The Nuts and Bolts of C++
preprocessor
preprocessor
int main()
{
std::cout << "Hello World!"
<< std::endl;
return 0;
}
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
Computer Programming
3. The Nuts and Bolts of C++
Preprocessor
#include <iostream>
Computer Programming
3. The Nuts and Bolts of C++
Program Codes
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
Computer Programming
3. The Nuts and Bolts of C++
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 " "
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;
}
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++
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
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
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++
21
Computer Programming
3. The Nuts and Bolts of C++
Function Definition
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>
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
Computer Programming
3. The Nuts and Bolts of C++
#include <iostream>
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>
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.
// 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++
main()
return c
29
Computer Programming
3. The Nuts and Bolts of C++
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
int i = 45;
i
45
int
36443
4 bytes
variable
value
datatype
address
size
33
Computer Programming
3. The Nuts and Bolts of C++
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
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
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;
38
Computer Programming
3. The Nuts and Bolts of C++
Variable Initialization
z
39
Computer Programming
3. The Nuts and Bolts of C++
40
Computer Programming
3. The Nuts and Bolts of C++
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
43
Computer Programming
3. The Nuts and Bolts of C++
44
What it Means
new line
tab
backspace
double quote
single quote
bell
backslash
#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
46
1.2F
1.2
1.2L
Computer Programming
3. The Nuts and Bolts of C++
Exponential Notation
z
10-3
10-4
6.25E-4
47
#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
49
Computer Programming
3. The Nuts and Bolts of C++
studentPerClass
87
50
Computer Programming
3. The Nuts and Bolts of C++
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";
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};
Another example
enum COLOR2 {RED=100, BLUE, GREEN=500, WHITE, 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";
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;
57
Computer Programming
3. The Nuts and Bolts of C++
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
(addition)
(division)
(subtraction)
(modulus, remainder)
* (multiplication)
(no ** )
(no + )
Example:
(x=1 + 4 -7 = -2)
(x= 1)
(x= -1)
(x=3)
(x= 1, remainder)
(y=5.75)
Ans: -2 -2 2
59
Computer Programming
3. The Nuts and Bolts of C++
Rule #1
char, short
float
60
int
double
Computer Programming
3. The Nuts and Bolts of C++
61
Computer Programming
3. The Nuts and Bolts of C++
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;
c = c / 5;
c /= 5;
// since it is meaningless
// a = 5, c = 6
a=c; c=c+1;
a = ++c;
// a = 6, c = 6
c=c+1; a=c;
63
Computer Programming
3. The Nuts and Bolts of C++
// x = 29
64
// x = 5 * (5 + 6) = 55
Computer Programming
3. The Nuts and Bolts of C++
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;
//
//
//
//
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
67
Computer Programming
3. The Nuts and Bolts of C++
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
doSomeThing();
Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called??? NO
69
Computer Programming
3. The Nuts and Bolts of C++
doSomeThing();
Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called??? YES
doSomeThing();
Would
WoulddoSomeThing()
doSomeThing()
be
becalled???
called???
NO
70
Computer Programming
3. The Nuts and Bolts of C++
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++
//
//
//
//
if the cond
is true,
then do doA()
else do doB()
73
Computer Programming
3. The Nuts and Bolts of C++
Compound statement:
>= 60 )
"Passed.\n";
"Failed.\n";
"You must take this course again.\n";
the statement
cout << "You must take this course again.\n" ;
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++
return 0;
}
76
Computer Programming
3. The Nuts and Bolts of C++
Dangerous error
77
Computer Programming
3. The Nuts and Bolts of C++
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)
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++
80
Computer Programming
3. The Nuts and Bolts of C++
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
while loop
82
Computer Programming
3. The Nuts and Bolts of C++
while Loop
int count ;
count = 4;
// 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++
85
Computer Programming
3. The Nuts and Bolts of C++
Format:
do {
statement;
} while ( condition );
Example:
action(s)
true
condition
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++
initialization;
while ( loopContinuationTest ) {
statement;
increment;
}
z
88
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++
90
Computer Programming
3. The Nuts and Bolts of C++
91
Computer Programming
3. The Nuts and Bolts of C++
92
Computer Programming
3. The Nuts and Bolts of C++
break
continue
for
z
93
Computer Programming
3. The Nuts and Bolts of C++
continue Statement
while (expr) {
statement
continue;
skip 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;
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++
times
times
97
Computer Programming
3. The Nuts and Bolts of C++
=
=
=
=
=
=
=
=
=
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++
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
// 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++
Reason 1
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
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++
Which
Whichone
oneshould
should
be
beplaced
placedfirst?
first?
107
Computer Programming
3. The Nuts and Bolts of C++
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++
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++
113
Computer Programming
3. The Nuts and Bolts of C++
Variable Scope
z
z
z
z
114
Computer Programming
3. The Nuts and Bolts of C++
Variable Scope
Global variable
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
}
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++
119
Computer Programming
3. The Nuts and Bolts of C++
different
copies
120
Computer Programming
3. The Nuts and Bolts of C++
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
#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
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++
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
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;
}
#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;
}
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.