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

CHAPTER 1

TRANSITION FROM C TO C++

Chapter 1 : Transition from C to C++ 1


Objectives
 C++ enhancement to C.
 The header files of the C++ Standard Library.
 Output Statement in C++
 Input Statement in C++
 Control Structures in C++
 C++ Keywords

Chapter 1 : Transition from C to C++ 2


Introduction to C++
 Improves on many of C's features
 Has object-oriented capabilities
 Increases software quality and reusability
 Developed by Bjarne Stroustrup at Bell Labs
 Called "C with classes"
 C++ (increment operator) - enhanced version of C
 Superset of C
 Can use a C++ compiler to compile C programs
 Gradually evolve the C programs to C++

Chapter 1 : Transition from C to C++ 3


C++ Standard Library
 C++ programs consist of pieces called classes and
functions.
 C++ has a rich collections of classes and functions in
its standard library.
 Two parts to learning C++
 Learn the language itself
 Learn the library functions
 Making your own functions
 Advantage: you know exactly how they work
 Disadvantage: time consuming, difficult to maintain
efficiency and design well
Chapter 1 : Transition from C to C++ 4
Your first C++ Program
// A First Program in C++

#include <iostream>

void main ()
{
std::cout << "HELLO WORLD\n ";
}

Chapter 1 : Transition from C to C++ 5


Header Files
 Header files
 Each standard library has header files
 Contain function prototypes, data type definitions, and
constants
 Files ending with .h are "old-style" headers
 User defined header files
 Create your own header file
 End it with .h
 Use #include "myFile.h" in other files to load
your header

Chapter 1 : Transition from C to C++ 6


Output Statement : cout
 Output and input in C++ is accomplished with
streams of character
 “<<“ operator is referred to as stream insertion
operator. Escape sequence for a
new line

std::cout << “Hello World \n”;

This string is inserted to the


std namespace standard output stream
object – cout- which is
connected to the screen
Chapter 1 : Transition from C to C++ 7
Input Statement : cin
 Input/Output in C++
 Performed with streams of characters
 Streams sent to input/output objects
 Output
 std::cout - standard output stream (connected to screen)
 << stream insertion operator ("put to")
 std::cout << "hi";
 Puts "hi" to std::cout, which prints it on the screen
 Input
 std::cin - standard input object (connected to keyboard)
 >> stream extraction operator ("get from")
 std::cin >> myVariable;
 Gets stream from keyboard and puts it into myVariable
Chapter 1 : Transition from C to C++ 8
I/O Manipulator statement : endl
 std::endl
 "end line"
 Stream manipulator - prints a newline and flushes output buffer
 Some systems do not display output until "there is enough
text to be worthwhile"
 std::endl forces text to be displayed

 Cascading
 Can have multiple << or >> operators in a single statement
std::cout << "Hello " << "there" << std::endl;

Chapter 1 : Transition from C to C++ 9


Exercise
 Can someone in this class be a “lady” or a
“gentleman”? Help me here…

Write a simple C program that adds up 2


numbers 

Shouldn’t be a problem right? Y’all have


learned this in Programming 1… :D
Exercise
 SAME CASE STUDY

Write a simple C++ program that adds up 2


numbers 

It may be a problem, right?


Since this is first time…

SO, lets do together !!


std::___
 Each header file in C++ draft standard uses a
namespace to guarantee that every feature in the C++
standard library is unique.
 So if a user defined a class that have features with
identical names, no name conflict will occur.
 But to suppress the use of std:: , for all use of
features in the standard library, we can use the
statement:
using std::cin;
using std::cout;
OR
using namespace std;
Chapter 1 : Transition from C to C++ 12
The using statement
 Remember that when you use the function
from iostream, you have to keep the
std:: over and over again?
The using statement
 Use the using statement, we can eliminate
the repetition of std:: in every statement
Comparison
Exercise:
 SAME CASE STUDY.
Write a simple C++ program that adds up 2
numbers 

 But lets use

using namespace std

It may be a problem, right? Since this is


first time…SO, lets do together !!
C++ Keywords

Chapter 1 : Transition from C to C++ 17


CONTROL
STRUCTURES
Conditional Statements & Loops

Chapter 1 : Transition from C to C++ 18


Control Structures
 Basically nothing change with the statements
in the structured programming part.
 The basic control structures
i. Sequential structure,
ii. conditional structure
iii. repetition structure.

Chapter 1 : Transition from C to C++ 19


Control Structures Cont…

Chapter 1 : Transition from C to C++ 20


Selection Structures
 The if selection statement is a single-selection
statement because it selects or ignores a single action
(or, as we’ll soon see, a single group of actions).
 The if…else statement is called a double selection
statement because it selects between two different
actions (or groups of actions).
 The switch selection statement is called a multiple-
selection statement because it selects among many
different actions (or groups of actions).

Chapter 1 : Transition from C to C++ 21


if…else Double-Selection Statement
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";

If studentGrade is greater than or equal to 90, the first


four conditions are true, but only the output statement
after the first test executes. Then, the program skips the
else-part of the “outermost” if…else statement.
Chapter 1 : Transition from C to C++ 22
if…else Double-Selection Statement (cont.)
 The C++ compiler always associates an else with the
