Chapter 1-8 Programming 2
Chapter 1-8 Programming 2
#include <iostream>
void main ()
{
std::cout << "HELLO WORLD\n ";
}
Cascading
Can have multiple << or >> operators in a single statement
std::cout << "Hello " << "there" << std::endl;
if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";
1
Pointers
Basic concept of pointers
Pointer declaration
Pointer operator (& and *)
Dynamic memory allocation
Pointers and Dynamic Memory
2
Basic Concept of Pointers
A pointer is a variable which directly points to a
memory address.
It allows programmer to directly manipulate the data
inside the memory.
So far, we have seen a variable is used to hold a value.
A pointer variable, however, does not hold a value,
instead holds an address of the memory which contain
the value.
3
Basic Concept of Pointers
Why would we want to use pointers?
To call a function by reference so that the
variable data passed to the function can be
changed inside the function.
To points to a dynamic data structure which
can grow larger or smaller as necessary.
To specify relationship among abstract data
structure linked list, tree, graphs, etc.
4
Basic Concept of Pointers cont…
A variable declaration such as,
int number = 20; causes the compiler to allocate a
memory location for the variable number and store in
it the integer value 20.
This absolute address of the memory location is readily
available to our program during the run time.
The computer uses this address to access its content.
number
number directly references a
20 a value which is 20
5
Basic Concept of Pointers Cont…
A pointer declaration such as,
int *numberptr; declares numberptr as a variable that
points to memory that holds an integer value. Its
content is not integer value but it is a memory
address.
The * indicates that the variable being defined
is a pointer.
In this sense, a variable named directly
references a value, however a pointer indirectly
references a value.
8
Pointer Declaration (con’t)
Consider the statements:
#include <iostream>
int main ( )
{
FILE *fptr1 , *fptr2 ; /* Declare 2 file pointers */
int *aptr ; /* Declare a pointer to an int */
float *bptr ; /* Declare a pointer to a float */
int a ; /* Declare an int variable */
float b ; /* Declare a float variable */
Pointer Operator (& and *)
To prevent the pointer from randomly pointing
to any memory addresses, it is advised to
initialize the pointer to 0 or NULL before being
used.
When a pointer is created, it is not pointing to
any valid memory address. Therefore, it is
necessary to assign with a variable’s address
by using the & operator. This operator is
called a reference operator.
After a pointer is assigned to a particular
address, the value in the pointed address can
be accessed using the * operator. This
operator is called a dereference operator.
10
Pointer Operator
(& and *)
11
Pointer Operator (& and *) Cont…
int *num_ptr, num = 9;
*num_ptr num
9
11111111 11001100
num_ptr = #
*num_ptr num
11001100 9
11111111 11001100
13
Pointer Operator (& and *) Cont…
E.g. Assume that the address of number is
11110000.
number 3
11110000
Declare a pointer
int *aPtr;
int *aPtr = null;
Assigning a pointer
aPtr = &aVar;
15
Write down the code to declare a pointer named
“Ptr” and assign that pointer to “Var”.
16
Draw a picture of memory after these statements:
int i = 42;
int k = 80;
int* p1;
int* p2;
p1 = &i;
p2 = &k;
17
Exercise
18
Question: Write a program to perform addition between two
numbers based on user’s input and display the output on
screen.
Sample output:
Question: Re-write the program to perform addition
between two numbers based on user’s input using Pointer
and display the output on screen
Sample output:
Pointers and Dynamic Memory
22
Dynamic Memory Allocation
In C++ programming, memory allocation is divided into
two parts:-
* The stack: All variables declared inside the function will take
up memory from the stack.
* The heap: This is unused memory of the program and can be
used to allocate the memory dynamically when program runs.
Basically, all memory needs were determined before
program execution by defining the variables needed.
But there may be cases where the memory needs of a
program can only be determined during runtime.
For example, when the memory needed depends on user
input.
On these cases, C++ programs need to dynamically
allocate memory and make use of the dynamic variables.
Dynamic Variables
Variables that can be created and destroyed during
program execution.
• Many times, you are not aware in advance how much memory you will
need to store particular information in a defined variable and the size of
required memory can be determined at run time.
24
Obtaining Dynamic Memory with
new
new operator: dynamically allocate (i.e. reserve) the exact
amount of memory required to hold an object or array at
execution time.
25
Obtaining Dynamic Memory with
new
Consider the following statement:
Time *timePtr = new Time
26
Obtaining Dynamic Memory with
delete
delete operator: To return memory to the free store use
the delete operator to deallocate (i.e. release) it.
27
Pointers and Dynamic Memory
Storage for these variables comes from an area of memory
called the free store or the heap.
Examples:
31
Pointers and Dynamic Memory
The new operator gets memory from the free store (heap).
If the pointer points to an array of objects, the statement first calls the
destructor for every object in the array, then deallocates the memory.
Using delete on a null pointer (i.e., a pointer with the value 0) has no
effect.
Pointers and Dynamic Memory
33
Sample Program
34
SUMMARY
This chapter has exposed you about:
Pointer variables and parameter passing by reference/
pointers
The usage of symbol * and address operator (&)
Passing by pointers allows us to return multiple values
from functions
Function returns a pointer
35
CHAPTER 3
FUNCTION AND
PROGRAM STRUCTURE
1
Functions and Program Structure
Introduction to function
Standard functions
User defined functions
Function passed by value and reference
Storage classes
Function Overload
Modularity
2
Introduction to Functions
A function is a block of code which is used to perform
a specific task.
It can be written in one program and used by another
program without having to rewrite that piece of code.
Functions can be put in a library. If another program
would like to use them, it will just need to include
the appropriate header file at the beginning of the
program and link to the correct library while
compiling.
A function is used by calling the name of the function.
3
Consider this example:
}
int GetScore(void);
void CalculateTotal(int);
Function prototypes
void PrintTotal(void);
int total = 0;
void main(void) {
int score;
for (count = 0; count < 10; count++) {
score = GetScore();
CalculateTotal(score); } Function calls
}
PrintTotal();
} 4
Cont…
The use of functions resembles a pseudocode.
Therefore we can easily convert steps in a
pseudocode into function calls.
Our code looks a lot neater and more readable
by using functions.
5
1 - Standard Functions
Standard functions are functions that have been pre-
defined by C++ and put into standard C++ libraries.
Example: std::cout(), std::cin(), rand(), etc.
What we need to do, to use them, is to include the
appropriate header files.
Example: #include <iostream>, #include <math.h>
Things that contained in the header files are the
prototypes of the standard functions.
The function definitions (the body of the functions) has been
compiled and put into a standard C++ library which will be
linked by the compiler during compilation
6
2 - User Defined Functions
A programmer can create his/her own function(s).
It is easier to plan and write our program if we divide it into
several functions instead of writing a long piece of code inside
the main function.
A function is reusable and therefore prevents us (programmers)
from having to unnecessarily rewrite what we have written
before.
In order to write and use our own function, we need to do
these:
create a function prototype
define the function somewhere in the program
call the function whenever it needs to be used
7
i - Function Prototype
A function prototype will tell the compiler that there
exist a function with this name defined somewhere
in the program and therefore it can be used even
though the function has not yet been defined at that
point.
Function prototypes need to be written at the
beginning of the program.
If the function receives some arguments, the
variable names for the arguments are not needed.
State only the data types.
8
i - Function Prototypes Cont…
Examples:
void Function1(void);
void Function2(int);
char Function3(char, int, int);
Function prototypes can also be put in a header file.
Header files are files that have an extension .h.
The header file can then be included at the beginning
of our program.
9
i - Function Prototypes Cont…
To include a user defined header file, type:
#include “header_file.h”
Notice that instead of using < > as in the case
of standard header files, we need to use “ ”.
This will tell the compiler to search for the
header file in the same directory as the
program file instead of searching it in the
directory where the standard library header
files are stored.
10
ii - Function Definitions
A function definition is where the actual code
for the function is written. This code will
determine what the function will do when it is
called it’s specific task.
A function definition has this format:
return_value FunctionName(function arguments) {
variable declarations;
statements;
}
11
ii - Function Definitions Cont…
The return value is a data that will be returned
by the functions. There can be only one return
value.
The function arguments is a list of data to be
passed to the function. The number of
arguments that can be passed is infinite.
In the example that we have seen earlier, 3
function prototypes has been declared. The
following are their definitions:
12
ii - Function Definitions Cont…
int GetScore(void) {
int temp; If the function has a return value,
cout<<“Enter the score:”; it needs to have a return statement
cin>> temp; at the end. Make sure the data type
return temp; is the same.
}
13
ii - Function Definitions Cont…
In the CalculateTotal() function, the function
takes only one argument. In the case where a
function takes more than one argument, each
arguments need to be separated by comas.
Make sure the data type for each arguments is
stated. For example:
void Calc(int a, int b, double c, char d) {
statements;
}
14
ii - Function Definitions Cont…
If the data type is not stated, for example:
void Calc(a, b, c, d) { }
Each of them (a, b, c, d) by default will be an
int. But, for the sake of good programming
style, please state the data type even though it
is an int.
Use the keyword void if no arguments will be
passed to or returned from the function (even
though it is perfectly okay not to write
anything).
15
iii - Function Call
A function is called by typing the name of the
function.
If the function requires some arguments to be
passed along, then the arguments need to be
listed in the bracket () according to the
specified order. For example:
void Calc(int, double, char, int);
void main(void) {
int a, b;
double c;
char d;
…
Calc(a, c, d, b);
}
16
iii - Function Call Cont…
If the function returns a value, then the returned value
need to be assigned to a variable so that it can be
stored. For example:
int GetUserInput(void);
void main(void)
{
int input;
input = GetUserInput();
}
However, it is perfectly okay (syntax wise) to just call
the function without assigning it to any variable if we
want to ignore the returned value.
17
iii - Function Call Cont…
Wecan also call a function inside another
function. For example:
18
Functions with Parameters
Two terms used:
Formal parameter
Variablesdeclared in the formal list of the
function header (written in function prototype &
function definition)
Actual parameter
Constants, variables, or expression in function
call that correspond to its formal parameter
19
Formal / Actual parameters
#include <iostream>
using namespace std;
Formal
int calSum(int, int); Parameters
void main(void) Actual
{ Parameters
int sum, num1, num2;
cout << "Enter two numbers to calculate its sum:" << endl;
cin >> num1 >> num2;
21
Exercise
What is the output?
int x = 3 , &y = x;
cout << “x = “ << x << “y = “ << y <<endl;
y = 7;
cout << “x = “ << x << “y = “ << y <<endl;
22
1 - Parameter passing by value
int function2(int, double, int);
void main()
{
int a, b, d;
double b;
. . .
d = function2(a, b, c);
. . .
}
int function2(int x, double y, int z)
{
int w;
. . .
return w;
}
23
Notes:
A function may
Receive no input parameter and return nothing
Receive no input parameter but return a value
Receive input parameter(s) and return nothing
Receive input parameters(s) and return a value
24
Example 1: receive nothing and return nothing
#include <iostream>
using namespace std;
void greeting(void)
{
cout << "Have fun!!" << endl;
}
25
Example 2: receive nothing and return a value
#include <iostream>
using namespace std;
int getInput(void);
int main(void)
{
int num1, num2, sum;
num1 = getInput( );
num2 = getInput( );
sum = num1 + num2;
int getInput(void)
{
int number;
cout << "Enter a number: ";
cin >> number;
return number;
}
26
Example 3: receive parameter(s) and return nothing
#include <iostream>
using namespace std;
int getInput(void);
void displayOutput(int);
int main(void)
{
int num1, num2, sum;
num1 = getInput();
num2 = getInput();
sum = num1 + num2;
displayOutput(sum);
return 0;
}
int getInput(void)
{
int number;
cout << "Enter a number: ";
cin >> number;
return number;
}
int main(void)
{
int sum, num1, num2;
cout << "Enter two numbers to calculate its sum: " << endl ;
cin >> num1 >> num2;
{
int sum;
sum = val1 + val2;
return sum;
}
28
Notes: Cont…
Three important points concerning functions
with parameters are: (number, order and type)
The number of actual parameters in a function call
must be the same as the number of formal
parameters in the function definition.
A one-to-one correspondence must occur among the
actual and formal parameters. The first actual
parameter must correspond to the first formal
parameter and the second to the second formal
parameter, an so on.
The data type of each actual parameter must be the
same as that of the corresponding formal parameter.
29
2 - Parameter Passing by
Reference
In previous chapter, you have learnt about a function
returns a single value.
But, for a function that returns multiple values must use
parameter passing by pointers. (It is so called as passed
by reference).
A pointer is a variable which directly points to a
memory address.
It allows programmer to directly manipulate the data
inside the memory.
So far, we have seen a variable is used to hold a value.
A pointer variable, however, does not hold a value,
instead holds an address of the memory which contain
the value.
30
2 - Parameter Passing by Reference
A function call by reference can be done by
passing a pointer to the function argument
(the same way as passing a normal variable to
the argument).
When the value referenced by the pointer is
changed inside the function, the value in the
actual variable will also change.
Therefore, we can pass the result of the
function through the function argument
without having to use the return statement. In
fact, by passing pointers to the function
argument, we can return more than one
value.
31
2 - Parameter Passing by Reference
Cont…
When a pointer is passed to a function, we are
actually passing the address of a variable to the
function.
Since we have the address, we can directly
manipulate the data in the address.
In the case where a non-pointer variable is
passed, the function will create another space in
memory to hold the value locally. Therefore,
any change to the variable inside the function
will not change the actual value of the variable.
32
2 - Parameter Passing by Reference
Cont…
To pass the value of variable by
pointers between two functions, we
must do the following:
1. Declare the variable that is meant to
return a value to the calling function as a
pointer variable in the formal parameter
list of the function.
void called_function(int *result);
2. When to call the function, use a variable
together with address operator (&)
called_function(&value_returned);
33
2 - Parameter Passing by Reference
Cont…
Note : the effect of the above two actions is the
same as the effect of the declarations
int value_returned;
int *result=&value_returned;
3. Declare the function with pointer
parameter appropriately in a function
prototype by using symbol * as a prefix
for pointer parameters.
void called_function(int*);
34
Function returns a pointer
#include <iostream>
using namespace std;
char *get_name();
int main() {
char *ptr = get_name();
cout << "Your name is: " << ptr << endl;
return 0;
}
char *get_name() {
char *name = new char[20];
cout << "Enter your name: ";
cin >> name;
return name;
}
35
PASS BY VALUE & REFERENCE
EXAMPLE
36
$ can also be used as an alias for one other
variable. However the alias must represent an
existing variable and is only dedicated to that
variable only for as long as the program is
executed. Or else syntax error will occur.
Chapter 2 : Function 38
Chapter 2 : Function 39
Chapter 2 : Function 40
41
Exercise
A taxpayer can determine his/her federal income tax by using the tax tables if the
taxable income is less than or equal to RM50,000. However, if taxable income
exceeds this amount, the taxpayer must use the tax rate schedule. Tax rate
schedule depend on filling status, which can be single, married filling jointly,
married filling separately and head of household. The following table summarizes
the tax rates for the year 2001.
42
Exercise
Modules:
1. entered_gross_income – to read and verify the
value typed by the user for income.
2. entered_filling_status – reads and verifies the
value provided for the variable filling_status
3. computed_tax – computes the federal income tax
using values for income and filling_status and
returns it to be saved in the variable tax.
4. output_result – values for income, filling_status
and tax are printed out on the screen.
43
Storage Classes
Each identifier in a program has attributes such as
storage class, storage duration, variable scope and
linkage.
C provides 4 storage classes indicated by the storage
class specifiers: auto, register, extern and static.
The 4 storage classes can be split into 2 storage
durations:
automatic storage duration
auto and register
44
Storage Classes Cont…
Variables with automatic storage duration are
created when the block in which they are
declared is entered, exist when the block is
active and destroyed when the block is exited.
The keyword auto explicitly declares variables of
automatic storage duration. It is rarely used
because when we declare a local variable, by
default it has class storage of type auto.
“int a, b;” is the same as “auto int a, b;”
45
Storage Classes Cont…
The keyword register is used to suggest to the
compiler to keep the variable in one of the
computer’s high speed hardware register.
However, it is also rarely used since compilers
nowadays are smart enough detect frequently
used variables to be put in a register.
Identifiers with static storage duration exist
from the point at which the program begin
execution.
46
Storage Classes Cont…
The static keyword is applied to a local variable so
that the variable still exist even though the program
has gone out of the function. As a result, whenever
the program enters the function again, the value in
the static variable still holds.
Continue where we left off – remember the last
value
The keyword extern is used to make an identifier
global. Global variables and function names are of
storage class extern by default.
47
Exercise: Identify Error 1
Chapter 2 : Function 48
Exercise: Identify Error 2
Chapter 2 : Function 49
Exercise: Identify Error 3
Chapter 2 : Function 50
Exercise: Identify Error 4
Chapter 2 : Function 51
Exercise: Identify Error 5
Chapter 2 : Function 52
Exercise: Identify Error 6
Chapter 2 : Function 53
Exercise
54
Question: Re-write the program to perform addition
between two numbers based on user’s input using Function
and display the output on screen
Question: Re-write the program to perform addition
between two numbers based on user’s input using
function call by Reference and display the output on
screen.
Function Overloading
Functions with same name and different
parameters
Functions should perform similar tasks
Function to square int and float
int square( int x) {return x * x;}
float square(float x) { return x * x; }
Program chooses function by signature
Signature determined by function name and
parameter types
Type safe linkage - ensures proper overloaded
function called
57
Chapter 2 : Function 58
First Variation
Second Variation
Third Variation
MODULAR PROGRAMMING
60
Standard Library
By using standard libraries, we are introducing
some modules into our application.
So, a modular program is modular because it
contains two or more programmer-defined
functions, because it uses some standard or
programmer-defined libraries, or both.
61
Programmer-defined Libraries
To enhance software reusability.
Need to identify some “general-purpose”
functions that are expected to use in
future in other projects.
62
Programmer-defined Libraries –
Step-by-step
1. Identify the reusable modules during the
design phase of software development.
2. Create header file (*.h file) that contains only
the declarations of functions, global
variables, named constant, typedefs, and
programmer-defined data types.
3. Create the implementation file (*.c file) of
general functions (function definitions) that
we declared in the header file.
63
Programmer-defined Libraries
Step-by-step
4. Create the application file (source file) to
solve a specific problem that use the general-
purpose functions.
Include the preprocessor directive
#include “header_file_name”
Include the preprocessor directive of other
standard libraries used by your program and/or by
the implementation file of general functions.
Write the function definitions of for the rest of
your program including main() function.
64
Programmer-defined Libraries
Step-by-step
5. Create a new project and insert into it the
application file and the implementation files.
Go ahead with compilation, linking and
executing the project.
65
Advantages of Using Programmer-
defined Libraries
Enhance module reusability.
Libraries make independent coding easier in
large-scale software development projects.
Simplify program testing and ensure reliable
functions.
Facilitate program maintenance.
Facilitate procedural abstraction and
information hiding.
Implementation files can be compiled
separately and can be used in their object form
in large-scale projects.
66
Example :Volumes.h
#define pi 3.142
67
Example Volumes.c
#include "Volumes.h"
69
SUMMARY
In this chapter, you have learnt:
Standard vs User Define functions
Function prototype, function definition and
function call
Formal vs Actual parameters
Value vs reference
Auto vs Static storage class
Function Overload
Modularity
70
CHAPTER 4
ARRAY
2
What is Array?
An array is a group of data with the same name and
data type located in contiguous logical memory.
The size of an array is static (fixed) throughout
program execution.
Fundamental data types – the compiler reserves a
memory location for the variable
char, int, double, float,
3
The position
Let say we have an array called A
starts from 0.
[2]
Multi-dimensional Arrays [1]
[0]
1 2
3 4 This array has 4 rows and 2
5 6 columns.
If you want to store values in any 3D array point first to table number,
then row number, and lastly to column number.
arr[0][1][2] = 32;
arr[1][0][1] = 49;
How to Declare an Array?
General syntax:
data_type array_name[size];
1D : type arrayName[arraySize];
2D : type arrayName[rowsize][columnsize];
3D : type arrayName[table][rowsize][columnsize];
Examples:
int my_array[100];
int a[27], b[10], c[76];
char abjad[3][4]; //array with 3 rows and 4 columns
int b[3][5][3]; //can be imagined we are declaring 3
tables of 5 rows and 3 columns each.
12
How to Initialize Array?
2. During execution: - array must be declared to be an
explicit number of size
int arr[3], j;
for (j = 0; j < 3; j++)
arr[j] = 0;
13
Example 1 : Declaring and
Initializing 2D array
Declaring and intializing a 5 by 2 array
with the values given.
15
Example 3: Using 1D Array
#include <iostream>
using namespace std;
#define SIZE 10
void main(void) {
int list[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int i, total = 0;
cout << "Total of array elements values is " << total << endl;
}
Output:
Total of array element values is 45.
int N[ 5 ][2] = { 1, 2; 3, 4; 5, 6; 7, 8; 9, 0; };
int N[ 5 ][2] = { 1, 2; 3, 4; 5, 6; 7, 8; 9, 0; };
Function call:
int marks[10] = {0,0,0,0,0,0,0,0,0,0};
get_marks(marks); /*pass array name*/
Function header:
void get_marks(int marks[])
{
……
28
}
Exercise 6
Program that receive age for n persons. n value
will be enter by the user. Then, create 3
functions as below:
void getAge(int[], int);
displayAge()
getTotalAge()
Sample output:
31
Bubble Sort Example
Sort a set of integers {23, 78, 45, 8, 32, 56}.
Step 1
23 23 23 23 23 23
78 78 45 45 45 45
OK
45 45 78 8 8 8
swap
8 8 8 78 32 32
swap
32 32 32 32 78 56
swap
56 56 56 56 56 78
swap
Bubble Sort Example (cont.)
Sort a set of integers {23, 78, 45, 8, 32, 56}.
Step 2
23 23 23 23 23
45 45 8 8 8
OK
8 8 45 32 32
swap
32 32 32 45 45
swap
56 56 56 56 56
OK
78 78 78 78 78
Bubble Sort Example (cont.)
Sort a set of integers {23, 78, 45, 8, 32, 56}.
Step 3
23 8 8 8
8 23 23 23
swap
32 32 32 32
OK
45 45 45 45
OK 8
56 56 56 56
78 78 78 78
Bubble Sort Example (cont.)
Sort a set of integers {23, 78, 45, 8, 32, 56}.
Step 4
8 8 8
23 23 23
OK
32 32 32
45 45 OK 45
8
56 8
56 8
56
78 78 78
Bubble Sort Example (cont.)
Sort a set of integers {23, 78, 45, 8, 32, 56}.
Step 5
8 8
23 23
OK
32 32
45 45
8
56 56
78 78
finished
Bubble Sort
In bubble sort, the list is divided into two sublists:
sorted and unsorted.
The smallest element is bubbled from unsorted
sublist and moved to the sorted sublist.
Each time an element moves from the unsorted
sublist to the sorted sublist, one sort is completed.
The bubble concept is shown in figure below :
1 j k n
Sorted Unsorted
Original list
23 78 45 8 32 56
Unsorted
Unsorted
if (found == 0)
cout << "The number " << key_value << " cannot be found in the list " << endl;
}
1
Structure
Introduction
Declaring Structure Type & Structure Variables
Referring and initializing structure elements
using value and reference
Passing structures to a function using value
and reference
Using typedef
Enumeration constants
2
Introduction
So far we have only used data types which have
been defined by C such as int, double and char.
It is also possible to create our own data types.
A user defined data type is called a structure.
A structure can contain both built-in data types
and another structure.
The concept of structure is pretty much the
same as arrays except that in an array, all the
data is of the same types but in a structure, the
data can be of different types.
3
Declaring Structure Type
Structure members can be of any type.
One structure may contain members of
many different type.
4
Example
struct student {
char name[20];
int studentID;
char major[50];
};
struct Time {
int hour;
int minute;
int second;
}
5
Declaring Structure Variables
After declaring a structure type, we may
declare variables that are of that type. A
structure variable declaration requires:
The keyword struct
The structure type name
A list of members (variable names) separated by
commas
A concluding semicolon
Then, assume that variable of structure type
student is my_student. So the declaration
should be written as;
struct student my_student;
6
Based on example: struct student
By including this declaration in our program,
we are informing the compiler about a new
data type which is a user defined data type.
The declaration just makes the compiler aware
of existent of new data type but does not take
an action yet.
Based on the declaration of
struct student my_student;
causes the compiler to reserve memory
space for variable my_student and the
components of its structure.
7
Based on example: struct student
cont…
Structure variable Components Values
name Simon
my_student studentID 0078
major CS
8
Based on example: struct student
cont…
It is possible to combine the
declarations of a structure type and a
structure variable by including the
name of the variable at the end of the
structure type declaration.
struct student { struct student {
char name[20]; char name[20];
int studentID; int studentID;
char major[50]; = char major[50];
}; } my_student;
struct student my_student;
9
Example
struct student {
char name[20];
int studentID;
char major[50];
};
student A_student;
student ClassLists[30]; //array of student
struct Time {
int hour;
int minute;
int second;
}
Time *timePtr; //pointer
Time Meetingtime; //a single object of type Time
10
Time Meetingtime; struct Time {
int hour;
int minute;
int second;
Time *timePtr; }
11
Declaring Nested Structure
Members of a structure declaration can
be of any type, including another
structure variable.
Suppose we have the following
structure declaration which this struct
will be as a member of struct type
student:
struct address {
int no;
char street[20];
int zipcode;
}addr;
12
Declaring Nested Structure
cont…
We can rewrite the structure student
declaration as follow:
struct student {
char name[20];
int studentID;
char major[50];
struct address addr;
} my_student;
14
Referring and Initializing Structure
Members
A structure contains many elements. Each
members of a structure can be referred to /
accessed by using the operator “.” (dot)
Let us use the structure student which we
have seen before as an example:
struct student {
char name[20];
int studentID;
char major[50];
} my_student;
15
Referring and Initializing Structure
Members
Therefore to refer to the element of a
structure, we may write as follow;
my_student.name;
my_student.studentID;
my_student.major;
Therefore, we can initialize each elements
of a structure individually such as:
struct student my_student;
my_student.studentID = 10179;
16
Referring and Initializing Structure
Members
Or we can initialize the structure while
we are creating an instance of the
structure:
struct student my_student = {“Ahmad”, 10179, “IT”}
struct birthdate {
int month;
int day;
int year;
}Picasso;
void main()
{
struct birthdate Picasso = {10, 25, 1881};
cout << "Picasso was born: " << Picasso.day << "/" << Picasso.month
<< "/" << Picasso.year << " " << endl;
18
Example 2
19
Example 3
20
Referring and Initializing Structure
Members using Pointer
A structure contains many elements. Each
members of a structure can be referred to /
accessed by using the operator “->” (arrow)
Let us use the structure student which we
have seen before as an example:
struct Time {
int hour;
int minute;
int second;
};
21
Referring and Initializing Structure
Members using Pointer
Meetingtime.hour = 12;
Meetingtime.minute = 30;
cout<< Meetingtime.hour, “:” Meetingtime.minute;
timePtr = &Meetingtime;
cout<<timePtr->hour, “:” ,timePtr->minute
22
Passing Structures to a Function
We can pass the Person structure that we have
created before to a function called displayData()
as follows:
void displayData(Person);
In the function above, a copy of the Person
structure will be created locally for the use of
the function. But any changes to the structure
inside the function will not affect the actual
structure.
23
struct Person
{
char name[50];
int age;
};
int main()
{
Person p;
void displayData(Person p)
{
cout << "\n*Displaying Information*" << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
}
24
It is also possible to use pointers and pass
the reference of the structure to the
function.
This way, any changes inside the function
will change the actual structure as well.
25
Passing Structures to a Function
using Pointer
To pass a reference, the displayData( )
function can be written this way:
void displayData(struct Person *p1);
Take note that when a structure is declared as
a pointer, the elements in the structure cannot
be referred to using the ‘.’ operator anymore.
Instead, they need to be accessed using the
‘->’ operator.
Example: void Read(struct student *s1)
{
s1->studentID = 10179;
scanf(“%s”, &(s1->name));
scanf(“%s”, &(s1->major));
}
26
27
Using typedef in Structure Declarations
The keyword typedef provides a mechanism for creating
synonyms (aliases) for previously defined data types.
Typedefs give a way to provide consistent type names
Let user-defined types declare associated types
Let you create type names for other purposes, convenience
Here is an example on how to use typedef when declaring a
structure:
typedef struct student {
char name[20]; struct student {
char name[20];
int studentID; int studentID;
char major[50]; char major[50];
struct address addr;
struct address addr; };
} StudentData;
typedef struct student StudentData;
Read(list);
found = Search(list);
if (found == TRUE)
cout << “FOUND!!”;
else
cout <<“Cannot find the requested item”;
}
void main ( ) {
enum months month;
char *monthsName[] =
{"January","February","March","April","May","June","Jul
y","August","September","October","November","December"
};
T.H.E E.N.D
1
Introduction to Classes
Classes, Objects & Strings
Define a Class with a Member Function
Inheritance
Inheritance: Public, Protected, Private
Base and Derived class
2
Classes, Objects & Strings
Classes is an improvement to ‘Structure’
3
Classes, Objects & Strings
We begin with an example that consists of class
GradeBook
represent a grade book that an instructor can use to
maintain student test scores
4
Example 1
Before function main can create a GradeBook
object, we must tell the compiler what member
functions and data members belong to the
class.
The GradeBook class definition contains a
member function called displayMessage that
displays a message on the screen.
We need to make an object of class GradeBook
and call its displayMessage member function to
execute and display the welcome message.
5
The class definition begins with the keyword
class followed by the class name GradeBook.
7
The keyword public which is an access specifier.
8
Defining a Member Function
with a Parameter
A member function can require one or more
parameters that represent additional data it
needs to perform its task.
9
Example2
Defining a Member Function
with a Parameter & Function
Next example, class GradeBook maintains the
course name as a data member so that it can
be used or modified at any time during a
program’s execution
15
Inheritance
When creating a class, instead of writing
completely new data members and member
functions, you can specify that the new class
(derived class) should inherit the members of
an existing class (base class).
17
Inheritance: Public
For example, if we have Vehicle as a base
class and Car as a derived class, then all Cars
are Vehicles, but not all Vehicles are Cars
for example, a Vehicle could also be a Truck or a Boat.
We distinguish between the is-a relationship
and the has-a relationship. The is-a relationship
represents inheritance. In an is-a relationship,
an object of a derived class also can be treated
as an object of its base class
for example, a Car is a Vehicle
so any attributes and behaviours of a Vehicle are also
attributes and behaviours of a Car.
18
Inheritance: Public
The inheritance relationship of two classes is
declared in the derived class. Derived classes
definitions use the following syntax:
class derived_class_name:
public base_class_name
{
/*...*/
};
19
Inheritance: Public
The public access specifier may be replaced by any
one of the other access specifiers (protected or
private).
This access specifier limits the most accessible level
for the members inherited from the base class:
The members with a more accessible level are inherited
with this level instead, while the members with an equal or
more restrictive access level keep their restrictive level in
the derived class.
20
20
Example 1:
Inheritance for 2 polygons
So there are two kinds of polygons here:
rectangles and triangles.
Polygon
Rectangle Triangle
21
Inheritance: Protected and Private
The objects of the classes Rectangle and Triangle
each contain members inherited from Polygon.
These are: width, height and set_values.
23
23
Inheritance: Public, Protected, Private
By declaring width and height as protected instead
of private
these members are also accessible from the derived
classes Rectangle and Triangle, instead of just from
members of Polygon.
24
Inheritance: Public, Protected, Private
In the example above, the members inherited by
Rectangle and Triangle have the same access
permissions as they had in their base class Polygon:
With protected,
all public members of the base class are inherited as protected
in the derived class.
31
Base Classes and Derived Classes
Every derived-class object is an object of its
base class.
32
Base Classes and Derived Classes
For example
the base class Vehicle represents all vehicles,
including cars, trucks, boats, airplanes,
bicycles and so on.
By contrast, derived class Car represents a
smaller, more specific subset of all vehicles.
Inheritance relationships form class
hierarchies.
33
Base Classes and Derived Classes
A base class exists in a hierarchical relationship
with its derived classes.
Although classes can exist independently, once they’re
employed in inheritance relationships, they become
affiliated with other classes.
34
Example 1:
CommunityMember Class Hierarchy
Example 2: Shape Class Hierarchy
Example 3:
Class Rectangle & Class Triangle
A program that has 2 classes shown below with
main () that executes them with the value 4 set
to width and 5 set to height for both shapes.
Rectangle Triangle
- width : Int - width : Int
- height : Int - height : Int
37
Example 4:
Inheritance for 2 polygons
So there are two kinds of polygons here:
rectangles and triangles.
Polygon
Rectangle Triangle
39
The Polygon class would contain members that
are common for both types of polygon.
In our case: width and height.
Rectangle and Triangle would be its
derived classes, with specific features
that are different from one type of
polygon to the other.
41
Classes that are derived from others inherit all
the accessible members of the base class.
42
SUMMARY
This chapter you learned about Classes, Objects
& Strings
Define a Class with a Member Function
You learned that Inheritance has 3 types:
Public, Protected, Private
Introduced you to Base and Derived class
T.H.E E.N.D
43
Stream Input & Output
CHAPTER 7
1
Stream Input & Output
Stream
Stream I/O
Unformatted I/O with read, gcount and
write
Stream Manipulators
Stream Format States
2
Stream
C++ I/O occurs in streams of bytes
A stream is simply a sequence of bytes
Input operation – bytes flow a device (mouse) to
main memory.
Output operation – bytes flow from main memory
to device
Bytes may represent ASCII characters, internal
format raw data, movie etc.
C++ provides both “low level” and “high level”
I/O capabilities.
Library Header Files
C++ <iostream> library provides hundreds of
I/O capabilities.
Several header files contain portions of the library
interface.
contains many classes for handling a wide variety of I/O
operations.
ios
istream ostream
fstream
Definition of operators
43
The End
44
File-Oriented Input &
Output
CHAPTER 8
1
File-Oriented Input & Output
2
File-Oriented Input & Output
3
Introduction
Storing data in variables (in memory) is
just temporary.
such data lost when the program
terminates.
Files are used for permanent retention
of large amounts of data.
Computers store files on secondary
storage devices esp. disk storage
devices.
A file is a group of related records.
A record is a group of related fields.
4
Files and Streams
C views a file as a sequential stream of bytes.
0 1 2 3 4 5 6 7 8 ..... n-1
7
General File I/O Steps
Declare a file name variable
Associate the filename variable with the
disk file name
Open the File
Use the file
Read data from the file
Write data to the file
Close the file
8
Basic File Operations – open a file
In order to open a file with a stream object we
use its member function open:
9
Creating a Sequential Access
Mode of Opening File
11
Creating a Sequential Access File :
Opening Files
12
Creating a Sequential Access File :
Opening Files
13
Creating a Sequential Access File :
Opening Files
14
Creating a Sequential Access File :
Closing a file
When we are finished with our input and output
operations on a file we shall close it so that the
operating system is notified and its resources
become available again. For that, we call the
stream's member function close. This member
function takes flushes the associated buffers and
closes the file:
myfile.close();
15
Creating a Sequential Access File :
Closing a file
When a C++ program terminates it automatically
closes flushes all the streams, release all the
allocated memory and close all the opened files.
But it is always a good practice that a
programmer should close all the opened files
before program termination
16
Creating a Sequential Access File :
Closing a File
17
Basic File Operations – write (ofstream)
While doing C++ programming, you write
information to a file from your program using the
stream insertion operator (<<) just as you use
that operator to output information to the screen.
The only difference is that you use an ofstream
or fstream object instead of the cout object.
18
Basic File Operations – write (ofstream)
19
Basic File Operations – write
20
Basic File Operations – write
21
Basic File Operations – read (ifstream)
You read information from a file into your
program using the stream extraction operator
(>>) just as you use that operator to input
information from the keyboard. The only
difference is that you use an ifstream or
fstream object instead of the cin object.
22
Basic File Operations – read
24
Detecting the End-of-File
25
Why to use Files
Convenient way to deal large quantities of
data.
Store data permanently (until file is
deleted).
Avoid typing data into program multiple
times.
Share data between programs.
26
Why to use Files
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
27
SUMMARY
FILEConcepts
Steps on how to apply FILE
programming structure
Examples of FILE program
Advantage use Files
28
The End
29