Introduction to C++ Programming Basics
Introduction to C++ Programming Basics
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 2
Language
▪ Human Language:
• Commonly used to express feelings and understand other
person expressions.
• It can be oral or gestural kind of communication
▪ Computer Language:
• Computer languages are the languages by which a user
command a computer to work on the algorithm which a user
has written to get an output.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 3
What is a program, programming, and
programmer?
▪ Program:
• Usually, one or more algorithms written in a programming
language that can be translated to run on a real machine.
• We sometimes call programs software.
• A computer program is a series of organized instructions that
directs a computer to perform tasks.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 4
What skills are required to become a
programmer?
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 6
Programming language
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 8
Generation of programming languages
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 9
Generation of programming languages
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 11
Programming paradigm
▪ Structured/modular Programming:
• Divides a program into a set of functions or modules.
• These functions have statements embraced inside curly braces.
• Each of these functions performs a subtask.
• Usually, as each function represents a specific functionality.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 13
Software development life cycle
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 15
Algorithm development
▪ Narrative: can be understood by any user who may not have any
knowledge of computer programming.
▪ Flowcharts: a diagram consisting of labelled symbols, together
with arrows connecting one symbols to another.
Terminal point marks the On-page Connector: used to connect
beginning or end of a program two points without drawing a flow line
Process: is used to
compute/calculate a process. Annotation flag: used to add
clarifying comments or descriptions
Decision: Indicates a yes/no
decision to be made by the program Inter-page Connector: used as exit or
entry from a flowchart on one page to
Input/output: is used to show input a flowchart in another page
or output data
Predefined Process: indicates a
process defined else where
Flow line: is used to show the
direction of logical flow
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 17
Algorithm development
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 18
Chapter Two
C++ Basics
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 19
Outlines
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 21
C++ Terminology and Syntax
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 22
C++ IDE /
The complete development cycle in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 23
C++ IDE /
The complete development cycle in C++
▪ Summary
▪ Start with C++ source code files (.CPP, .HPP/.H)
▪ Compile: convert source code to object code
• Object code stored in object file (.OBJ or .O)
▪ Link: combine contents of one or more object files (and
possibly some Libraries) to produce executable program
▪ Executable program can then be run directly
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 24
Structure of C++ Program
[Comments]
[Pre processor directives]
[Global variable declarations]
[Prototypes of functions]
[Definitions of functions]
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 25
Sample C++ Program Description
▪ // my first program in C++ is a comment
and do not have any effect on the
behaviour of the program.
▪ #include <iostream> tells the pre-
processor to include the iostream
standard file.
• basic standard input/output library in
C++
▪ using namespace std; all the elements of ▪ cout << "Hello World!"; This line is a
the standard C++ library are declared C++ statement.
within what is called a namespace, • cout is declared in the iostream
the namespace with the name std. standard file within the std
▪ int main () is the beginning of the namespace.
definition of the main function. ▪ return 0; causes the main function
▪ other functions with other names to finish.
defined before or after it. ▪ interpreted as the program
▪ the instructions within always be the worked as expected without
first ones to be executed. any errors during its execution.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 26
Input and Output (cin and cout respectively)
▪ Cout is an object used for printing data to the screen.
• The word cout followed by the insertion operator also called
output redirection operator (<<) and the object to be printed
on the screen.
• Syntax: Cout<<Object;
• The object at the right-hand side can be:
o A literal string: “Hello World”
o A variable: a place holder in memory
▪ Cin is an object used for taking input from the keyboard and
store it in the memory.
• The word cin followed by the input redirection operator (>>) and the
object name to hold the input value.
• Syntax: Cin>>Object;
▪ Both << and >> enabling multiple input or multiple output
operations to be combined into one statement.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 27
Keywords
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 29
Variables
• Example:
int i; int m; int i, j, k;
char ch;
double current_balance;
int num_stud = 31; //variable initialization
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 30
…cont. Variables
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 32
…cont. Basic Data Types
▪ Both the numeric data types offer modifiers that are used to
vary the nature of the data to be stored.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 33
…cont. Basic Data Types
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 34
…cont. Basic Data Types
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 35
Characters
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 38
Comments
▪ Comments are for the reader, not the compiler
▪ Two types:
• Single line
// This is a C++ program. It prints the sentence:
// Welcome to C++ Programming.
• Multiple line
/*
You can include comments that can
occupy several lines.
*/
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 41
...cont. Operators
▪ Assignment operators
Operator Description Expression
= Assignment Operator a=b
+= add and assign a+=b is equivalent to a=a + b
-= subtract and assign a-=b is equivalent to a=a - b
*= multiply and assign a*=b is equivalent to a=a * b
/= divide and assign a/=b is equivalent to a=a/b
%= mod and assign a%=b is equivalent to a=a % b
<<= Left shift AND assign a<<=5 is equivalent to a=a<<5
>>= Right shift AND assign a>>=5 is equivalent to a=a>>5
&= Bitwise AND assign a&=5 is equivalent to a=a&5
^= Bitwise exclusive OR and assign a^=5 is equivalent to a=a^5
|= Bitwise inclusive OR and assign a|=5 is equivalent to a=a|5
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 42
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 43
...cont. Operators
▪ Increment/decrement operator: In C++, ++ and — are
know as increment and decrement operators respectively.
▪ ++ adds 1 to operand and — subtracts 1 to operand
respectively.
▪ Example: int k = 5;
Operator Example Description Example
++k + 10
++ [prefix] ++a The value of a after increment
// gives 16
k++ + 10
++ [postfix] a++ The value of a before increment
// gives 15
--k + 10
— [prefix] –a The value of a after decrement
// gives 14
--k + 1
— [postfix] a– The value of a before decrement
// gives 14
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 44
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 45
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 46
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 47
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 48
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 49
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 50
...cont. Operators
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 52
Chapter Three
Control Statements
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 53
Outlines
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 57
C++ Selection Statements
if…else statement
Output:
i is 20
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 61
C++ Selection Statements
nested if statement
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 62
C++ Selection Statements
nested if statement
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 63
C++ Switch Case Statement
▪ Syntax:
switch (expression){
▪ In C++, switch case statement is case value1:
simplified form of the C++ Nested // statements
if else statement , it helps to avoid break;
long chain of if…else if...else case value2:
statements.
// statements
▪ A switch case statement evaluates break;
an expression against multiple default:
cases in order to identify the block // statements
of code to be executed.
break;
}
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 64
C++ Switch Case Statement
Output:
C++ Switch Case statement.
Today is Friday.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 65
Jump Statements
Introduction
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 66
Jump Statements
break
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 67
Jump Statements
continue
▪ The continue statement is opposite to that of break statement, instead of
terminating the loop, it forces to continue or execute the next iteration of
the loop.
▪ When the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped and next iteration
of the loop will begin.
▪ Syntax:
continue;
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 68
Jump Statements
continue
Output:
1 2 3 4 5 7 8 9 10
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 69
Jump Statements
goto
▪ The goto statement in C/C++ also referred to as unconditional jump
statement can be used to jump from one point to another within a
function.
▪ Syntax:
Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 70
Jump Statements
goto
Output:
1 2 3 4 5 6 7 8 9 10
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 71
Looping Statements
▪ Loop statements are used to execute the block of code repeatedly for
a specified number of times or until it meets a specified condition.
▪ Loop statement are very useful to iterate over collection/list of items
or to perform a task for multiple times.
▪ In C++, we have following loop statements available:
• For loop
• While loop
• Do…while loop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 72
Looping Statements
for loop
Start
▪ The for loop is used when we want to
execute block of code known times. The Initialization
for loop takes a variable as iterator and
assign it with an initial value, and iterate
through the loop body as long as the test Condition
False
condition is true.
▪ Syntax: True
Loop body
for(initialization; condition; incr/decr){
// loop body incr/decr
// Or statement(s)
} Stop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 73
Looping Statements
for loop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 74
Looping Statements
while loop
▪ Syntax:
while(condition){
// loop body
}
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 75
Looping Statements
while loop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 76
Looping Statements
do…while loop
▪ Syntax:
do{
// loop body
} while(condition);
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 77
Looping Statements
do…while loop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 78
Looping Statements
infinite loop
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 79
Chapter Four
C++ Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 80
Outlines
▪ Introduction
▪ User Defined Functions
▪ Function Prototype and Return Statement
▪ Integration of a Function
▪ Functions with Empty Parameter List
▪ Function Overloading
▪ The inline Functions
▪ C++ Standard Library Functions
▪ Passing Arguments by Value, by Reference, and by Pointer
▪ Recursive Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 81
Introduction
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 82
User-defined Function
▪ When the function is invoked from any part of the program, it all
executes the codes defined in the body of the function.
▪ Syntax:
returnType functionName (parameter1, parameter2,...) {
// function body
}
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 83
User-defined Function
▪ Return Type − A function may return a value. The return type is the
data type of the value the function returns.
• Some functions perform the desired operations without returning a value.
• In this case, the return type is the keyword void.
▪ Function Name − This is the actual name of the function. The
function name and the parameter list together constitute the
function signature.
▪ Parameters − A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to
as actual parameter or argument.
▪ The parameter list refers to the type, order, and number of the parameters
of a function.
▪ Parameters are optional; that is, a function may contain no parameters.
▪ Function Body − The function body contains a collection of
statements that define what the function does.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 84
User-defined Function: Function Declaration
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 86
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 87
User-defined Function: Function Calling
▪ Function Parameters/Arguments
• The type of the arguments passed while calling the function
must match with the corresponding parameters defined in the
function declaration.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 88
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 89
User-defined Function: Function Calling
▪ Actual Parameters are the parameters that appear in the function
call statement.
▪ Formal Parameters are the parameters that appear in the declaration
of the function which has been called.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 90
User-defined Function: Function Calling
• Both the actual and formal parameters have their own copies of
values, therefore any change in one of the types of parameters
will not be reflected by the other.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 91
User-defined Function: Function Calling
▪ Call by Value:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 93
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 94
User-defined Function: Function Calling
▪ Call by Reference:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 95
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 96
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 97
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 98
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 99
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 100
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 101
User-defined Function: Function Calling
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 102
User-defined Function: Function Calling
▪ Constant Arguments:
▪ Just like we can declare constant variables, C++ also allows us to
declare constant arguments which cannot be modified in the
function.
▪ For example:
float example (int day, int month, const int year = 2005);
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 103
User-defined Function: Function Calling
▪ Return Statement
▪ In the below program, the add() function is used to find the sum of two
numbers.
▪ We store the returned value of the function in the variable sum.
▪ Note: sum is a variable of int type. This is because the return value of add()
is of int type.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 104
User-defined Function: Function Calling
▪ Function Prototype
▪ In C++, the code of function declaration should be before the function
call. However, if we want to define a function after the function call,
we need to use the function prototype.
▪ This provides the compiler with information about the function name
and its parameters.
▪ The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 105
Benefits of User-defined Function
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 106
C++ Library Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 107
C++ Library Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 108
Function Overloading
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 109
Function Overloading
▪ Notice that the return types of all these 4 functions are not the same.
▪ Overloaded functions may or may not have different return types but
they must have different arguments.
▪ For example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 110
Function Overloading
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 111
Function Overloading
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 112
Inline Functions
▪ C++ enable you to use inline functions that expand into their
statements. Thus, inline functions offer faster execution time
especially helpful where speed is critical at the cost of expanding the
code.
▪ An inline function is a function that is expanded in line when it is
called.
▪ When the inline function is called whole code of the inline function
gets inserted or substituted at the point of the inline function call.
▪ This substitution is performed by the C++ compiler at compile time. .
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 113
Inline Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 114
Inline Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 115
Inline Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 116
Recursive functions
▪ A function that calls itself, and doesn't perform any task after
function call, is known as tail recursion. In tail recursion, we
generally call the same function with return statement.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 117
Recursive functions: Types of Recursion
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 118
Recursive functions: Types of Recursion
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 119
Recursive functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 120
Recursive functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 121
Recursive functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 122
Exercises
1. Write a program to take two numbers say, ‘x’ and ‘y’ from the
user and add these numbers using a function and then
display the sum of these two numbers on the screen.
2. Write a program which declares a function ‘int accept(int a,
int b, int c);’ which accepts three parameters ‘a’, ‘b’ and ‘c’
inputted by the user and returns the value obtained by
computing value of the expression ‘a * b +c’ to the main
program which displays the returned value.
3. Write a program to find the roots of a quadratic equation.
Assume that the quadratic equation only has unequal or
equal roots. The program should use separate set of functions
to determine whether the equation has equal or unequal
roots.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 123
Exercises
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 125
Part I
Arrays in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 126
Outlines
▪Arrays in C++
• What does it mean?
• Declaration of an Array
• Accessing Elements of an Arrays
• Input/Output of an Array
• Searching a Value in an Array
• Address of an Array
• Multidimensional arrays
• Two Dimensional Arrays
• Three Dimensional Arrays
• Passing an Array to a Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 127
Overview of C++ Arrays
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 128
Overview of C++ Arrays
Array Indices 0 1 2 3 4
Array Data 10.0 2.0 3.4 17.5 50.6
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 132
Accessing Elements of an Array
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 133
Address of an array
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 134
Address of an array
cout << section; //returns the address of an array section/address of section [0]
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 135
Address of an array
cout << section+1; //returns the address of the second element (i.e. section [2]).
cout << section+2; //returns the address of the third element (i.e. section [3]).
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 136
Multidimensional Arrays
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 137
Multidimensional Arrays
▪ Two-dimensional array example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 138
Multidimensional Arrays
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 139
Passing arrays as an argument
▪ C++ does not allow to pass an entire array as an argument to
a function. However, you can pass a pointer to an array by
specifying the array's name without an index.
▪ If you want to pass a single-dimension array as an argument
in a function, you would have to declare function formal
parameter in one of following three ways and all three
declaration methods produce similar results because each
tells the compiler that an integer pointer is going to be
received.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 140
Passing arrays as an argument
▪ Way 1: Formal parameters as a pointer as follows:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 141
Passing arrays as an argument
▪ By passing a particular element of the array to the function
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 142
Passing arrays as an argument
▪ By passing the whole array to the function:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 143
Passing arrays as an argument
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 144
[Link]
s/cpp/strings-in-cpp/
Part 2
C++ String
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 145
Outlines
▪Strings in C++
• Overview
• The C-style character string
• String vs. Character Array
• Concatenation of Strings
• Passing Strings to Functions
• C++ Built-in String Functions
• Operations of C++ Strings
• Input functions
• Capacity Functions
• Iterator Functions
• Manipulating Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 146
Overview of C++ Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 147
The C-style character string
▪ The C-style character string originated within the C
language and continues to be supported within C++.
▪ This string is actually a one-dimensional array of characters
which is terminated by a null character ‘\0’.
▪ Thus a null-terminated string contains the characters that
comprise the string followed by a null.
▪ The following declaration and initialization create a string
consisting of the word "Hello". To hold the null character at
the end of the array, the size of the character array
containing the string is one more than the number of
characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0’};
char greeting[] = "Hello";
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 148
The C-style character string
▪ Alternatively, we have:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 150
The C-style character string
▪ Example
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 152
The String Class in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 153
String vs. Character Array
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 155
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 156
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 157
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 158
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 159
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 160
Concatenation of Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 162
Passing Strings to Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 163
C++ Built-in String Functions
Functions Description
int length() Used to find the string length
void swap(string& str1) Used to swap the values of 2 strings
int compare(const Used to compare 2 strings
string& str1)
string substr(int Used to create a new string of a given
position, int length) length
int size() Used to find the string length in
terms of bytes
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 164
C++ Built-in String Functions
Functions Description
void resize(int length) Used to resize the string length up to
the given no. of characters
string& replace(int pos, Used to replace a portion of the
int n, string& str1) string that begins at position pos and
is of the length of n characters
string& append(const Used to add new characters at the
string& str1) end of a string
char& at(int position) Used to access an individual
character at the given position
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 165
C++ Built-in String Functions
Functions Description
int find(string& str1, int Used to find the string given in the
position, int len) parameter
int find_first_of(string& str1, Used to find the first occurrence of the
int position, int len) given sequence
int find_first_not_of(string& Used to search the string for the first
str1, int position, int n) character that does not match any
characters specified in the string
int find_last_of(string& str1, Used to search the string for the last
int position, int n) character of the sequence specified
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 166
C++ Built-in String Functions
Functions Description
int find_last_not_of(string& Used to search for the last character that
str1, int position) does not match with the sequence
specified
string& insert() Used to insert a new character before the
character indicated at the given position
int max_size() Used to get the maximum length of a
string
void push_back(char c) Used to add a new character at the end of
a string
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 167
C++ Built-in String Functions
Functions Description
void pop_back() Used to remove the string's last character
string& assign() Used to assign new value to a string
int copy(string& str1) Used to copy the contents of a string into
another
begin() Used to return the first character's reference
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 168
C++ Built-in String Functions
Functions Description
void clear() Used to remove string's all elements
const_iterator cbegin() Used to point to the string's first element
const_iterator cend() Used to point to the string's last element
const_reverse_iterator Used to point to the string's last character
crbegin()
bool empty() Used to check if the string is empty or not
string& erase() Used to remove the characters
const_char* data() Used to copy the string's characters into an
array
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 169
C++ Built-in String Functions
Functions Description
char& front() Used to return a reference of the string's first
character
string& operator=() Used to assign a new value to a string
string& operator+=() Used to insert a new character at the end of a
string
char Used to retrieve a character at the position
operator[](position) specified
int rfind() Used to search for the string's last occurrence
iterator end() Used to reference the string's last character
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 170
C++ Built-in String Functions
Functions Description
reverse_iterator rend() Used to point to the string's first character
void shrink_to_fit() Used to reduce the capacity of the container
and make it equal to the size of the string
char* c_str() Used to return pointer to an array containing
null-terminated character sequence
const_reverse_iterator Used to reference the first character of the
crend() string
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 171
C++ Built-in String Functions
Functions Description
allocator_type Used to return the allocated object connected
get_allocator(); with a string
reverse_iterator rbegin() Used to reference the last character of a string
void reserve(int length) Used to reserve the vector capacity
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 172
Operations of C++ Strings
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 174
C++ String Input Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 175
C++ String Input Functions
▪getline()- Example
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 176
C++ String Input Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 177
C++ String Input Functions
▪push_back()- Example
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 178
C++ String Input Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 179
C++ String Input Functions
▪pop_back()- Example
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 180
C++ String Capacity Functions
▪ The C++ string capacity functions help to work with the size
and capacity of the string. The primary functions of the
capacity type are:
Functions Description
capacity() Returns the capacity allocated to a string by the
compiler
resize() Allows increasing or decreasing the size of the
string
length() Returns the size of the string
shrink_to_fit() Decreases and makes the capacity equal to the
minimum to save memory
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 181
C++ String Capacity Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 182
C++ String Capacity Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 183
C++ String Capacity Functions
▪resize(): It is used to either increase or decrease the size of a
string.
▪ In the below example, we used the resize() function to change the
number of characters in the string. Because we had specified the
first ten characters in resize(), all the characters after the first 10
were removed from the string.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 184
C++ String Capacity Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 185
C++ String Capacity Functions
• shrink_to_fit():
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 186
C++ String Iterator Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 188
C++ String Iterator Functions
▪end(): This function returns an iterator that points to the end of the
string. The iterator will always point to the null character.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 189
C++ String Iterator Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 190
C++ String Iterator Functions
• rbegin(): Example-
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 191
C++ String Iterator Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 192
C++ String Manipulating Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 194
C++ String Manipulating Functions
▪ copy(): Example-
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 195
C++ String Manipulating Functions
▪ swap(): It swaps one string with another.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 196
1. [Link]
2. [Link]
3. [Link]
4. [Link]
Part 3
C++ Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 197
Outlines
▪Pointers in C++
• Overview
• Declaring pointers
• Assigning values to pointers
• Pointer to void
• Invalid pointers
• Null pointers
• Arrays of pointers
• Pointers and arrays
• Pointer arithmetic
• Pointer and string
• Pointer to pointer
• Dynamic memory
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 198
Overview
▪ Note: The reason we declare data types of pointers is to know how many
bytes of data is used by the variable it stores the address of. If we increment
(or decrement) a pointer, we increase (or decrease) the pointer by the size
of the data type it points to.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 199
Overview
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 200
Reference Operator and Dereference Operator
▪ Output:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 202
Reference Operator and Dereference Operator
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 204
Pointer Declaration Syntax
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 205
How to use Pointers in C++?
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 207
Ways to Pass C++ Arguments to a Function
• Call By Value
• Call By Reference with Pointer Argument
• Call By Reference with Reference Argument
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 208
Ways to Pass C++ Arguments to a Function
▪Call By Value
▪ By default, C++ uses the call by value method.
▪ This method copies the real value of an argument into
the function's parameter.
▪ So, if the parameter inside the function is changed, it will
not affect the argument.
▪ From the below example, we can observe that the address
of variable var was different inside the function triple().
Also, altering var inside the function triple() did not have
any impact on var present in the main() function.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 209
Ways to Pass C++ Arguments to a Function
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 210
Ways to Pass C++ Arguments to a Function
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 212
Ways to Pass C++ Arguments to a Function
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 214
Void Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 216
Void Pointers
▪ In the following example, we declared a void pointer variable and a
float variable. Then, we stored the address of the float variable in the
void pointer variable.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 217
Invalid Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 219
NULL Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 220
NULL Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 221
Arrays of pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 223
Arrays and Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 224
Arrays and Pointers
▪ The addresses for the rest of the array elements are given by
&arr[1], &arr[2], &arr[3], and &arr[4].
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 225
Arrays and Pointers
▪ Point to Every Array Elements
▪ Suppose we need to point to the fourth element of the
array using the same pointer ptr.
▪ Here, if ptr points to the first element in the above
example then ptr + 3 will point to the fourth element.
▪ For example,
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 226
Arrays and Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 227
Arrays and Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 228
Arrays and Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 229
Arrays and Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 230
Pointer Expressions and Pointer Arithmetic
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 231
Pointer Expressions and Pointer Arithmetic
▪ Example 1: Using Increment Operator
• When we increment a pointer using the increment
operator (++), the address of the pointer increases. The
increase in address of the pointer is equal to the size of its
data type.
• As all the elements of the array are stored in contiguous
memory, we can use the increment operator on pointers to
access the elements of an array.
• In the example, we used ptr++ to access each element of the
array arr. Since ptr had an int type, the address was
increased by 44 (because size of an int is 44 ) when we
used ptr++.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 232
Pointer Expressions and Pointer Arithmetic
▪ Example 1: Using Increment Operator
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 233
Pointer Expressions and Pointer Arithmetic
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 235
Pointer Expressions and Pointer Arithmetic
▪ Example 3: Addition and Subtraction
• If we add 3 to a pointer (ptr + 3), the pointer will point to
the memory address located 3 places ahead of the current
address. In other words, the pointer will point to an
address that is three times the size of the pointer's data
type ( 3 * size_of_pointer_type).
• The subtraction operation is similar to addition. In case of
the subtraction operation in pointers, if we subtract 1 from
the pointer (ptr - 1), the pointer will point to the previous
memory address.
• In the following example, ptr1 + 2 is equivalent to &arr[2],
and ptr2 - 1 is equivalent to &arr[3].
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 236
Pointer Expressions and Pointer Arithmetic
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 237
Pointer Expressions and Pointer Arithmetic
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 238
Pointer Expressions and Pointer Arithmetic
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 239
Pointer Expressions and Pointer Arithmetic
▪ Example 5: Pointer Comparison
• Pointers can be compared using relational operators,
such as ==, <, >, <= and >=. If two pointers are related to
each other such as pointing to the elements of same
array, then they can be compared meaningfully.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 241
Pointer Expressions and Pointer Arithmetic
▪Programming Exercises:
1. Write a program that initializes integer values to an
array and displays the value of the array on the screen
using pointer notation and pointer arithmetic in C++.
2. Write a program that inputs values into an array and
displays the odd value of array on screen using pointer
notation and pointer arithmetic in C++.
3. Write a program that inputs value into array and
display in reverse order on screen using pointer
notation and pointer arithmetic in C++.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 242
Pointer and string
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 245
Common Mistakes When Working With Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 247
Advantages of Using Pointers
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 248
Conclusion
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 250
Outline
▪ Introduction
▪ Defining the structure
▪ Accessing Structure Members
▪ Single Structure
▪ Arrays of Structure
▪ Structures as Function Arguments
▪ Pointers to Structs
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 251
User Defined Data Types
▪ Structure
• Member of the structure
• Variables
• Functions
▪ Class
• Member of the class
• Variables
• Functions
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 252
Introduction
• C++ struct, short for C++ Structure, is an user-
defined data type available in C++. It allows a user
to combine data items of (possibly) different data
types under a single name.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 253
How to create a structure?
▪ Syntax:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 256
Access Structure Members
▪ To access members of a structure, use the dot syntax (.):
▪ Example: Assign data to members of a structure and
print it:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 257
An array of structures
▪ Like other primitive data types, we can create an array
of structures.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 258
Structures as function arguments
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 259
Structures as function arguments
▪ Example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 261
Structures as function arguments
Example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 262
Structures as function arguments
Example: Output
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 263
A structure pointer
▪ Like primitive types, we can have pointer to a structure.
If we have a pointer to structure, members are accessed
using arrow ( -> ) operator instead of the dot (.)
operator.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 264
Chapter Seven
File Management in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ 265
What is File Handling in C++?
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 266
What is File Handling in C++?
▪ Almost every programming language has a ‘File
Handling’ method to deal with the storage of data.
In this article, we will learn about file handling in
C++. But, before that, if you are a newbie at C++, you
could check out this free course on C++ to learn the
basics.
▪ Now, This topic of file handling is further divided
into sub-topics:
• Create a file
• Open a file
• Read from a file
• Write to a file
• Close a file
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 267
fstream library
▪ Before diving into each sub-topics, let us first learn about
the header file we will be using to gain access to the file
handling method.
▪ In C++, fstream library is used to handle files, and it is dealt
with the help of three classes:
• ifstream: This class helps create and write the data to the
file obtained from the program’s output. It is also known as
the input stream.
• ifstream: We use this class to read data from files and also
known as the input stream.
• fstream: This class is the combination of both ofstream
and ifstream. It provides the capability of creating, writing
and reading a file.
▪ To access the following classes, you must include the
fstream as a header file like how we declare iostream in the
header.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 268
File Operations in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 269
Opening files in C++
▪ To read or enter data to a file, we need to open it first.
This can be performed with the help of ‘ifstream’ for
reading and ‘fstream’ or ‘ofstream’ for writing or
appending to the file. All these three objects have
open() function pre-built in them.
▪ Syntax: open( FileName , Mode );
▪ FileName – It denotes the name of file which has to
be opened.
▪ Mode – There different mode to open a file and it
explained in the next slide.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 270
Opening files in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 271
Opening files in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 272
Opening files in C++
▪ Example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 273
Writing to file in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 275
Reading from file in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 276
Reading from file in C++
▪ Example:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 277
Closing a file in C++
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 278
File Position Pointers
▪ When our program reads and writes files Randomly,
it treats the file like a big Array. with arrays, we know
we can add, print, or remove values in any order. we
don't have to start at the first array element,
sequentially looking at the Next one, until we get the
Element we need. We can view our
▪ Random-access-file in the same way, accessing the
data in any order. In Random Access file:
▪ We Can Read from Anywhere from the file.
▪ We Can Write to Anywhere in the file.
▪ We can Modify our record.
▪ We can Search any Record from file.
▪ And we can Delete Any record from file:
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 279
File Position Pointers
▪ Special function to move File-Pointer within the File:
Function Syntax Description
seekg() [Link]( We can move input pointer to a specified location
long_num, for reading by using this function. fileObject is the
origin); pointer to the file that we want to access. long_num
is the number of bytes in the file we want to skip.
and origin is a value that tells to compiler, where to
begin the skipping of bytes.
seekp() [Link]( We can move Output pointer to a specified location
long_num, by using this function. it's same like seekg()
origin); Function but in Case of writing:
tellg() [Link](); This function return the current position of Input
pointer. this function don't need any argument.
tellg() [Link](); This function return the current position of Output
pointer. this function don't need any argument.
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 280
File Position Pointers
▪ origin from the syntax of file pointers is the value that
tells Compiler, where to begin the skipping of bytes
specified by long_num . Origin can be any of the three
values shown in the table below.
Function Description
bad() Returns True if an Error occurs while reading or writing
Operation. (Example: in case we try to write to a file that is
not open for writing or if the device where we try to write
has no space left).
fail() Returns true in the same cases as bad() plus in case that a
format error happens. (as trying to read an integer number
and an alphabetical character is received:).
eof() Returns true if a file opened for reading has reached the end.
good() Return False in the same cases in which calling any of the
previous functions would return true
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 281
File Position Pointers
▪ origin from the syntax of file pointers is the value that
tells Compiler, where to begin the skipping of bytes
specified by long_num . Origin can be any of the three
values shown in the table below.
Function Syntax Description
ios::beg [Link] Go to Start: No matter how far into a file we
kg(0, have read, by using this Syntax, the file-
ios::beg); pointer will back to the beginning of the file.
ios::cur [Link] Stay at Current Position: Using this syntax,
kg(0, ios::cur); the filepointer will show its current
position.
ios::end [Link] Go to End of the file: using this syntax, the
kg(0, file-pointer will point to end of the file.
ios::end);
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 282
File Position Pointers – Examples
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 283
File Position Pointers – Examples
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 284
File Position Pointers – Examples
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 285
Error Handling in C++ Files
▪ In our each example, we are trying to use error checker to
avoid error, and it's really good for us and for our program.
C++ provides it's self some function, which can help us to
reduce our error in our program
Function Description
bad() Returns True if an Error occurs while reading or writing
Operation. (Example: in case we try to write to a file that is
not open for writing or if the device where we try to write
has no space left).
fail() Returns true in the same cases as bad() plus in case that a
format error happens. (as trying to read an integer number
and an alphabetical character is received:).
eof() Returns true if a file opened for reading has reached the end.
good() Return False in the same cases in which calling any of the
previous functions would return true
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 286
Other Functions in C++ Files
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 287
Other Functions in C++ Files
2. Read(): his function is used with Input-Pointer object
to read the block of data. It's same like read()
Function, but in sense of reading.
• Syntax: read( (char *) &Obj, sizeof(Obj));
3. Remove(): This Function is used to remove any file
from record. it take one argument, which is the file
Name to be delete.
• Syntax: read( (char *) &Obj, sizeof(Obj));
4. Rename(): This function is used to rename any file. it
take two argument, first is the Old Name of file, and
the other is New name for that file.
• Syntax: rename(Old_Name, New_Name);
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 288
Thank You!!!
Any ???
@ WDU: WiT: School of Computing: Programming Chair 2023 Computer Programming in C++ Slide 289