immediately preceding if unless told to do
otherwise by the placement of braces ({ and }).
 This behavior can lead to what’s referred to as the
dangling else problem.

if ( x > 5 )
if ( y > 5 )
cout << "x and y are > 5";
else
cout << "x is <= 5";

appears to indicate that if x is greater than 5, the nested if


statement determines whether y is also greater than 5.
Chapter 1 : Transition from C to C++ 23
Repetition Structures
 C++ provides three types of repetition statements
(also called looping statements or loops) for
performing statements repeatedly while a condition
(called the loop continuation condition) remains true.
 These are the while, do…while and for
statements.
 The while and for statements perform the action (or
group of actions) in their bodies zero or more times.
 The do…while statement performs the action (or
group of actions) in its body at least once.

Chapter 1 : Transition from C to C++ 24


SUMMARY
 In this chapter, you have learnt:
 The header files of the C++ Standard Library
#include<iostream.h>
 Output Statement in C++
std::cout
 Input Statement in C++
std::cin
 Control Structures in C++
 Sequential structure, conditional structure & repetition structure.
 C++ Keywords

Chapter 1 : Transition from C to C++ 25


CHAPTER 2
POINTER

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.

numberptr numberptr indirectly references a


10 value which is 10
6
Graphical Representation of MM
Memory address Memory content

0x0000 27 A variable of type int is


0x0001 10 stored here. The address
of this location is 0x0002.
0x0002 76
0x0003 99
… ...
... ...
0xFFFC 0x0002
This location contains the
0xFFFD 787 value 0x0002. Therefore this
0xFFFE 878 location stores a pointer
0xFFFF 999 variable which points to the
address 0x0002.
7
Pointer Declaration
 General format:
data_type *ptr_name;
 Example:
 Pointer to an int: int *intptr;
 Pointer to a char: char *charptr;
 Pointer to a float: float *floatptr;
 Pointer to double: double *doublepter;
 The asterisk (*) character in front of the variable
name tells that the variable is a pointer.

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

Graphical representation of a pointer pointing to an integer variable in memory

 num_ptr = &num;
*num_ptr num

11001100 9
11111111 11001100

Representation of num and numPtr in memory


Example

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;

 Read the pointer value


cout << "&aVar = " << &aVar << endl;
cout << “*aPtr = " << *aPtr << endl;

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

The real power of pointers is seen


when they are used to point to
dynamically allocated variables.

Let’s see why.


Memory Allocation
 What is Memory Allocation ?
 Types of memory allocation
 Static
 Dynamic
 Static Memory Allocation – compiler time
 Dynamic Memory Allocation – run time
 We can control the allocation and deallocation of
memory in a program for objects and for arrays:
 of any built-in or user-defined type.

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.

 Their address is determined when the program is run.

• In contrast, a static variable has memory reserved for it at


compilation time.

 In short, a dynamic variable was created during run time,


not when the program is compiled.

• 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.

 Once memory is allocated in the free store, it can be access


via the pointer that operator new returns.

25
Obtaining Dynamic Memory with
new
 Consider the following statement:
Time *timePtr = new Time

 The new operator allocates storage of the proper size for an


object of type Time
 calls the default constructor to initialize the object and
returns a pointer to the type specified to the right of the
new operator (i.e. a Time *).
 •If new is unable to find sufficient space in memory for the
object, it indicates that an error occurred by “throwing an
exception.”

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.

 To destroy a dynamically allocated object, use the delete


operator as follows:
delete Timeptr;

 This statement first calls the destructor for the object to


which Timeptr points, then deallocates the memory
associated with the object, returning the memory to the
free store.

27
Pointers and Dynamic Memory
 Storage for these variables comes from an area of memory
called the free store or the heap.

 The creation of new dynamic variables is called memory


allocation and the memory is called dynamic memory.

 C++ uses the new operator create a dynamic variable.

Examples:

char *my_char_ptr = new char;


int *my_int_array =new int[20];
double *ptr = new double(3.14159);
Time *timePtr = new Time(12,45,0);
Pointers and Dynamic Memory
Here are the steps:

int * myIntPtr; // create an integer pointer variable


myIntPtr = new int; // create a dynamic variable
// of the size integer

new returns a pointer (or memory address) to the location where


the data is to be stored.
Pointers and Dynamic Memory
Pointers and Dynamic Memory

31
Pointers and Dynamic Memory
 The new operator gets memory from the free store (heap).

 When you are done using a memory location, it is your


responsibility to return the space to the free store. This is done
with the delete operator.

delete myIntPtr; // Deletes the memory pointed


delete [ ] arrayPtr; // to but not the pointer variable

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:

#include <iostream> File header


using namespace std;

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

void CalculateTotal(int score) {


total = total + score; Give a name to the argument(s)
}
that are passed to the function.
void PrintTotal(void) {
cout<<“Total score is:”<<total<<;
}

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:

cout<<“User input is:”<< GetUserInput()<<;

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;

sum = calSum(num1,num2); /* function call */


