Date post: | 17-Jan-2016 |
Category: |
Documents |
Upload: | drusilla-bailey |
View: | 214 times |
Download: | 0 times |
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 1 -
Building BlocksBuilding Blocks
Overview
In this lesson
• We will study the basic building blocks of a C++ program
• Explore data types that are part of the C++ language
• Look at basic arithmetic operators
• Begin our study of functions
• We will write some functions
To use data the user can enter into our
program
Return computed results
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 2 -
Building Blocks
Fundamental Data
Identifiers in C++
The name of object or function in C++ is called an identifier
Gives us means to refer to an entity in program
Such an entity may be a Variable Function
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 3 -
Building Blocks
Identifiers
Any combination of symbols can be used as an identifier, but….
The C++ standard establishes some restrictions
An identifier is case-sensitive
The first character of an identifier must be an alphabetic character or an underscore
Identifiers cannot be a C++ keyword
Identifiers have no length limit
An identifier is case-sensitive
The first character of an identifier must be an alphabetic character or an underscore
Identifiers cannot be a C++ keyword
Identifiers have no length limit
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 4 -
Building Blocks
IdentifiersSimple Variables
A variable is an object we use to hold data; it’s also an identifier
It has a name
The name let’s us refer to it in our program
It has a type
Tells us how big the variable is
Types are kind of like barrels
We have a number of different types or sizes of barrels
1, 2, 5, 10, 50 gallon containers
Should be immediately obvious
Putting contents of a 50 gal barrel into a 1 gal barrel is problem
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 5 -
Building Blocks
Identifiers
Intrinsic Types
Look around real world and we see we have a number of
different units we measure by….
– Inches, feet, yards, miles
– Centimeters, meters, kilometers
– Gram, kilograms, etc.
These are standards; They are intrinsic units of measure
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 6 -
Building Blocks
Identifiers
Intrinsic Types
C++ does same thing…just not with barrels
We have number of standard numeric types to hold stuff
These are predefined variables of different sizes
Such numeric types are called the intrinsic types,
The intrinsic types are classified into two groups
Integer Types
Floating Point Types
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 7 -
Building Blocks
Identifiers
Integer Types
Integer types are whole numbers ….They have no fractional part
25, -6, 100, 83, -972….
The C++ language standard defines the following integer types
char
short
int
long
bool
char
short
int
long
bool
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 8 -
Building Blocks
Identifiers
Integer Types
May be signed or unsigned … By default all are signed except
bool
A signed integer can be either positive or negative – Unsigned integer can only be positive
Signed Integerssigned int aNumber = -25;
or
int aNumber = -25;
Unsigned Integersunsigned int aNumber = 15;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 9 -
Building Blocks
Identifierschar Integer Type
We represent characters by assigning a value to a char
char x = ‘A’; // Preferred
char y = 65; // Assigning numeric ASCII value
We denote a char type by enclosing a character in single quotes
This line of code will display the letter M on the screen.
cout << 'M' << endl;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 10 -
Building Blocks
When I Say 0….
There is difference between 0 and '0'
0 is integer zero…that is, all bits are 0
A char integer with a value of zero is often referred to as a
null character
On the other hand the ASCII '0' has a value of 48
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 11 -
Building Blocks
Identifiersbool Integer Type
bool integer type can contain only two values…..
zero (false) or one (true)
To express conditions for success or failure of some test
We might write
bool pass = true;
bool fail = false;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 12 -
Building Blocks
How Big is Big…The Size of Integer Types
Each of the integer types requires different amount of memory to
store its value
• The smaller the size of the variable
…..Fewer bits allocated to store it
…..Smaller the value it can hold
• Sizes of integer types varies by computer and operating system
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 13 -
Building Blocks
How Big is Big…The Size of Integer Types
#include <iostream>
using namespace std;
int main(void)
{
// checking sizes
cout << "A char is " << sizeof(char) << " byte" << endl;
cout << "A short is " << sizeof(short) << " bytes " << endl;
cout << "A int is " << sizeof(int) << " bytes" << endl;
cout << "A long is " << sizeof(long) << " bytes" << endl;
cout << "A bool is " << sizeof(bool) << " byte" << endl;
return 0;
}
#include <iostream>
using namespace std;
int main(void)
{
// checking sizes
cout << "A char is " << sizeof(char) << " byte" << endl;
cout << "A short is " << sizeof(short) << " bytes " << endl;
cout << "A int is " << sizeof(int) << " bytes" << endl;
cout << "A long is " << sizeof(long) << " bytes" << endl;
cout << "A bool is " << sizeof(bool) << " byte" << endl;
return 0;
}
A char is 1 byte
A short is 2 bytes
A int is 4 bytes
A long is 4 bytes
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 14 -
Building Blocks
How Big is Big…The Size of Integer Types#include <iostream>
#include <limits>
using namespace std;
int main(void)
{
cout << CHAR_MAX << endl; //displays char maximum
cout << CHAR_MIN << endl; //displays char minimum
cout << SHRT_MAX << endl; //displays short maximum
cout << SHRT_MIN << endl; //displays short minimum
cout << INT_MAX << endl //displays int maximum
cout << INT_MIN << endl; //displays int minimum
cout << LONG_MAX << endl; //displays long maximum
cout << LONG_MIN << endl; //displays long minimum
return 0;
}
#include <iostream>
#include <limits>
using namespace std;
int main(void)
{
cout << CHAR_MAX << endl; //displays char maximum
cout << CHAR_MIN << endl; //displays char minimum
cout << SHRT_MAX << endl; //displays short maximum
cout << SHRT_MIN << endl; //displays short minimum
cout << INT_MAX << endl //displays int maximum
cout << INT_MIN << endl; //displays int minimum
cout << LONG_MAX << endl; //displays long maximum
cout << LONG_MIN << endl; //displays long minimum
return 0;
}
127
-128
32767
-32768
2147483647
-2147483648
2147483647
-2147483648
127
-128
32767
-32768
2147483647
-2147483648
2147483647
-2147483648
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 15 -
Building Blocks
Floating Point Types
With an integer type, the size of number we can express is
determined by number of bits in integer
Early PCs had integers containing 16 bits which meant that the
largest integer number that could be expressed was 65,536
Clearly we need to represent large numbers in a computer….
...Have to keep track of national debt after all
To do so we use different data type called floating point type
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 16 -
Building Blocks
Floating Point TypesConsider the number 3500….
We can easily rewrite this as 0.35 x 10000
Next we rewrite 10000 as 10*10*10*10 or 104
Thus the original number becomes 0.35 x 104
We call the 0.35 the fractional part or mantissa and
The 104 the exponent part
When number expressed in such a format, we say we’re using a
floating-point format
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 17 -
Building Blocks
Floating Point Types
C++ language standard specifies two floating-point types
float
double
• Each of these types contains the same maximum exponent • Double has more significant figures to the right of the decimal
point
– There is even a long double -
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 18 -
Building Blocks
Floating Point TypesFloating-point constants by default are of size double.
If we write
float pi = 3.14159;
We get truncation warning
We can avoid the warning by directing the compiler to create
3.14159 as a float and not a double.
float pi = 3.14159f;
or
float pi = 3.14159F;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 19 -
Building Blocks
The const Qualifier
Consider the two declarations and initializing values….
int legalPaperLength = 17;
int standardPaperLength = 11;
Now let these two variables be assigned alternate values…
legalPaperLength = 14;
standardPaperLength = 10;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 20 -
Building Blocks
The const Qualifier
C++ language gives us the ability to make the contents of a variable
constant
We use the const qualifier when we define the variable
Thus, when we declare the variables and we write
const int legalPaperLength = 17;
const int standardPaperLength = 11;
If we now try…..problemlegalPaperLength = 14;
standardPaperLength = 10;
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 21 -
Building Blocks
Functions
Let’s now take first look at the other kind of C++ identifier
Function
A C++ program is simply collection of functions
Some functions are pre-defined
We call these library functions
Most functionsUser defined
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 22 -
Building Blocks
Functions
As we write larger programs...
Will need to write more functions
More sophisticated functions
We write such functions to decompose program into more manageable pieces
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 23 -
Building Blocks
Functions
We create a function by defining it
Defining a function involves providing
Function header
Function Body
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 24 -
Building Blocks
FunctionsFunction Header
Specifies
Function name
Return type
Parenthesized parameter list
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 25 -
Building Blocks
Functions
Function Header
Function Name
Each function has a Name that is used to identify the function
The name should be descriptive of what the function does
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 26 -
Building Blocks
FunctionsFunction Header
Argument or Parameter List Arguments enclosed in parentheses Appear after the function name Separated by commas
Parentheses and the arguments
Called the argument list
Signature of the function Number, type, and order of arguments
Called the signature
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 27 -
Building Blocks
Functions
Function Header
Return Type
Return data from a function using a C++ return
statement
When a value is returned from a function using the return statement the function is said to have a return value
Kind of data returned called the return type.
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 28 -
Building Blocks
Functions
Function Body
Series of C++ instructions
Enclosed in curly braces
These express the function body
This is where the real work gets
done
Thus we have…
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 29 -
Building Blocks
Functions
returnType functionName ( arg0, arg1…argn-1 )
{
body
}
int multiply(int first, int second)
{
// this is the function body
}
returnType functionName ( arg0, arg1…argn-1 )
{
body
}
int multiply(int first, int second)
{
// this is the function body
}
Function Body
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 30 -
Building Blocks
FunctionsUsing a Function
Using a function is called
Executing
Evaluating
Invoking
Calling A function is executed
By performing a function call The function performing the function call
Is the calling function The function being executed
Is the called function
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 31 -
Building Blocks
Functions
In C++ all functions created equal…..
…..Any function can call any other function
Recall the simple program
int main(void)
{
// statements to execute go here
return 0;
}
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 32 -
Building Blocks
Functions
Let’s consider the multiply function we described above
We can write the function body such that
It is able to multiply the first and second argument
Return the product
We might ask... How do we call the function? How do we pass in the numbers to be multiplied? How do we use the product that is returned?
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 33 -
Building Blocks
Functions
#include <iostream>
using namespace std;
int multiply(length, width); // function prototype
int main()
{
// declare some variables
int length = 10;
int width = 20;
int area;
area = multiply(length, width); // the function call
cout << area << endl; // displays 200
return 0;
}
#include <iostream>
using namespace std;
int multiply(length, width); // function prototype
int main()
{
// declare some variables
int length = 10;
int width = 20;
int area;
area = multiply(length, width); // the function call
cout << area << endl; // displays 200
return 0;
}
int multiply(int first, int second)
{
int answer;
answer = first * second;
return answer;
}
int multiply(int first, int second)
{
int answer;
answer = first * second;
return answer;
}
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 34 -
Building Blocks
Functions
Function PrototypesIf we look back at the example program….
We see line near top of the program
#include <iostream>
using namespace std;
int multiply(length, width);
The line that looks like the function header is important
Called function prototype
Functions need to be known before they can be used
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 35 -
Building Blocks
Functions
You might ask why we need this ????
Doesn’t the function header provide same information
Let’s see what’s going on here…..
When compiler encounters a function
It needs to know how to process it
It needs the information contained in header
To keep compiler happy
It’s sufficient to declare the function
If declaration not present we get a compile error
We declare a function by listing
return type function name (parameters)
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 36 -
Building Blocks
FunctionsNesting Functions
When one function used inside a second function
It’s called nesting
Now, a good question
How deeply can we nest functions????
Accompanying figure shows
Functions nested 4 deep
myF0()
myF1()
myF2()
myF3()
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 37 -
Building Blocks
FunctionsHow deeply can we nest functions????
Our question has a relative answer…..
We know the compiler
Makes copies of the variables it uses for arguments
Destroys the copies when the function completes
Seems reasonable that all copies hang around (on the stack)
Until the most deeply nested function call completes
When we run out of the stack memory our program will crash
Amount of stack memory varies with operating systems
Usually adjustable if needed
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 38 -
Building Blocks
Functions
Return ValueIn our study of functions we’ve observed the prototype
specifies
return type
We now ask question,
Do all functions have return value?????
The answer is no
void displayAnswer(int answer)
{
cout << "The answer is: " << answer << endl;
return; // this return is optional but is included // for clarity and completeness
}
void displayAnswer(int answer)
{
cout << "The answer is: " << answer << endl;
return; // this return is optional but is included // for clarity and completeness
}
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 39 -
Building Blocks
Functions
Now we use displayAnswer() in our example C++ program:
#include <iostream>using namespace std;int multiply(length, width);int main(){
// declare some variablesint length = 10;int width = 20;int area;
area = multiply(length, width); // the function calldisplayAnswer(area) // displays: The answer is 200return 0;
}
#include <iostream>using namespace std;int multiply(length, width);int main(){
// declare some variablesint length = 10;int width = 20;int area;
area = multiply(length, width); // the function calldisplayAnswer(area) // displays: The answer is 200return 0;
}
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 40 -
Building Blocks
Functions
Library FunctionsIn addition to our own functions….
….Many functions we will use are in libraries
A library is pre-compiled code and usually comes with your
compiler
To use a library function we include the proper header file
The header file contains the function prototype
This satisfies the compiler
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 41 -
Building Blocks
Arithmetic Operators
C++ uses operators to perform arithmetic operations on
variables.
Operators are the same for both integer and floating-point
Basic C++ operators are:
+ add
- subtract
/ divide
* multiply
…and they work as you would expect
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 42 -
Building Blocks
Arithmetic Operators
Operator Precedence
Let’s declare some variables…. e variablesint a = 20;
int b = 25;
int c;
Then write
c = a * 2/b + 15;
However, if we include these four lines of code in a program
Then compile and run it….
We will print the number 16 will appear
Why did that happen?
Variable c is
a times 2
divided by b
plus 15
Which is really 40 divided by 40
We expect the variable c to be 1
Variable c is
a times 2
divided by b
plus 15
Which is really 40 divided by 40
We expect the variable c to be 1
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 43 -
Building Blocks
Arithmetic OperatorsOperator Precedence
The answer lies in a concept we call operator precedence
Operators in C++ are evaluated in a specific order
Based upon precedence …..
For this example the compiler will
Perform division before addition
Perform multiplication before division
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 44 -
Building Blocks
Arithmetic Operators
Operator Precedence
In the light of precedence
1. a is multiplied by 2
Because multiplication comes before division or addition
This is 20 times 2 which is 40.
2. Next 40 is divided by b
Because division comes before addition
This is 40 divided by 25 which is 1.6
3. Finally, 15 is added to 1
To give 16
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 45 -
Building Blocks
Arithmetic Operators
Operator Precedence
If we wish evaluation to proceed in different order, we
can over
ride the precedence using parentheses
To force b plus 15 to be done before the division….
….We enclose those terms in parentheses
c = a * 2/ (b + 15);
Doing this changes evaluation order because the grouping
parentheses operator comes before any arithmetic operator
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 46 -
Building Blocks
Arithmetic Operators
Operator AssociativityNow we ask….
If precedence determines which operator is applied first,
What happens when all of the operators in a line of code
Have the same precedence?????
a + b – c
Does the compiler evaluate a + b or b – c first?
The answer is associativity subtraction
According to the C++ Operator Precedence and Associativity table
The associatively of addition and subtraction is Left to Right
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 47 -
Building Blocks
Arithmetic OperatorsInteger Division
For our example the answer will be 1. Why?????
Integers do not have fractional parts
Because the two operands are integers….
The compiler expresses result (1.6) as an integer
Which is 1 since 0.6 can't be expressed as integer
int x = 40;
int y = 25;
x = x / y;
cout << x << endl
int x = 40;
int y = 25;
x = x / y;
cout << x << endl
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 48 -
Building Blocks
Arithmetic Operators
The Modulus Operator %
We’ve seen integer division gives us Whole number part Remainder part
…and the remainder part disappears
If we want the remainder portion we must use an operator
Called the modulus operator
Written as percent sign
%
Also called remainder operator
Copyright 2001 Oxford Consulting, Ltd
1 January 2001
- 49 -
Building Blocks
Arithmetic Operators
The Modulus Operator %Let’s apply the mod operator to the following integer
int number = 15;
cout << number % 3 << endl; // prints 0 …3 divides 15
// 5 times with 0 remainder
cout << number % 5 << endl; // prints 0 …5 divides 15
// 3 times with 0 remainder
cout << number % 10; << endl; // prints 5 …10 divides 15
// 1 time with 5 remainder
cout << number % 2; << endl; // prints 1 …2 divides 15 7
// times with 1 remainder