cout << "sum = " << sum << endl;
}

int calSum(int val1, int val2) /*function definition*/


{
int sum;
sum = val1 + val2;
Formal
return sum;
} Parameters
20
Functions with Parameters Cont…
 2 types of formal parameters:
 Value parameters which are used only to send values to
functions.
 Only the copy of variable’s value is passed to the function.
 Any modification to the passed value inside the function will not
affect the actual value
 Pointer parameters which are used to send values to and/or
returning values from functions.
 The reference (memory address) of the variable is passed to
the function.
 Any modification passed done to the variable inside the function
will affect the actual value.

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); /* function prototype */


In this example, function greeting does not
int main(void) receive any arguments from the calling function
{ (main), and does not return any value to the
greeting( ); calling function, hence type ‘void’ is used for
greeting( ); both the input arguments and return data type.
return 0;
}

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;

cout << "Sum is = " << sum << endl;


return 0;
}

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

void displayOutput(int sum)


{
cout << "Sum is = " << sum << endl;
}
27
Example 4: receive parameters and return a value
#include <iostream>
using namespace std;

int calSum(int,int);/*function protototype*/

int main(void)

{
int sum, num1, num2;

cout << "Enter two numbers to calculate its sum: " << endl ;
cin >> num1 >> num2;

sum = calSum(num1,num2); /* function call */


cout << "Sum is = " << sum << endl;
return 0;
}

int calSum(int val1, int val2) /*function definition*/

{
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.

Filling status Taxable Income


Over But not over Tax
1. Single 59,300 - 11,158 + 31% of amount over 49,300
2. Married (joint) 34,000 82,150 5,100 + 28% of amount over 34,000
82,150 - 18,582 +31% of amount over 82,510
3. Married (separate) 41,075 - 9,291 + 31% of amount over 41,075
4. Head of household 27,300 70,450 4,095 + 28% of amount over 27,300
70,450 - 16,177 + 31% of amount over 70,450

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

 static storage duration


 static and extern

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

 Start from scratch – re-initialise the variables

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

typedef double radius_type;


typedef double height_type;
typedef double length_type;

double right_circular_cylinder(radius_type, height_type);


double right_circular_cone(radius_type, height_type);
double sphere(radius_type);
double ellipsoid(length_type, length_type, length_type);

67
Example Volumes.c
#include "Volumes.h"

double right_circular_cylinder(radius_type r, height_type h)


{
double volume;
volume = pi * r * r * h;
return volume;

double right_circular_cone(radius_type r, height_type h)


{
double volume;
volume = pi * r * r * h/3;
return volume;
}
68
Example Volumes.c Cont…
double sphere(radius_type r)
{
double volume;
volume = 4 * pi * (r * r * r)/3;
return volume;

double ellipsoid(length_type a, length_type b, length_type c)


{
double volume;
volume = 4 * pi * a * b * c/3;
return volume;
}

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

Prepared by MMD, Edited by MSY 1


Arrays
 Introduction to arrays
 Declaring arrays
 Initializing arrays
 Examples using arrays
 Array passing to a function
 Simple sorting: bubble sort
 Simple searching: linear sort

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,

 Derived data types – derived from fundamental


data types eg. arrays.

3
The position
Let say we have an array called A
starts from 0.

Name of the array A[0] -10


A[1] 99
Position/index number of the
element within the array A[2] -8
The index number is written within A[3] 100
the square brackets. Size
An index can be an integer or an A[4] 27
integer expression.
For example if A[5] 1
x = 1 and y = 2, then A [x+y]
is A [3]. A[6] 1976
A[7] -2020
A[8] 1
4
MULTI-dimensional ARRAYS
 C++ allows for arrays of two or more dimensions.
 A two-dimensional (2D) array is an array of arrays.
 A three-dimensional (3D) array is an array of arrays of
arrays.

 In C++ programming an array can have two, three, or even


ten or more dimensions.
 The maximum dimensions a C++ program can have depends
on which compiler is being used.

 More dimensions in an array means more data be held, but


also means greater difficulty in managing and understanding
arrays.
Multi-dimensional ARRAYS

[0] [1] [2]


One-dimensional arrays are linear containers.

[2]
Multi-dimensional Arrays [1]
[0]

[0] [1] [2] [3] [0]


[0] [1]
[1] [2]
[2] [3]
two- [0] [1] [2] [3] [4]
dimensional
three-
dimensional
2-Dimensional Array
 It is possible to create an array which has more than
one dimension.
 For example:
 2D array: int array[4][2];
 3D array: int array[4][2][10];
 Graphical representation of a 2D array:
int myarray[4][2] = {1, 2, 3, 4, 5, 6, 7, 8};

1 2
3 4 This array has 4 rows and 2
5 6 columns.

7 8 Prepared by MMD, Edited by MSY 7


2-Dimensional Array Cont…
 Variable initialization can also be done this way:
int myarray[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
int test_score[4][3]={{95,80,78},{69, 75,81}, {100,98,100},
{98,85,87}};
This method is less confusing since we can see the rows
and columns division more clearly.
 To initialize a 2D array during execution, we need to use
a double loop (nested loop):
for (i = 0; i < 4; i++)
for (j = 0; j < 2; j++)
total=total + myarray[i][j];

 Although it is possible to create a multi-dimensional


array, arrays above 2-dimensions are rarely used.

Prepared by MMD, Edited by MSY 8


3-Dimensional Array
 Let's take a closer look at a 3D array. A 3D array is essentially an array of
arrays of arrays: it's an array or collection of 2D arrays, and a 2D array is
an array of 1D array.
 It may sound a bit confusing, but don't worry. As you practice working
with multidimensional arrays, you start to grasp the logic.
 The diagram below may help you understand:
3-Dimensional Array Cont…
Initializing a 3D Array in C++
 Like any other variable or array, a 3D array can be initialized at the time
of compilation.
The Conceptual Syntax of a 3D Array in C
 The conceptual syntax for 3D array is this:
data_type array_name[table][row][column];

 If you want to store values in any 3D array point first to table number,
then row number, and lastly to column number.

Some hypothetical examples:

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.

Prepared by MMD, Edited by MSY 11


How to Initialize Array?
 There are 2 ways to initialize an array:
1. During compilation:
 Unsized array (Implicit number of size )
int arr[] = {1, 2, 3, 4, 5};

 Sized array (Explicit number of size)


 int arr[3] = {90, 21, 22};
 int N[4][2]={ 1, 2; 3, 4; 5, 6; 7, 8; 9, 10;};
 int myarray[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7,
8}};
 int arr[0][1][2] = 32;
 int arr[1][0][1] = 49;

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;

 To initialize a 2D array during execution, we need to use


a double loop (nested loop):
for (i = 0; i < 4; i++)
for (j = 0; j < 2; j++)
total=total + myarray[i][j];

13
Example 1 : Declaring and
Initializing 2D array
 Declaring and intializing a 5 by 2 array
with the values given.

Prepared by MMD, Edited by MSY 14


Example 2: Using 1D Array
#include <iostream> Output:
using namespace std;
Element Value
#define SIZE 5 0 0
1 9
void main(void) { 2 18
3 27
int temp[SIZE], i;
4 36
for (i = 0; i < SIZE; i++)
temp[i] = i*9;
cout << "Element" << "Values" << endl;
for (i = 0; i < SIZE; i++)
cout << i << " " << temp[i] << endl;

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;

for (i=0; i < SIZE; i++)


total += list[i];

cout << "Total of array elements values is " << total << endl;
}

Output:
Total of array element values is 45.

Prepared by MMD, Edited by MSY 16


Example 4: 2D Array
Example 5: 3D Array
Example 6: 3D Array
Example 7: 3D Array
Exercise 1
 Print the elements in the array
: row by row

int N[ 5 ][2] = { 1, 2; 3, 4; 5, 6; 7, 8; 9, 0; };

Prepared by MMD, Edited by MSY 21


Exercise 2
 Print the elements in the array
: column by column

int N[ 5 ][2] = { 1, 2; 3, 4; 5, 6; 7, 8; 9, 0; };

Prepared by MMD, Edited by MSY 22


Exercise 3
 Program that receive age for 2 persons and
then display the ages, as below:

Prepared by MMD, Edited by MSY 23


Exercise 4
 Program that receive age for 4 persons, then
display the ages and the total of ages, as
below:

Prepared by MMD, Edited by MSY 24


Exercise 5
 Program that receive age for n persons. n value
will be enter by the user. Then display the ages
and the total of ages, as below:

Prepared by MMD, Edited by MSY 25


How to Pass Arrays to a called
Function’s Parameter
 Declare the function prototype as usual but the
difference is the way the formal parameter is
written.

void Process (char []) ;


float average (int []);

Prepared by MMD, Edited by MSY 26


How to Pass Arrays to a called
Function’s Parameter (Cont)
 When we want to pass an array to a function, we
need to know these 3 things:
 How to write the function prototype?
 How to do function call?
 How does the function header would look like?

 Assume that we have the following array


declaration.
int marks[10] = {0,0,0,0,0,0,0,0,0,0};
 Say for example we want to write a function,
called get_marks, which will read marks from the
user and store the marks inside the array.
27
Passing Array to a Function Cont…
 Function prototype:
/* data type with square bracket */
void get_marks(int []);

 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:

Prepared by MMD, Edited by MSY 29


Passing 2D Array to Function
 When a 2D (or higher dimensional) array is passed to
a function, the size of the second (or subsequent)
subscript needs to be specified.
 For example, if we have:
int twoD[4][5];
Then a function which would take twoD as an
argument should be declared like this:
void Process2D(int td[][5])
 An array is stored consecutively in memory
regardless of the number of dimensions. Therefore,
specifying the subscripts in the function parameter
will help the compiler to know the boundary of the
different dimensions.
Prepared by MMD, Edited by MSY 30
Sorting
 Sorting is the process of placing data into a
particular order such as ascending or descending.
 There are many sorting algorithms that are usually
used.
 Among them are bubble sort, selection sort, insertion sort,
shell sort, merge sort etc.
 Here, we will discuss how bubble sort can be used
to sort the elements in an array.

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

Prepared by MMD, Edited by MSY 37


Bubble Sort cont…
 Figure below shows how the wall moves one
element in each pass.

Original list
23 78 45 8 32 56

Unsorted

 Looking at the first pass, start with 56 and compare


it to 32. Since 56 > 32, it is not moved and we step
down one element.
 No changes take place until we compare 45 to 8.
Since 8 < 45, the two elements are exchanged
(swapped).
Prepared by MMD, Edited by MSY 38
Bubble Sort cont…
 The two elements are swapped and we step
down 1 element.
 Because 8 was moved down, it is now compared
to 78 and these two elements are swapped.
 Finally, 8 is compared to 23 and exchanged.
This series of exchanges places 8 in the first
location and the wall is moved up one position.
8 23 78 45 32 56 After pass 1

Unsorted

Prepared by MMD, Edited by MSY 39


Simple Searching
 Searching is the process of determining whether an
array contains a value that matches a certain key
value.
 Same as in sort, there are more than one algorithms
that can be used to do a search.
 Here, we will discuss how can we do a linear search
on an array.
 Linear search is a simple searching algorithm where:
 data are stored in an array
 a key value is compared with each elements in the array
starting from the first element

Prepared by MMD, Edited by MSY 40


Let us look at the C code:
Sample Output:
#include <iostream> Enter the number that you want to find: 53
using namespace std; The number 53 is found at location 1
Press any key to continue
void main(void)
{
int list[] = {34, 53, 21, 23, 4};
int i, key_value, found = 0;
cout << "Enter the number that you want to find: " ;
cin >> key_value;

for (i = 0; i < 5; i++) {


if (list[i] == key_value) {
found = 1;
cout << "The number is found at location: " << i << endl;
break;
}
}

if (found == 0)
cout << "The number " << key_value << " cannot be found in the list " << endl;
}

Prepared by MMD, Edited by MSY 41


SUMMARY
 In this chapter, we have looked at:
 Array declaration and initialization
 Reading and writing from/to array elements
 Passing array to function
 Array sorting : BubbleSort
 Simple searching : Linear Search

Prepared by MMD, Edited by MSY 42


CHAPTER 5
STRUCTURE

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.

 General syntax: Also called as structure tag


struct structure_name {
data_type element1;
data_type element2; Components / members
...
};

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

Conceptual memory structure variable my_student of


type student

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;

 This structure type student can be


written as;
13
Declaring Nested Structure
cont…
struct student {
char name[20];
int studentID;
char major[50];
struct address{
int no;
char street[20];
int zipcode;
}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”}

 Notice that it is possible to use the ‘=’


operator on a struct variable. When
the ‘=’ sign is used, each elements of
the structure at the right hand side is
copied into the structure at the left
hand side.
17
Example 1
#include<iostream>
using namespace std;

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

 The expression timePtr->hour is the same as


(*timePtr).hour

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

void displayData(Person); // Function declaration

int main()
{
Person p;

cout << "Enter full name: ";


cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;

// Function call with structure variable as an argument


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

Chapter 6 : User Defined Data Types 28


Using typedef in Structure Declarations
 By using typedef, we now do not have to
write the word “struct” before declaring a
struct variable. Instead of writing:
struct student my_student;
we can now write:
StudentData my_student;
 Same thing with passing the structure to
a function:
void Read(StudentData *s1);

Chapter 6 : User Defined Data Types 29


Exercise
Create a program that receive studentID,
name and score mark, for 5 students.
Then, display the name and the grade.
Sample output:

Chapter 6 : User Defined Data Types 30


Enumeration Constants
 An enumeration, introduced by the keyword
enum, is a set of integer constants represented by
identifiers. (to specify one after another)
 Example:
enum islamic_months {
muharam, safar, rabiulawal, rabiulakhir,
jamadilawal, jamadilakhir, rejab,
syaaban, ramadhan, syawal, zulkaedah,
zulhijjah
};
 Each of the identifiers actually has a value,
starting with 0 (unless specified otherwise).
Therefore, we can treat them as integers.
Chapter 6 : User Defined Data Types 31
Enumeration Constants cont…
 If we want the enumeration to start with a
value other than 0, we can assign the value to
the first identifier:
enum islamic_months {
muharam = 1, safar, rabiulawal, rabiulakhir,
jamadilawal, jamadilakhir, rejab, syaaban,
ramadhan, syawal, zulkaedah, zulhijjah
};
 Same as with the other data types, before an
enum can be used, a variable needs to be
declared:
enum islamic_months months;

Chapter 6 : User Defined Data Types 32


Enumeration Constants cont…
 There are cases where it is appropriate for us to
use an enum. This is an example of such a case:
enum islamic_months months;
GetMonth (&months);
switch (months) {
case muharam:
. . .
break;
case safar:
. . .
break;
case ramadhan:
cout << “lunch not provided”;
break;
. . .
}
Chapter 6 : User Defined Data Types 33
Enumeration Constants cont…
 This is another case where it is appropriate to
use an enum:
enum Boolean {FALSE, TRUE};
void main ( ) {
int list[];
Boolean found;

Read(list);
found = Search(list);
if (found == TRUE)
cout << “FOUND!!”;
else
cout <<“Cannot find the requested item”;
}

Chapter 6 : User Defined Data Types 34


Enumeration Constants cont…
#include <iostream>
using namespace std;
enum months {JAN = 1, FEB, MAR, APR, MAY, JUN, JUL,
AUG, SEP, OCT, NOV, DEC};

void main ( ) {
enum months month;
char *monthsName[] =
{"January","February","March","April","May","June","Jul
y","August","September","October","November","December"
};

for (month = JAN; month <= DEC; month++)


cout << “ “ << month << monthName[month-1]);
}
Chapter 6 : User Defined Data Types 35
Enumeration Constants cont…
Output:
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December

Chapter 6 : User Defined Data Types 36


Exercise
 Declare a structure called Q1Struct, that
contains two integers called Integer1 and
Integer2 as well as two floating point numbers
called Float1 and Float2

 Declare a structure called Q2Struct, that


contains an array of ten integers called IntNums
and array of ten characters called Characters.
 Write C statements that will fill the values of the
integer’s array from user and calculate and store the
sum

Chapter 6 : User Defined Data Types 37


SUMMARY
 This chapter you learned about structures
 Structure type and variable declarations
 How structure members can be accessed
 How they can be initialized
 You learned that structures can be passed
between function
 Introduced you to another user defined data
type which is enumeration

T.H.E E.N.D

Chapter 6 : User Defined Data Types 38


CHAPTER 6
INTRODUCTION TO CLASSES

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’

 ‘Structure’ can only store data members

 Classes can store data members and functions


(methods) with other characteristics
manipulator

 Let us see how it is done 

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

 A main function: creates a GradeBook object


 uses this object and its member function to display a
message on the screen welcoming the instructor to the
grade-book program.

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.

 Every class’s body is enclosed in a pair of left


and right braces ({ and })

 The class definition terminates with a semicolon


(;)

7
 The keyword public which is an access specifier.

 The member function displayMessage appears


after access specifier public:
 to indicate that the function is “available to the
public”
 it can be called by other functions in the program
(such as main), and by member functions of other
classes (if there are any)

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.

 A function call supplies values—called


arguments—for each of the function’s
parameters.

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

 The class contains member functions:


 setCourseName - stores a course name in a
GradeBook data member
 getCourseName - obtains the course name from that
data member
 displayMessage - displays a welcome message that
includes the course name (no parameter)
11
 Most data-member declarations appear after the
private access specifier.

 When a program creates a GradeBook object,


data member courseName is encapsulated
(hidden) in the object and can be accessed only
by member functions of the object’s class.

 In class GradeBook, member functions


setCourseName and getCourseName manipulate
the data member courseName directly.
14
Inheritance
 is a form of software reuse in which you create
a class that absorbs an existing class’s
capabilities, then customizes or enhances them.

 Software reuse saves time during program


development by taking advantage of proven,
high-quality software.

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).

 Other programming languages, such as Java


and C#, refer to the base class as the
superclass and the derived class as the
subclass. A derived class represents a more
specialized group of objects.
16
Inheritance
 C++ offers public, protected and private
inheritance.
 In this chapter, we concentrate on public inheritance
and briefly explain the other two.

 With public inheritance, every object of a


derived class is also an object of that
derived class’s base class. However, base
class objects are not objects of their derived
classes.

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.

 These two polygons have certain common


properties, such as the values needed to
calculate their areas: they both can be
described simply with a height and a width.
 This could be represented in the world of classes
with a class Polygon from which we would derive the
two other ones: Rectangle and Triangle:

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.

 The protected access specifier used in class Polygon


is similar to private.
 Its only difference occurs in fact with inheritance:
 When a class inherits another one, the members of the
derived class can access the protected members inherited
from the base class, but not its private members.

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.

 If they were public, they could be access just from


anywhere.

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:

 This is because the inheritance relation has been


declared using the public keyword on each of the derived
classes:
class Rectangle : public Polygon { }
Inheritance: Public, Protected, Private

 This public keyword after the colon (:)


 denotes the most accessible level the members inherited from
the class that follows it (in this case Polygon) will have from
the derived class (in this case Rectangle).

 Since public is the most accessible level, by specifying


this keyword the derived class will inherit all the
members with the same levels they had in the base
class.
Inheritance: Public, Protected, Private

 With protected,
 all public members of the base class are inherited as protected
in the derived class.

 Conversely, if the most restricting access level is


specified (private),
 all the base class members are inherited as private and thus
cannot be accessed from the derived class.
Inheritance: Public, Protected, Private
 For example, if daughter were a class derived from
mother that we defined as:
class Daughter : protected Mother { }

 This would set protected as the less restrictive access level


for the members of Daughter that it inherited from mother.
 That is, all members that were public in Mother would
become protected in Daughter.
 Of course, this would not restrict Daughter from declaring
its own public members.
 That less restrictive access level is only set for the members inherited
from Mother.If no access level is specified for the inheritance, the compiler
assumes private for classes declared with keyword class and public for
those declared with struct.
Inheritance: Public, Protected, Private
Base Classes and Derived Classes
 Below figure lists several simple examples of
base classes and derived classes. Base classes
tend to be more general and derived classes
tend to be more specific.

31
Base Classes and Derived Classes
 Every derived-class object is an object of its
base class.

 One base class can have many derived classes.

 The set of objects represented by a base class


typically is larger than the set of objects
represented by any of its derived classes.

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.

 A class becomes either:


 a base class—supplying members to other classes
 a derived class—inheriting its members from other
classes
 or both.

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.

 Formula for Rectangle’s area is (width*height)


while Triangle’s are is (width * height / 2)

Rectangle Triangle
- width : Int - width : Int
- height : Int - height : Int

+ area () : Int + area () : Int


+ set_values (a : Int, b: Int) + set_values (a : Int, b: Int)

37
Example 4:
Inheritance for 2 polygons
 So there are two kinds of polygons here:
rectangles and triangles.

 These two polygons have certain common


properties, such as the values needed to
calculate their areas: they both can be
described simply with a height and a width.
 This could be represented in the world of classes
with a class Polygon from which we would derive the
two other ones: Rectangle and Triangle:

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.

 That means that if a base class includes a


member A and we derive a class from it with
another member called B, the derived class will
contain both member A and member B

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.

 C++ <iomanip> header declares services useful


for performing formatted I/O with so called
parameterized stream manipulators.
Stream I/O Classes and Objects

ios

istream ostream

ifstream iostream ofstream

fstream
Definition of operators

 << is called Stream-Insertion Operator

 >> is called Stream-Extraction Operator


1 - Stream Output
Outputting Expression Values
Output of Char* Variables
2 - Input: Stream-Extraction Operator
Stream-Extraction Operator returns 0
on end-of-file
3 - get

 Formatted and unformatted input


capabilities are provided by istream.
 The stream extraction operator (>>)
normally skips whitespace characters (such
as blanks, tabs and newlines) in the input
stream
3 - get
 The get member function with
 no arguments inputs one character from the designated
stream (including white-space characters and other nongraphic
characters, such as the key sequence that represents end-of-
file)
 returns it as the value of the function call.
 This version of get returns EOF when end-of-file is
encountered on the stream.

 The get member function with a character reference


argument inputs the next character from the input stream
(even if this is a white-space character) and stores it in the
characters argument.
 This version of get returns a reference to the istream object
for which the get member function is being invoked
3 - get
3 - get

 A third version of get takes three arguments—a character


array, a size limit and a delimiter (with default value '\n').
This version reads characters from the input stream.

 It either reads one fewer than the specified maximum


number of characters and terminates or terminates as soon
as the delimiter is read.

 A null character is inserted to terminate the input string in


the character array used as a buffer by the program.
4 - put
5 - getline

 Member function getline operates similarly to


the third version of the get member function
and inserts a null character after the line in
the character array.

 The getline function removes the delimiter


from the stream (i.e., reads the character
and discards it), but does not store it in the
character array.
5 - getline
Unformatted I/O: read, gcount, read
Unformatted I/O: read, gcount, read

Problem solved with getline.


The question here is, besides
getline, can we solve this using
the std cin method?
Stream Manipulators
 C++ provides various stream manipulators that
perform formatting tasks.

 The stream manipulators provide capabilities


such as
 setting field widths
 setting precision
 setting and unsetting format state
 setting the fill character in fields
 flushing streams
 inserting a newline into the output stream (and flushing
the stream)
 inserting a null character into the output stream and
skipping white space in the input stream.
1 - Floating-Point Precision (precision, setprecision)

 We can control the precision of floating-point numbers (i.e.,


the number of digits to the right of the decimal point) by
using either the setprecision stream manipulator or the
precision member function of ios_base.

 A call to either of these sets the precision for all subsequent


output operations until the next precision-setting call.

 A call to member function precision with no argument


returns the current precision setting (this is what you need
to use so that you can restore the original precision
eventually after a “sticky” setting is no longer needed).
2 - Field Width (width, setw)
 The width member function (of base class ios_base)
 sets the field width (i.e., the number of character
positions in which a value should be output or the
maximum number of characters that should be input)
 returns the previous width.

 If values output are narrower than the field width, fill


characters are inserted as padding.

 A value wider than the designated width will not be


truncated—the full number will be printed.

 The width function with no argument returns the


current setting.
3 - Trailing Zeros and Decimal Points
(showpoint)

 Stream manipulator showpoint forces a


floating-point number to be output with its
decimal point and trailing zeros.

 To reset the showpoint setting, output the


stream manipulator noshowpoint.
4 - Justification (left, right and internal)

 Stream manipulators left and right enable


fields to be left justified with padding
characters to the right or right justified with
padding characters to the left, respectively.

 The next example uses the setw( ), left


and right manipulators to left justify and
right justify integer data in a field.
4 - Justification (left, right and internal)

 Stream manipulator internal indicates that a


number’s sign (or base when using stream
manipulator showbase) should be left justified
within a field, that the number’s magnitude
should be right justified and that intervening
spaces should be padded with the fill character.

 Note that showpos forces the plus sign to print.

 To reset the showpos setting, output the stream


manipulator noshowpos.
5 - Padding (fill, setfill)

 The fill member function specifies


the fill character to be used with justified
fields;
 spaces are used for padding by default.

 The function returns the prior padding


character.
 The setfill manipulator also sets the
padding character.
6 - Integral Stream Base (dec, oct, hex, showbase)

 C++ provides stream manipulators dec, hex and oct to


specify that integers are to be displayed as decimal,
hexadecimal and octal values, respectively.

 Stream insertions default to decimal if none of these


manipulators is used. With stream extraction, integers
prefixed with 0 (zero) are treated as octal values, integers
prefixed with 0x or 0X are treated as hexadecimal values,
and all other integers are treated as decimal values.

 Once a particular base is specified for a stream, all integers


on that stream are processed using that base until a
different base is specified or until the program terminates.
6 - Integral Stream Base (dec, oct, hex, showbase)

 Stream manipulator showbase forces the base of


an integral value to be output.
 Decimal numbers are output by default, octal numbers
are output with a leading 0, and hexadecimal numbers
are output with either a leading 0x or a leading 0X
(stream manipulator uppercase determines which option
is chosen).

 The use of stream manipulator showbase to force


an integer to print in decimal, octal and
hexadecimal formats.
 To reset the showbase setting, output the stream
manipulator noshowbase.
6 - Integral Stream Base (dec, oct, hex, showbase)
7 - Floating-Point Numbers; Scientific and Fixed Notation
(scientific, fixed)

 Stream manipulators scientific and fixed control the


output format of floating-point numbers. Stream
manipulator scientific forces the output of a
floating-point number to display in scientific format.

 Stream manipulator fixed forces a floating-point


number to display a specific number of digits (as
specified by member function precision or stream
manipulator setprecision) to the right of the decimal
point.

 Without using another manipulator, the floating-point-


number value determines the output format.
8 - Uppercase/Lowercase Control (uppercase)

 Stream manipulator uppercase outputs an uppercase


X or E with hexadecimal-integer values or with
scientific notation floating-point values, respectively.

 Using stream manipulator uppercase also causes all


letters in a hexadecimal value to be uppercase.

 By default, the letters for hexadecimal values and the


exponents in scientific notation floating-point values
appear in lowercase.
 To reset the uppercase setting, output the stream
manipulator nouppercase.
9 - Specifying Boolean Format (boolalpha)

 C++ provides data type bool, whose values may be


false or true, as a preferred alternative to the old
style of using 0 to indicate false and nonzero to
indicate true.
 A bool variable outputs as 0 or 1 by default.

 However, we can use stream manipulator boolalpha


to set the output stream to display bool values as the
strings "true" and "false".

 Use stream manipulator noboolalpha to set the


output stream to display bool values as integers (i.e.,
the default setting).
SUMMARY
 Stream I/O
 Unformatted I/O with read, gcount and
write
 Stream Manipulators
 Stream Format States

43
The End

44
File-Oriented Input &
Output

CHAPTER 8

1
File-Oriented Input & Output

 Files and streams


 Creating a sequential access file
 Reading data from a sequential access
file
 Review on fundamentals of data files
 Processing text files
 Input of preformatted data from files
 Advantage use Files

2
File-Oriented Input & Output

 Concepts of Input and Output (I/O) File


 File I/O Steps
 Using I/O Files
 Classes for Stream I/O in C++
 File mode and file pointer
 Deal with text files – reading and
writing

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

 A file ends either with an EOF (end-of-file)


marker or at a specified byte number specified
by the system.
 When a file is opened, a stream is associated
with a file.
 Stream is a sequence of characters
 Streams provide communication channels
between files and the programs.
5
Files and Streams cont…
 A stream can also be used to access
devices.
 For example, when a program (any
program) is executed, 3 streams are
automatically opened:
 ofstream
 stream class to write on files
 Output stream (Program -> File)
 ifstream
 stream class to read from files
 Input stream (File -> Program)
 fstream
 stream class to both read/write from/to files
 Input & Output stream (Program -> File
OR/AND File -> Program)
6
Files and Streams cont…
 These functions are derived directly or indirectly
from the functions istream and ostream.
 We have already used objects whose types were
these functions: cin is an object of function
istream and cout is an object of function ostream.
Therefore, we have already been using functions
that are related to our file streams.
 And in fact, we can use our file streams the same
way we are already used to use cin and cout,
with the only difference that we have to associate
these streams with physical files.

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:

open (filename, mode);

Where filename is a string representing the name


of the file to be opened, and mode is an optional
parameter with a combination of the following
flags:
 All these flags can be combined using the bitwise operator
OR (|).

9
Creating a Sequential Access
Mode of Opening File

* All these flags can be


combined using the bitwise
operator OR (|).
10
Creating a Sequential Access File :
Opening Files

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

Chapter 7: File Processing 23


Detecting the End-of-File

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

You might also like