SlideShare a Scribd company logo
Wolkite University
Fundamentals of Programming II
CoSc1014
Chapter-One
Functions
Melaku Kore
melaku.kore@gmail.com
What is Function?
 C ++ enables its programmers to break up a program into segments commonly known as functions, each of
which can be written more or less independently of the others.
 A function is a group of statements that together perform a task.
 Every function in the program is supposed to perform a well-defined task.
 Every C++ program has at least one function, which is main(), and all the most trivial programs can define
additional functions.
 A function is a block of code designed to tackle a specific problem.
 One of the best ways to tackle a problem is to start with the overall goal, then divide this goal into several
smaller tasks. You should never lose sight of the overall goal, but think also of how individual pieces can fit
together to accomplish such a goal.
 Function makes a program much easier to read, test and debug
Cont…
 In the figure, we can see that main() calls a function named func1().
 Therefore, main() is known as the calling function and func1() is known
as the called function.
 The moment the compiler encounters a function call, the control jumps to
the statements that are a part of the called function.
 After the called function is executed, the control is returned to the calling
program.
Cont…
The main() function can call as many functions as it wants and as many
times as it wants.
For example, a function call placed within a for loop, while loop, or do–
while loop may call the same function multiple times till the condition
holds true.
Not only main(), any function can call any other function.
Why?
Dividing the program into separate well-defined functions facilitates each
function to be written and tested separately.
Understanding, coding, and testing multiple separate functions is easier than
doing the same for one big function.
When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload by
writing different functions.
Like C/C++ libraries, programmers can also write their own functions and use
them from different points in the main program or any other program that needs
its functionalities.
C++ functions generally adhere to the following rules:
1. Every function must have a name.
2. Function names are made up and assigned by the programmer following the same
rules that apply to naming variables. They can contain up to 32 characters, they must
begin with a letter, and they can consist of letters, numbers, and the underscore (_)
character.
3. All function names have one set of parenthesis immediately following them. This
helps you (and C++ compiler) differentiate them from variables.
4. The body of each function, starting immediately after parenthesis of the function
name, must be enclosed by braces.
Components of Function
 Function declaration :-Before using a function, the compiler must know the
number of parameters and the type of parameters that the function expects to
receive and the data type of value that it will return to the calling program.
Placing the function declaration statement prior to its use enables the compiler to
make a check on the arguments used while calling that function.
It is the interface of a function (also called function prototype) specifies how it
may be used.
Function declaration is required when you define a function in one source file and
you call that function in another file. In such case, you should declare the function
at the top of the file calling the function.
return_type function_name( parameter list );
Cont…
return_type:-specifies the data type of the value that will be returned to the calling
function as a result of the processing performed by the called function.
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.
Parameter names are not important in function declaration only their type is required.
Cont…
A function definition consists of two parts: interface (prototype or function
header ) & body.
The function header is same as the function declaration. The only difference
between the two is that a function header is not followed by a semi-colon.
Function Body − The function body contains a collection of statements that define
what the function does. Syntax of function definition
return_type function_name( parameter list )
{
body of the function
}
If function definition is done before the main function, then there is no need to put the
prototype, otherwise the prototype should be script before the main function starts
Function Calling
Calling a function means making the instruction of the function to be executed.
While creating a C++ function, you give a definition of what the function has to do.
When a function call is executed, the arguments are first evaluated and their resulting
values are assigned to the corresponding parameters.
The function call statement invokes the function.
When a function is invoked, the compiler jumps to the called function to execute the
statements that are a part of that function.
Once the called function is executed, the program control passes back to the calling
function.
Function calling
The following points are to be noted while calling a function:
 Function name and the number and the type of arguments in the function call must be same
as that given in the function declaration and the function header of the function definition.
Names (and not the types) of variables in function declaration, function call, and header of
function definition may vary.
Arguments may be passed in the form of expressions to the called function. In such a case,
arguments are first evaluated and converted to the type of formal parameter and then the
body of the function gets executed.
 If the return type of the function is not void, then the value returned by the called function
may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Example
1. Write a program to find whether a number is even or odd using functions.
int evenodd(int); Function Declaration
int main()
{
int num, flag;
cout<<"n Enter the number : ";
cin>>num;
flag = evenodd(num); Function calling
if (flag == 1)
cout<< num <<" IS EVEN";
else
cout<< num<<―IS ODD";
return 0;
}
int evenodd(int a) // Function header
{
// Function body
if(a%2 == 0)
return 1;
else
retun 0;
}
Example
2. Write a function which calculates the area of rectangle. Note the dimensions of
the polygon should be provided from the user.
void AreaRectangle (int l,int w);
void main()
{
int length,width,area;
cout<<Enter Length and width of rectangle‖;
cin>>length>>width;
AreaRectangle(length,width);
}
void AreaRectangle (int l,int w)
{
int area;
area=l*w;
cout<<―The area of rectangle is=‖<<area;
}
Example 2
3 . Write a function which return the maximum of two numbers. Note that the numbers should be
provided from the user.
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
void main()
{
int FirstNum,SecondNum, maximum;
cout<<―Enter the two numbers‖;
cin>> FirstNum>>SecondNum;
maximum=max(FirstNum,SecondNum);
cout<<―Maximum of two numbers is=‖<<maximum;
}
Home Work
3. Write C++ program using function which perform all arithmetic operations for two
numbers.
Note:- 1. Use different functions for each operation
2. Check divide by zero exception (If denominator is zero your program display error
message).
3. Your program display menu for the user to select the operation.
Function Parameters
A parameter is like a placeholder.
Arguments or parameters are divided into two: Formal and Actual parameters
o When a function is called some parameters are written within the parenthesis . These are
know as actual parameters.
eg AreaRectangle (length, width);
o Formal parameters are those who are written in the function header.
eg void AreaRectangle (int length,int width);
The formal parameter and the variable which declare inside the body of function are created when
function called and they exist only upto control remain on the function.
We can give same name for actual and formal parameters but their implementation is different.
 If in any function there is no formal parameters then we can write void instead.
Passing Arguments
There are 2 ways to pass arguments into a function
1. Passing By value :- The value of the actual parameter is passed to formal
parameters when we call the function.
• In this method, the called function creates new variables to store the value of the
arguments passed to it.
• Therefore, the called function uses a copy of the actual arguments to perform its
intended task.
• If the called function is supposed to modify the value of the parameters passed to
it, then the change will be reflected only in the called function.
Cont…
• In the calling function, no change will be made to the value of the variables. This is because all the
changes are made to the copy of the variables and not to the actual variables.
void add(int n);
int main()
{
int num = 2;
cout<<"nThe value of num before calling the function "<< num;
add(num);
cout<<"nThe value of num after calling the function = "<<num;
return 0;
}
void add(int n)
{
n = n + 10;
cout<<"n The value of num in the called function = "<< n;
}
Cont…
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 2
Following are the points to remember while passing arguments to a function using the
call-by value method:
 When arguments are passed by value, the called function creates new variables of the
same data type as the arguments passed to it.
 The values of the arguments passed by the calling function are copied into the newly
created variables.
 Values of the variables in the calling functions remain unaffected when the arguments
are passed using the call-by-value technique.
Cont…
2. Passing By Reference
In this method, we declare the function parameters as references rather than normal
variables.
When this is done, any changes made by the function to the arguments it received are also
visible in the calling function.
To indicate that an argument is passed using call by reference, an asterisk (*) is placed
after the type in the parameter list.
A reference parameter, on the other hand, receives the argument passed to it and works on
it directly.
Any change made by the function to a reference parameter is in effect directly applied to
the argument.
Cont…
void add(int *n);
int main()
{
int num = 2;
cout<<"nThe value of num before calling the function "<< num;
add(&num);
cout<<"nThe value of num after calling the function = "<<num;
return 0;
}
void add(int *n)
{
*n = *n + 10;
cout<<"n The value of num in the called function = "<< n;
}
Output
The value of num before calling the function = 2
The value of num in the called function = 12
The value of num after calling the function = 12
Exercise :- What is the output of this program ?
void swap_call_val(int, int);
void swap_call_ref(int *, int *);
int main()
{
int a=1, b=2, c=3, d=4;
cout<<"n In main() a = "<<a<<" and b = "<<b;
swap_call_val(a, b);
cout<<"n In main() a = "<<a<<" and b = "<<b;
cout<<"nn In main() c = "<<c<<" and d = "<<d;
swap_call_ref(&c, &d);
cout<<"n In main() c =“<<c <<"and d =“<<d;
return 0;
}
void swap_call_val(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
cout<<"n In function (Call By Value Method) – a = "<<a <<"and b = "<<b;
}
void swap_call_ref(int *c, int *d)
{
int temp;
temp = *c;
*c = *d;
*d = temp;
cout<<"n In function (Call By Reference Method) – c ="<<c<<" and d = "<<d,
}
Global versus local variables
1. Local variables:
Variables that are declared inside a function or block are local variables.
 They can be used only by statements that are inside that function or block of code.
 Local variables are not known to functions outside their own.
2. Global variables;
Global variables are defined outside of all the functions, usually on top of the
program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration.
Example
void sum ();
int c; // global variable declaration:
int main () {
// local variable declaration:
int a, b,c1;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
sum();
return 0;
}
void sum()
{
int x=25;
int y=45;
c1=x+y; // error
cout<<―The sum is =‖<<c1;
}
Cont…
It‘s possible to declare local and global variables of the same name.
C++ provides the unary scope resolution operator (::) to access a global variable
when a local variable of the same name is in scope.
The unary scope resolution operator cannot be used to access a local variable of
the same name in an outer block.
A global variable can be accessed directly without the unary scope resolution
operator if the name of the global variable is not the same as that of a local
variable in scope.
Example
#include <iostream>
using namespace std;
int num =15;
int main()
{
double num=77.5;
// display values of local and global variables
cout << "Local double value of number = " <<num;
cout<< "nGlobal int value of number = " <<::num << endl;
} // end main
Output
Local double value of number =77.5
Global int value of number = 15
Const Argument
In C++ we can declare constant like the following
const datatype variable _name ;
const is a reserved word and any variable declared with this keyword is can‘t be modified.
While trying to modify any constant argument the compiler gives syntax error which
detect that the argument is non-modifiable value.
eg
int Add (const int c)
{
c=c+3;// error
}
Defualt argument
 A function in C++ can be called without specifying all its arguments.
In such cases the function declaration must provide default values for those
arguments that are not specified.
The compiler look at the prototype to see how many arguments a function uses
and alerts the program for possible default values.
Default argument must be added from right to left, we can not provide a default
value to a particular argument in the middle or first of an argument list.
Eg float Add(int a,int b=2,int c=5);
float Add(int a,int b=2,int c); // illegal
Example
float func(float p,int n,float r=50);
void main()
{
float p,r,A;
int n;
cout<<―Enter the value of P and n‖;
cin>>p>>n;
A=func(p,n);
cout<<―The value of A for default value of r is =‖<<A;
cout<<―Enter the value of p, n and r‖;
cin>>p>>n>>r;
A=func(p,n,r);
cout<<―The value of A for default value of r is =‖<<A;
}
// Function definition
float func(float p,int n,float r)
{
float temp=1+r/100;
float final=p*pow(temp,n);
return final;
}
1. Write a function which calculates A where A=P*(1+r/100)n for data p,r
and n having fixed value of 50.
Function overloading
Two or more functions having same name but different argument(s) are known as
overloaded functions.
 It allows the programmer to write functions to do conceptually the same thing on
different types of data without changing the name.
The overloaded function should be different interns of number of arguments, data
type of the arguments and order of argument lists.
If two or more functions differ only in their return types, C++ can‘t overload them.
 To be execute the compiler identifies the overloaded function based on the
difference they encounter while the function is invoked.
Example
// Overloaded functions based on argument type
int square(int x)
{
return x*x;
}
double square(double x)
{
return x*x;
}
int main()
{
cout<<"The square of integer 7 is"<<square(7);
cout<<"nThe square of double 7.5 is"<<square(7.5);
return 0;
}
Exercise
1. Write a function which prints area of rectangle and circle using function overloading.
While developing the function the value of pi is constant.
2. What is the output of this segment code of program
void func1(int a, int b)
{
a*=2;
b+=10;
cout<<―a=―<<a<‖ and b= ‖<<b<<endl;
}
void func2(int *x, int *y)
{
*x*=2;
*y+=10;
cout<<―x=―<<*x<‖ and y= ‖<<*y<<endl;
}
int main(void)
{
int i=10,j=40;
cout<<―i=―<<i<‖ and j= ‖<<j<<endl;
func1(i,j);
cout<<―i=―<<i<‖ and j= ‖<<j<<endl;
func2(&i,&j);
cout<<―i=―<<i<‖ and j= ‖<<j<<endl;
}
Recursion Function
A recursive function is one that calls itself.
void message(void)
{
cout << "This is a recursive function.n";
message();
}
The function above displays the string "This is a recursive function.", and then calls itself.
The function is like an infinite loop because there is no code to stop it from repeating.
Like a loop, a recursive function must have some algorithm to control the number of
times it repeats.
Cont…
void message(int times)
{
if (times > 0)
{
cout << "This is a recursive function.n";
message(times - 1);
}
return;
}
The function contains an if/else statement that controls the repetition.
As long as the times argument is greater than zero, it will display the message and
call itself again.
Each time it calls itself, it passes times - 1 as the argument.
Cont..
For example, let's say a program calls the function with the following statement:
Message(5);
The Recursive Factorial Function
In mathematics, the notation n! represents the factorial of the number n. The factorial of a
number is defined as:
n! = 1 * 2 * 3 * ... * n if n > 0
1 if n = 0
 Another way of defining the factorial of a number, using recursion, is:
Factorial(n) = n * Factorial(n - 1) if n > 0
1 if n = 0
The following C++ function implements the recursive definition shown above:
int factorial(int num)
{
if (num > 0)
return num * factorial(num - 1);
else
return 1;
}
Cont…
// Function prototype
int factorial(int);
void main(void)
{
int number;
cout << "Enter an integer value and I will displayn";
cout << "its factorial: ";
cin >> number;
cout << "The factorial of " << number << " is ";
cout << factorial(number) << endl;
}
int factorial(int num)
{
if (num > 0)
return num * factorial(num - 1);
else
return 1;
}
Storage classes
The storage class of a variable tells about which part of a program can access it
and also tells about its existence.
In C++ the storage classes are the following:
I. Automatic
II. Static
III. External
IV. Register
Automatic
A variable is defined within a function
Also known as local variable
A keyword auto is used to specify automatic variable but we can skip the word
auto also.
Cont…
The general syntax for automatic variable is :
auto datatype variable_name;
An automatic variable is created only when the function is called in which they are
defined and automatically destroyed when we return from the function.
The time period between the creation and destruction of a variable is called
lifetime.
The lifetime of automatic variable is the execution time of the function.
But if automatic variable is inside main() then that remains until main is
executing.
Cont…
When we create automatic variable then the compiler does not initialize this. Thus
it will take an arbitrary value which maybe 0 or something else.
But if we want to initialize we have to assign value for the variable.
External
External variables re also called global variables
Defined outside of any function (i.e the variable defined in between the header of
the program and main).
To declare external variable the keyword extern is used but we can skip.
extern datatype variable_name;
Cont…
External variable exists for the life of a program.
Takes memory space when the program begins and remain until the program ends.
If external variables are not initialized by the programmer then its initialized to 0
automatically when they are created.
Static
A static variable has a scope of that of local variables but life time of external
variables.
Initialized only once at the beginning, they are not reinitialized each time the
function is called. static datatype variable name;
Cont…
The following program demonstrates the difference between static and local variable.
void F1();
void F2();
void main()
{
F1();
F1();
F1();
F2();
F2();
F2();
}
void F1()
{
int n=1;
n++;
cout<<―n=―<<n<<endl
}
void F2()
{
static int m=1;
m++;
cout<<―m=―<<m<<endl;
}
Output
n=2
n=2
n=2
m=2
m=3
m=4
Cont…
The value of n is 2 in every call. Because n is automatic variable, this creates
when we call the function and destroy when we come back from the function.
In every execution the value of n is destroyed and n is created in the next calling.
But the value of m is initialized once at the first execution only.
Reading assignment
Register storage class
Chapter Two
Array and String
An array is a collection of variables of the same type that are referred to by a
common name.
 Arrays offer a convenient means of grouping together several related variables, in
one dimension or more dimensions:
• product part numbers:
int part_numbers[] = {123, 326, 178, 1209};
• student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
• 3D coordinates:
vector coordinates[4][3] = {{0, 0, 0}, {1, 0, 1}, {1, 0, 5} {4, 7, 9}};
How To Declare Arrays
To declare an array in C++, you should specify the following things
The data type of the values which will be stored in the array
The name of the array (i.e. a C++ identifier that will be used to access and update the array
values)
The dimensionality of the array:
• One dimensional (i.e. list of values ),
• Two-dimension array (a matrix or a table), etc.
The size of each dimension
• Examples int x[10]; // An integer array named x with size 10
• float GPA[30]; // An array to store the GPA for 30 students
• int studentScores[30][5]; // A two-dimensional array to store the scores of 5 exams
for 30 students
One-dimensional Arrays
We use one-dimensional (ID) arrays to store and access list of data values in an easy way
by giving these values a common name, e.g.
int x[4]; // all values are named x
x[0] = 10; // the 1st value is 10
x[1] = 5; // the 2nd value is 5
x[2] = 20; // the 3rd value is 20
x[3] = 30; // the 4th value is 30
All C++ one-dimensional arrays with N entries start at index 0 and ended at index
N-1 i.e arrays in C++ are zero bounded.
const int N=5;
int v[N]; // this array contains 5 entries
It is a common error to try to access the Nth entry, e.g. v[5] or V[N], since the
index of the last array entry is N-1, not N
Initializing One-dimensional Arrays
There are two common ways to initialize one-dimensional arrays
• Using for loop, e.g.
int x[10];
for( int index=0; index<10; index++) x [index] = index+1 ;
• Specifying list of values while declaring the 1D array, e.g.
int x[10] = {1,2,3,4,5,6,7,8,9,10};
int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values
double z[100] = {0}; // this array contains 100
// entries, all of which are initialized by 0
double w[20] = {5,3,1}; // this array contains 20 entries,
// the first three entries are initialized by 5, 3, and1 respectively
// while the remaining 17 entries are automatically initialized by 0
Storing and displaying Values in 1D Arrays
int x[10];
// Reading one value at a time from the user:
for (int index=0; index<10; index++)
cout<<“nEnter the” <<index+1<<“valuen”;
cin >> x[index];
int x[10];
// Displaying one value per line to the user:
for (int index=0; index<10; index++)
cout << x[index] << endl;
void main()
{
int x[5], index;
cout << ―Please enter five integer values: ―;
for( index=0; index<5; index++)
cin >> x[index];
cout << ―The values in reverse order are: ―;
for (index=4; index>=0; index--)
cout << setw(3) << x[index];
cout << endl;
}
Representation of Arrays in Memory
In C++, any array is mapped to a contiguous memory location.
All memory elements reside next to each other.
The lowest address corresponds to the first element, and the highest address to the
last element.
• Example:
int a[8];
int j;
for(j=0; j<8; j++) a[j] = 7-j;
Example about Sum of arrays
#include <iostream>
using namespace std;
int main()
{
const int arraySize= 10; // constant variable indicating size of
array
int a[ arraySize ]= { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
// sum contents of array a
for ( int i= 0;i <arraySize;++i )
total += a[ i];
cout << "Total of array elements:" << total << endl;
return 0;
} // end main
Exercise
Write the output of the following programs(1-2).
1. int main()
{
int arr[5]={1,3,5,7,9}; //initialize arr array
int i;
for(i=0;i<5;i++) //output arr array
cout<<arr[i]*arr[i+1]<<"t";
return 0;
}
2. int main(){
int arr[5]={1,3,5,7,9}; //initialize arr array
int i;
for(i=4;i>=0;i--) //output arr array
cout<<arr[i]<<"t";
return 0;
}
3. Write a program which accepts five
scores of ten students result and display
sum and average of each students score.
4. Write a C++ program which accepts ten
integers and prints the maximum and
minimum from the lists it also locate the
position where the maximum and
minimum element is found .
Some Restrictions on Array
Consider the following statements:
int myList[5] = {0, 4, 8, 12, 16}; //Line 1
int yourList[5]; //Line 2
The statement in Line 1 declares and initializes the array myList, and the
statement in Line 2 declares the array yourList.
These arrays are of the same type and have the same number of components.
Suppose that you want to copy the elements of myList into the corresponding
elements of yourList. The following statement is illegal:
yourList = myList; //illegal
Cont…
To copy one array into another array, you must copy it component-wise—that is,
one component at a time.
This can be done using a loop, such as the following:
for (int index = 0; index < 5; index ++)
yourList[index] = myList[index];
To read data into yourList, you must read one component at a time, using a loop
such as the following:
for (int index = 0; index < 5; index ++)
cin >> yourList[index];
Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array without any
brackets.
In C++, arrays are passed by reference only.
Because arrays are passed by reference only, you do not use the symbol & when
declaring an array as a formal parameter.
For example, if array hourlyTemperatures has been declared as
int hourlyTemperatures[ 24 ];
the function call modifyArray( hourlyTemperatures, 24 );
Cont…
When declaring a one-dimensional array as a formal parameter, the size of the array is
usually omitted.
If you specify the size of a one-dimensional array when it is declared as a formal parameter,
the size is ignored by the compiler.
void initialize(int list[], int listSize)
{
int count;
for (count = 0; count < listSize; count++)
list[count] = 0;
}
The first parameter of the function initialize is an int array of any size.
When the function initialize is called, the size of the actual array is passed as the second
parameter of the function initialize.
Exercise
1. Write a program which store an array of five numbers using getNumbers function
and prints these numbers using printNumbers function. The numbers should be
provided from the user.
1. Write a program which calculates the average of ten numbers, where the numbers
are initialized during array declaration and passed to a function called getAverage.
Multidimensional array
Multidimensional arrays can be described as "arrays of arrays".
For example, a bidimensional array can be imagined as a two-dimensional table
made of elements, all of them of a same uniform data type.
The general form of an N -dimensional array declaration is:
type array_name [size_1] [size_2] … [size_N];
For example, the following declaration creates a 4 x 10 x 20 character array, or a
matrix of strings:
char string_matrix[4][10][20];
Two-Dimensional Arrays
A two-dimensional array is a list of one-dimensional arrays.
Arrays that require two subscripts to identify a particular element are called two-
dimensional arrays or 2-D arrays
To declare a two-dimensional integer array matrix of size 10,20 we would write:
int matrix[3][4];
The array contains three rows and four columns, so it‘s said to be a 3-by-4 array.
In general, an array with m rows and n columns is called an m-by-n array.
Cont…
This corresponds to a table with 3 rows and 4 columns (for example).
The following program generates the above
array.
int main()
{
int row=3, col=4;
int matrix[row][col];
for(row=0; row < 3; ++row) {
for(col=0; col < 4; ++col) {
matrix[row][col] = (row*4)+ col +1;
cout << matrix[row][col] << ‘ ‘;
}
cout << ‘n’;
}
return(0);}
Memory Allocation for Two-Dimensional Arrays
Storage for all array elements is determined at compile time.
The memory used to hold an array is required the entire time that the array is in
existence.
The following formula determines the number of bytes of memory that will be
allocated:
bytes = rows * columns * number_of_bytes_in_type
For example, an integer array (with two-byte integers) with dimensions 100,100
would require 100 * 100 * 2 = 20,000 bytes.
Exercise
1. Write a C++ program that adds equivalent elements of the two-dimensional
arrays named first and second. Both arrays should have two rows and three
columns. For example, element [1][2] of the resulting array should be the sum of
first[1][2] and second[1][2].
2. Write a C++ program that adds the values of 4 by 4 matrix, you can initialize all
values during declaration.
3. Modify the program written for Exercise 2 to display the total of each row of
matrix separately.
4. Write a program which displays multiplication table of 12 by 12 matrix.
Cont…
5. Write a C++ program that finds and displays the maximum value in a two-dimensional array of integers. The
array should be declared as a 4-by-5 array of integers and initialized with the data 16, 22, 99, 4, 18, -258, 4,
101, 5, 98, 105, 6, 15, 2, 45, 33, 88, 72, 16, and 3.
6. Modify the program written in Exercise 5 so that it also displays the maximum value‘s row and column
subscript numbers.
7. Write a C++ program that displays the contents of two dimensional array by passing the array elements as
arguments of the function.
8. Write a program that includes two functions named calcavg() and variance(). The calcavg() function should
calculate and return the average of values stored in an array named testvals. The array should be declared in
main() and include the values 89, 95, 72,83, 99, 54, 86, 75, 92, 73, 79, 75, 82, and 73. The variance() function
should calculate and return the variance of the data. The variance is obtained by subtracting the average from
each value in testvals, squaring the values obtained, adding them, and dividing by the number of elements in
testvals.
String
• One of the most useful data types supplied in the C++ libraries is the string.
• A string is a variable that stores a sequence of letters or other characters, such as
"Hello" or "May 10th is my birthday!".
• Just like the other data types, to create a string we first declare it, then we can store
a value in it.
string testString;
testString = "This is a string.";
• Often, we use strings as output, and cout works exactly like one would expect:
• cout << testString << endl; will print the same result as
• cout << "This is a string." << endl;
Cont…
In order to use the string data type, the C++ string header <string> must be
included at the top of the program.
String manipulation using arrays
 The most common use for one-dimensional arrays is to store strings of
characters
In C++, a string is defined as a character array terminated by a null symbol (‘0’).
 To declare an array Str that could hold a 10-character string, one would write:
char str[11];
Cont…
Specifying the size as 11 makes room for the null at the end of the string.
Some examples of string constants
in C++ are:
"hello there"
"I like C++."
"#$%§@@+*"
"""
""""
""
""
 The null string, “ “, only contains the null terminator and represents
the empty string.
Reading a String from the Keyboard
How to read a string entered from the keyboard?
Make an array, that will receive the string, the target of a cin stream.
The following program reads (part of) a string entered by the user:
int main()
{
char str[80];
cout << ―Enter a string: ―;
cin >> str; // read string from keyboard
cout << ―Here is your string: ―;
cout << str;
return(0);}
Cont…
Problem: Entering the string ― This is a test‖, the above program only returns
―This ‖, not the entire sentence.
Reason: The C++ input/output system stops reading a string when the first
whitespace character is encountered.
Solution: Use another C++ library function, gets().
To use gets() libraray function we have to include <cstdio> as header.
The function takes one argument i.e name of the string.
Cont…
#include <iostream.h>
#include <cstdio.h>
int main()
{
char str[80]; // long enough for user input?
cout << ―Enter a string: ―;
gets(str); // read a string from the keyboard
cout << ―Here is your string: ―;
cout << str << endl;
return(0);
}
Some C++ Library Functions for Strings
C++ supports a range of string-manipulation functions.
The most common are:
strcpy() : copy characters from one string to another
strcat() : concatenation of strings
strlen(): length of a string
strcmp(): comparison of strings
Cont…
• strcpy(to_string,from_string) — String Copy:
#include <iostream.h>
#include <cstring.h>
int main()
{
char a[10];
strcpy(a, ―hello‖);
cout << a;
return(0);
}
Cont…
strlen(string) — String Length
strlen(str) returns the length of the string pointed to bystr, i.e.,the number of
characters excluding the null terminator.
int main()
{
char str[80];
cout << ―Enter a string: ―;
gets(str);
cout << ―Length is: ― << strlen(str);
return(0);
}
Cont…
strcat(string_1,string_2) — Concatenation of Strings
The strcat() function appends s2 to the end of s1 . String s2 is unchanged.
int main()
{
char s1[21], s2[11];
strcpy(s1, ―hello‖);
strcpy(s2, ― there‖);
strcat(s1, s2);
cout << s1 << endl;
cout << s2 << endl;
return(0);
}
Cont…
strcmp(string_1,string_2) — Comparison of Strings
The strcmp(str_1, str_2) function compares two strings and returns the following
result:
• str_1 == str_2 : 0
• str_1 > str_2 : positive number
• str_1 < str_2 : negative number
The strings are compared lexicographically (i.e., according to dictionary order):
• a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd < ...
Chapter Three
Structure
 C/C++ arrays allow you to define variables that combine several data items of the
same kind, but structure is another user defined data type which allows you to
combine data items of different kinds.
Structure is a collection of data items. The data item can be different type, some
can be int type, some can be float, some can be char and so on.
The data item of structure is called member of the structure.
In other words, heterogeneous data types can be grouped to form a structure.
Cont…
The difference between array and structure is the element of the array has same
type, while the element of structure can be different.
The other difference is that each element of the array referred by its position while
each element of a structure has a unique name.
Declaration of structure
struct [structure tag]
{
Data type 1 member 1;
Data type 2 member 2;
Data type n member n;
} ;
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
Creating Structure variable
Structure variable can be creating in the following 3 ways.
struct [structure tag]
{
Data type 1 member 1;
Data type 2 member 2;
Data type n member n;
} a, b …;
struct [structure tag]
{
Data type 1 member 1;
Data type 2 member 2;
Data type n member n;
} ;
struct structure tag a,b..;
struct [structure tag]
{
Data type 1 member 1;
Data type 2 member 2;
Data type n member n;
} ;
structure tag a,b..;
S2
Cont…
struct student
{
char Name[30];
int RollNo;
char Sex[5];
int age;
} S1,S2;
Name
RollNo
Sex
age
Name
RollNo
Sex
age
S1
 Unless a structure variable is created memory space is not reserved for
members of the structure.
Accessing Member of Structure
To access any member of a structure, we use the member access operator (.).
The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access.
Syntax : stracture variableName.member
struct student
{
char Name[30];
int RollNo;
char Sex[7];
int age;
} S1,S2;
strcpy(S1.Name,‖Helen‖);
S1.RollNo=1234;
strcpy(S1.Sex,‖Female‖);
S1.age=23;
Helen
1234
Female
23
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} Book1; // Declare Book1 of type Book
Books Book2; // Declare Book2 of type Book
int main() {
// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;
// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;
// Print Book1 info
cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;
// Print Book2 info
cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;
return 0;
}
Cont…
When the above code is compiled and executed, it produces the following result −
Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700
Initialization of structure
Like normal variable structures can be initialized at the time of declaration.
Initialization of structure is almost similar to initializing array.
struct Employee {
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
Employee E = {2,"Suresh",35,35000};
cout << "nnEmployee Id : " << E.Id;
cout << "nEmployee Name : " << E.Name;
cout << "nEmployee Age : " << E.Age;
cout << "nEmployee Salary : " << E.Salary;
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Array of Structure
Structure is collection of different data type.
An object of structure represents a single record in memory, if we want more than
one record of structure type, we have to create an array of structure or object.
 As we know, an array is a collection of similar type, therefore an array can be of
structure type. struct structure-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
structure-name obj [ size ];
Syntax for declaring structure array
Cont…
struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void main()
{
int i;
Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
cout << "nEnter details of " << i+1 << " Employee";
cin >> Emp[i].Id>> Emp[i].Name>> Emp[i].Age >> Emp[i].Salary;
}
Array within Structure
Like normal data type, structure can also store an array as well.
Syntax for array within structure
struct structure-name
{
datatype var1; // normal variable
datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
structure-name obj;
Eg. struct Student
{
int Roll;
char Name[25];
int Marks[3]; //Statement 1 : array of marks
int Total;
float Avg;
};
Cont…
void main()
{
int i;
Student S;
cout << "nnEnter Student Roll : ";
cin >> S.Roll;
cout << "nnEnter Student Name : ";
cin >> S.Name;
S.Total = 0;
for(i=0;i<3;i++)
{
cout << "nnEnter Marks " << i+1 << " : ";
cin >> S.Marks[i];
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
}
Structure within structure
When a structure contains another structure, it is called nested structure.
For example, we have two structures named Address and Employee.
 To make Address nested to Employee, we have to define Address structure before
and outside Employee structure and create an object of Address structure inside
Employee structure.
struct structure1
{
- - - - - - -
- - - - - - - -
};
struct structure2
{ - - - - - - - - - - - -
- - - - - - - -
structure1 obj;
};
Syntax for structure within structure or nested
structure
Cont…
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};
struct Employee
{
int Id;
char Name[25];
float Salary;
Address Add;
};
void main()
{
int i;
Employee E;
cout << "ntEnter Employee Id : ";
cin >> E.Id;
cout << "ntEnter Employee Name : ";
cin >> E.Name;
cout << "ntEnter Employee Salary : ";
cin >> E.Salary;
cout << "ntEnter Employee House No : ";
cin >> E.Add.HouseNo;
cout << "ntEnter Employee City : ";
cin >> E.Add.City;
cout << "ntEnter Employee House No : ";
cin >> E.Add.PinCode;
}
Structures as Function Arguments
Using function we can pass structure as function argument and we can also return
structure from function.
Structure can be passed to function through its object therefore passing structure to
function or passing structure object to function is same thing because structure object
represents the structure.
Like normal variable, structure variable(structure object) can be pass by value or by
references.
Passing Structure by Value
The structure object is passed as function argument to the definition of function,
here object is representing the members of structure with their values.
Eg. struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void Display(struct Employee);
void main()
{
Employee Emp = {1,"Kumar",29,45000};
Display(Emp);
}
void Display(struct Employee E)
{
cout << "nnEmployee Id : " << E.Id);
cout << "nEmployee Name : " << E.Name);
cout << "nEmployee Age : " << E.Age);
cout << "nEmployee Salary : " << E.Salary);
}
Output :
Employee Id : 1
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
Passing Structure by Reference
In this approach, the reference/address structure object is passed as function
argument to the definition of function.
Eg . struct Employee
{
int Id;
char Name[25];
int Age;
long Salary;
};
void Display(struct Employee &E);
void main()
{
Employee Emp = {1,"Kumar",29,45000};
Display(Emp);
cout<< " n" <<Emp.Id
}
void Display(struct Employee &E)
{
E.Id=5;
cout << "nnEmployee Id : " << E.Id;
cout << "nEmployee Name : " << E.Name;
cout << "nEmployee Age : " << E.Age;
cout << "nEmployee Salary : " << E.Salary;
}
Output :
Employee Id : 5
Employee Name : Kumar
Employee Age : 29
Employee Salary : 45000
5
Exercise
1. Write a complete C++ program which shows the details of students. Note that your
program include college details, department details and student personal
information and all those details should be a record themselves.
Your program should consists of the following concepts:-
 Nested structure (structure within structure)
Array of structure i.e the record should be more than a single record
In the student personal information structure you have to apply array within
structure.
Chapter Four
Pointers
Introduction
In C++, every value is stored somewhere in memory and can therefore be
identified with that address. Such addresses are called pointers.
 A pointer is a variable which stores the address of another variable.
The only difference between pointer variable and regular variable is the data they
hold.
A pointer is simply the address of an object in memory. Generally, objects can be
accessed in two ways: directly by their symbolic name, or indirectly through a
pointer.
Declaring Pointers
Like all variables, pointers must be declared before they can be used to store an address.
When you declare a pointer variable, C++ requires also specifying the type of variable that‘s
pointed to.
Is reserving a memory location for a pointer variable.
Syntax: type * pointer_name ;
For example, if you wanted to declare a variable px to be a pointer to a double
value, you could do so as follows:
double *px;
Similarly, to declare a variable pptr as a pointer to a Point structure, you would
write:
Point *pptr;
Pointer Operators
C++ includes two built-in operators for working with pointers:
The address-of operator (&) is written before a variable name (or any expression
to which you could assign a value) and returns the address of that variable. Thus,
the expression &total gives the address of total in memory.
The dereference operator (*) is written before a pointer expression and returns the
actual value to which the pointer points.
 Suppose, for example, that you have declared and initialized the following
variables:
double x = 2.5;
double *px = &x;
 At this point, the variable px points to the variable x, and the expression *px is
synonymous with the variable x.
Getting Address of a variable
int main()
{
int num;
num = 22;
cout << "The value stored in num is " << num << endl;
cout << "The address of num = " << &num << endl;
return 0;
}
Output
The value stored in num is 22
The address of num = 0012FED4
 Address information changes, depending on what computer is running the
program and how many other programs are currently loaded into memory.
Cont…
Besides displaying the address of a variable, you can store addresses in suitably
declared variables.
For example var=25; x=var; ptr = &var;
 We have assigned to x the content of variable var as we
have done in many other occasions in previous
sections, but to ptr we have assigned the address in
memory where the operating system stores the value of
var , that we have imagined that it was 1776 (it can be
any address).
Cont…
 The content of or dereference operators allows us to get the value at the
address held by the pointer.
 The * operator, when used with pointers, either declares a pointer or
dereferences the pointer‘s value.
 The dereference operator can be literally translated to "value pointed by”.
 The act of getting to an object via a pointer to it, is called dereferencing the
pointer.
 Pointer variables are defined to point to objects of a specific type so that when
the pointer is dereferenced, a typed object is obtained.
Assigning values to pointers
Assigning values to pointers is similar to that of assigning values to normal variable,
except that the variable is pointer variable.
Suppose ptr is a pointer variable then to assign an integer value ,5
int *ptr; === int *ptr=5;
ptr=5;
OR
int x=5;
int *ptr;====int *ptr=&x;
ptr=&x;
cout<<x;//prints the value of x
Or by using pointers you can do it as follows
cout<<*ptr;//dereferences ptr;
cout<<ptr;// print an address (the address of x).
Cont…
int main()
{
int *numAddr; // declare a pointer to an int
int miles, dist; // declare two integer variables
dist = 158; // store the number 158 in dist
miles = 22; // store the number 22 in miles
numAddr = &miles; // store the address of miles in numAddr
cout << "The address stored in numAddr is " << numAddr << endl;
cout << "The value pointed to by numAddr is " << *numAddr << "nn";
numAddr = &dist; // now store the address of dist in numAddr
cout << "The address now stored in numAddr is " << numAddr << endl;
cout << "The value now pointed to by numAddr is " << *numAddr << endl;
return 0;
}
Output
The address stored in numAddr is 0012FEC8
The value pointed to by numAddr is 22
The address now stored in numAddr is 0012FEBC
The value now pointed to by numAddr is 158
Cont…
void main(void)
{
int x = 25, y = 50, z = 75;
int *ptr;
cout << "Here are the values of x, y, and z:n";
cout << x << " " << y << " " << z << endl;
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *= 2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
cout << "Once again, here are the values of x, y, and z:n";
cout << x << " " << y << " " << z << endl;
}
References and Pointers
What is the difference between a pointer and a reference?
A reference is a named constant for an address; therefore, the address named as a
reference can‘t be altered.
Because a pointer is a variable, the address in a pointer can be changed.
For most applications, using references rather than pointers as arguments to
functions is easier and preferred. Why??
The reason is the simpler notation for locating a reference
parameter, which eliminates the address operator (&) and indirection operator (*)
required for pointers.
Cont…
Syntax for reference variable :- dataType& newName = existingName;
For example, the reference declaration
double& sum = total; equates the name sum to the name total. Both now refer to the
same variable.
A reference variable is an alias, that is, another name for an already existing
variable. Once a reference is initialized with a variable, either the variable name or
the reference name may be used to refer to the variable.
Cont…
int main()
{
double total = 20.5; // declare and initialize total
double& sum = total; // declare another name for total
cout << "sum = " << sum << endl;
sum = 18.6; // this changes the value in total
cout << "total = " << total << endl;
return 0;
}
Because the variable sum is simply another reference to the variable total, the first cout
statement in the program displays the value stored in total. Changing the value in sum then
changes the value in total, which the second cout statement in the program displays.
output
sum = 20.5
total = 18.6
Cont…
When constructing references, keep two points in mind.
 First, the reference should be of the same data type as the variable it refers to.
int num = 5;
double& numref = num; // INVALID - CAUSES A COMPILER ERROR
Second ,a compiler error is produced when an attempt is made to equate a
reference to a constant.
int& val = 5; // INVALID - CAUSES A COMPILER ERROR
Pointer Arithmetic
As we know pointer stores the address of another variable, memory location we
can perform the following operations.
Pointer increment ,p++ or ++p
Pointer decrement, p- - or --p
Constant addition, p+k
Constant subtraction , p-k
Pointer Increment
If p is a pointer then ++p,p++ is possible with pointer.
Pointer increment, p++ or ++p does not mean adding 1 to the pointer but adding the size
of that data type to the pointer p.
eg int x,*p,*q;
short int y;
p=&x;
q =&y;
++q;
p++;
Here if both p and q has an address of 1000 after the statement p=&x then p++ will be
1004 which is incrementing the size of (x) and ++q will be 1002 ;
Pointer Decrement
If p is a pointer then --p,p-- is possible with pointer.
Pointer increment, p-- or --p does not mean subtracting 1 from the pointer but
subtracting the size of that data type from the pointer p.
eg int x,*p,*q;
short int y;
p=&x;
q =&y;
--q;
p--;
Here if both p and q has an address of 1004 after the statement p=&x then p--
will be 1000 which is incrementing the size of (x) and --q will be 1002;
Constant addition /subtraction
 An integer can be added to or subtracted from a pointer variable. This may be performed
with the +, - +=, or -= operators.
Eg
int main()
{
int *p,x;
x=25;
p=&x;
*p=*p+10;// same as x=x+10 or p=p+10;
cout<<―Now x is‖<<x; // 35
cout<<―The value of x through p:‖<<*p; //35
cout<<―The address of x is‖<<&x; //0x8f51fff4
cout<<―The address of x through p is‖<<x; // 0x8f51fff4
}
Pointer to void
We cannot assign the address of different type to pointer.
If the type of the variable and pointer is different then we can use void as pointer
variable.
float y;
int *x;
x=&y; // illegal
float *a;
int b;
a=&b; //illegal
float y;
void *x;
x=&y;
void *a;
int b;
a=&b;
Relationship between pointers and arrays
Pointers and arrays are strongly related.
In fact, pointers and arrays are interchangeable in many cases.
For example, a pointer that points to the beginning of an array can access that
array by using either pointer arithmetic or array-style indexing.
Consider the following program:
Relationship between pointers and arrays
int main ()
{
int var[3] = {10, 100, 200};
int *ptr;
ptr = var; // same as ptr=&var[0];
for (int i = 0; i < 3; i++)
{
cout << "Address of var[" << i << "] = ";
cout << ptr << endl;
cout << "Value of var[" << i << "] = ";
cout << *ptr << endl;
// point to the next location
ptr++;
}
return 0;
}
Output
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200
• Note that the address may be different
on different machine.
Array of Pointers
There may be a situation, when we want to maintain an array, which can store
pointers to an int or char or any other data type available.
Array of pointer is declared as:- Datatype * array_Name[Size];
 Following is the declaration of an array of 10 integers, each element is a pointer
type :
int *ptr[10];
This declares ptr as an array of MAX integer pointers.
Thus, each element in ptr, now holds a pointer to an int value.
Consider the following program, to illustrate this concept.
Cont…
int main ()
{
int var[3] = {10, 100, 200};
int *ptr[3];
for (int i = 0; i < 3; i++)
{
ptr[i] = &var[i]; // assign the address of integer.
}
for (int i = 0; i < 3; i++)
{
cout << "Value of var[" << i << "] = ";
cout << *ptr[i] << endl;
}
return 0;
}
output
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
Cont…
You can also use an array of pointers to character to store a list of strings as
follows:
const int MAX = 4;
int main()
{
char *names[MAX] = {"Zara Ali","Hina Ali","Nuha Ali","Sara Ali"};
for (int i = 0; i < MAX; i++)
{
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl;
}
return 0;
}
Pointer to a Pointer
A pointer to a pointer is a form of multiple indirection or a chain of pointers.
Normally, a pointer contains the address of a variable.
When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as
shown below.
Cont…
A variable that is a pointer to a pointer must be declared as such. This is done by placing an
additional asterisk in front of its name.
 For example, following is the declaration to declare a pointer to a pointer of type int:
int **var;
When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
that the asterisk operator be applied twice. Eg.
int main ()
{
int var;
int *ptr;
int **pptr;
var = 3000;
// take the address of var
ptr = &var;
Cont…
// take the address of ptr using address of operator &
pptr = &ptr;
// take the value using pptr
cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Value of var :3000
Value available at *ptr :3000
Value available at **pptr :3000
Pointer as an Argument to a function
If a pointer is passed as an argument to a function that is known as pass by address or pass by
pointer.
The concept is similar to pass by reference but the only difference is that in this case we pass the
address of the variable.
void swap(int *,int *);
void main()
{
int x,y;
x=10;
y=20;
swap(&x,&y);
cout<<―X=‖<<x<<―t‖<<―Y‖<<y;
}
void swap(int *x,int *y)
{
int t;
t=*a;
*a=*b;
*b=t;
}
Memory management through pointer
As each variable is defined in a program, sufficient storage for it is assigned from a pool
of computer memory locations made available to the compiler.
After memory locations have been reserved for a variable, these locations are fixed for the
life of that variable, whether or not they are used.
For example, int a[100]; reserve 100 space for array a ,but suppose we want to create
array at run time then we can do using pointer.
When the space is created for a variable at compile time that approach is known as static
if the space created at execution /run time its called dynamic.
Using dynamic allocation, the amount of storage to be allocated is determined or adjusted
at run time
• Useful for lists because allows expanding or contracting the memory used
Cont…
In C++ the new operator is used create space dynamically i.e at run time and the delete
operator the is used to release the memory taken by a variable and return memory to the
operating system.
Dynamic storage requests for scalar variables or arrays are made as part of a declaration
or an assignment statement
• Example:
int *num = new int; // scalar
• Example:
int *grades = new int[200];// array
• Reserves memory area for 200 integers
• Address of first integer in array is value of pointer variable grades
Chapter Five
File Operations (File Input/output)
The data created by the user and assigned to variables with an assignment statement is
sufficient for some applications.
With large volume of data most real-world applications use a better way of storing
that data. For this, disk files offer the solution.
Storage of data in memory is temporary. Files are used for data persistence permanent
retention of data.
A File is a collection of information, usually stored on a computer‘s disk.
 Information can be saved to files and then later reused.
Cont...
For example, the C++ programs you store on disk are examples of files.
The stored data in a program file is the code that becomes input data to the C++
compiler.
 In the context of data processing, however, a C++ program isn‘t usually considered
as data, and the term ―file‖ or ―data file‖ typically refers only to external files
containing the data used in a C++ program.
A file is physically stored on an external medium, such as a disk. Each file has a
unique filename, referred to as the file‘s external name.
The external name is how the operating system (OS) knows the file.
Stream classes
Stream is a general name given to flow of data. In C++, there are different types of
streams. Each stream is associated with a particular class, which contains member
function and definition for dealing with file.
 C++ provides the following classes to perform output and input of characters
to/from files:
• ofstream: represents the output file stream and is used to create files and to write
information to files.
• ifstream: represents the input file stream and is used to read information from
files.
Cont...
• fstream: represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files,
and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be
included in your C++ source file.
Cont...
A file stream is a one-way transmission path used to connect a file stored on a physical
device, such as a disk or CD, to a program.
Each file stream has its own mode that determines the direction of data on the transmission
path—that is, whether the path moves data from a file to a program or from a program to a
file.
A file stream that receives or reads data from a file to a program is an input file stream.
A file stream that sends or writes data to a file is an output file stream.
The direction, or mode, is defined in relation to the program, not the file; data going into a
program is considered input data, and data sent out from a program is considered output data.
Cont...
.
 For each file your program uses, regardless of the file‘s type (text or binary), a
distinct file stream object must be created.
 If you want your program to read from and write to a file, both input and output
file stream objects are required. Input file stream objects are declared to be of
type ifstream, and output file stream objects are declared to be of type ofstream.
Cont…
For example, the following declaration statement declares an input file stream
object named inFile to be an object of the ifstream class:
ifstream inFile;
Similarly, the following declaration statement declares an output file stream object
named outFile to be an object of the ofstream class:
ofstream outFile;
In a C++ program, a file stream is accessed by its stream object name: one name
for reading the file and one name for writing to the file.
Object names, such as inFile and outFile,can be any programmer-selected name
that conforms to C++‘s identifier rules.
File Stream Functions
Each file stream object has access to the functions defined for its ifstream or
ofstream class.
 These functions include
o connecting a stream object name to an external filename (called opening a file),
o determining whether a successful connection has been made,
o closing a connection (called closing a file),
ogetting the next data item into the program from an input stream,
o putting a new data item from the program onto an output stream, and
o detecting when the end of a file has been reached.
Cont…
Opening a file connects a file stream object to a specific external filename by using an
open() function, which accomplishes two purposes.
• First, opening a file establishes the physical connecting link between a program and a file.
• Besides establishing the actual physical connection between a program and a data file,
opening a file connects the file‘s external name to the stream object name that the
program uses internally.
In using the open() function to connect the file‘s external name to its internal object
stream name, only one argument is required: the external filename.
For example, the following statement connects the external file named prices.dat to the
internal file stream object named inFile:
inFile.open("prices.dat");
Cont…
When opening a file for input or output, good programming practice requires
checking that the connection has been established before attempting to use the file.
You can do this with the fail() function, which returns a true value if the file was
opened unsuccessfully (that is, it's true the open failed) or a false value if the open
succeeded.
Typically, the fail() function is used in code similar to the following, which attempts
to open a file named prices.dat for input, checks that a valid connection was made,
and reports an error message if the file wasn‘t opened for input successfully:
Cont…
ifstream inFile; // any object name can be used here
inFile.open("prices.dat"); // open the file
// Check that the connection was successfully opened
if (inFile.fail())
{
cout << "nThe file was not successfully opened"
<< "n Please check that the file currently exists."
<< endl;
exit(1);
}
• If the fail() function returns a true, indicating the open failed, this code displays an
error message. In addition, the exit() function, which is a request to the OS to end
program execution immediately, is called.
Operation with File
• Opening a File
To open a file we can use two methods:- using a Constructor or
using the open function
A file can be created by constructor as follows:
ofstream fout(―Hello‖);
The above statement creates an object fout (we can give another name also) of
stream class and this object a file Hello.
The operating system takes the name of the file Hello.
In the file Hello we can only write the data because this is created by ofstream
class.
Cont…
A file can be created by using ifstream class through constructor.
ifstream infile(―Test‖);
The above statement creates an object infile of ifstream class and attached a file Test with
this.
In the file Test we can perform only input operation (i.e read data from it) because this is
created by ifstream class.
 These file can be also opened as:-
ofstream fout; ofstream fout(―Hello‖);
fout.open(―Hello‖);
ifstream infile(―Hello‖); ifstream infile(―Test‖);
infile.open(―Hello‖);
Cont…
If you open a file for writing (out access mode), C++ creates the file. If a file by that
name already exists, C++ overwrite the old file with no warning. You must be
careful when opening files not to overwrite existing data that you want.
If an error occurs during opening of a file, C++ does not create a valid file pointer
(file object). Instead, C++ creates a file pointer (object) equal to zero.
For example if you open a file for output, but use an invalid disk name, C++ can‘t
open the file and therefore makes the file object equal to zero.
You can also determine the file access mode when creating a file in C++. If you
want to use the open function to open a file then the syntax is:
fileobject.open(filename,accessmode);
Closing File
A file is closed by using close() function as follows.
infile.close();
outfile.close();
 The general syntax is :-file_object_name.close();
Writing to File
By using insertion and extraction operator string data can be write and read.
void main(){
ofstream outfile(―result‖);
outfile<<―Abebe‖;
outfile<<―Marks‖;
outfile<<―450‖;
outfile.close();
}
Writing characters to Files
A character can be written onto a file using the put() function. See the following
code:
int main()
{
char c;
ofstream outfile;
outfile.open(―c:test.txt‖,ios::out);
if(outfile.fail())
{
cerr<< ―nError opening test.txt‖;
exit(1);
}
for(int i=1;i<=15;i++)
{
cout<< ―nEnter a character : ‖;
cin>>c;
outfile.put(c);
}
outfile.close();
}//end main
Cont…
 The above program stores Abebe, Marks and 450 onto file result.
Reading From a file
Files you open for read access (using ios::in) must exist already, or C++ gives you an
error message.
You can‘t read a file that does not exist. Open() returns zero if the file does not exist when
you open it for read access.
If you attempt to read a file that you have completely read the data from, C++ returns the
value zero.
To find the end-of-file condition, be sure to check for zero when reading information from
files.
The following code asks the user for a file name and displays the content of the file to the
screen.
Example
.
#include <fstream >
#include <iostream>
#include<cstdlib>
using namespace std;
ofstream fp;
int main()
{
char name[20],filename[15];
ifstream indata;
cout<<"nEnter the file name : ";
cin.getline(filename,15);
indata.open(filename,ios::in);
if(indata.fail())
{
cerr<<"nError opening file : "<<filename;
exit(1);
}
while(!indata.eof())// checks for the end-of-file
{
indata>>name;
cout<<name<<endl;
}
indata.close();
}/
Reading Characters from file
You can read a character from file using get() function. The following program asks a file name
and displays each characters on the screen.
int main()
{
char c,filename[15];
ifstream indata;
cout<<"nEnter the file name : ";
cin.getline(filename,15);
indata.open(filename,ios::in);
if(indata.fail())
{
cerr<<"nError opening file : "<<filename;
exit(1);
}
while(!indata.eof())// checks for the end-of-file
{
indata.get(c);
cout<<c;
}
indata.close();
}//end of main
File Access Modes
• ios::in Open a text file in input mode
• ios::out Open a text file in output mode
• ios::app Open a text file in append mode
• ios::ate Go to the end of the opened file
• ios::binary Open a binary file in input mode (default is text file)
• ios::trunc Delete the file contents if exists
Error handling/ state flags
bad()
• Returns true if a reading or writing operation fails. For example in the case that 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(), but also in the case that a format error
happens, like when an alphabetical character is extracted when we are trying to
read an integer number.
eof()
• Returns true if a file open for reading has reached the end.
good()
• It is the most generic state flag: it returns false in the same cases in which calling
any of the previous functions would return true.
Types of Disk File Access
Your program can access files either in sequential manner or random manner.
The access mode of a file determines how one can read, write, change, add and
delete data from a file.
 A sequential file has to be accessed in the same order as the file was written. This
is analogues to cassette tapes: you play music in the same order as it was recorded.
 Unlike the sequential files, you can have random-access to files in any order you
want. Think of data in a random-access file as being similar to songs on compact
disc (CD): you can go directly to any song you want to play without having to
play or fast-forward through the other songs.
Random Access File Concepts
Random access enables you to read or write any data in your disk file without
having to read and write every piece of data that precedes it.
 Generally you read and write file records. A record to a file is analogues to a C++
structure.
A record is a collection of one or more data values (called fields) that you read and
write to disk.
Generally you store data in the structures and write structures to disk.
When you read a record from disk, you generally read that record into a structure
variable and process it with your program.
File Pointer and their Manipulators
Each file has two pointers one is called input pointer and second is output pointer.
The input pointer is called get pointer and the output pointer is called put pointer.
When input and output operation take places, the appropriate pointer is automatically
set according to mode. For example when we open a file in reading mode, file pointer is
automatically set to start of file.
When we open a file in append mode, the file pointer is automatically set to the end of
file.
 In C++ there are some manipulators by which we can control the movement of the
pointer.
Cont…
Cont…
. int main(){
fstream fileobj;
char ch; //holds A through Z
//open the file in both output and input mode
fileobj.open("c:alph.txt",ios::out|ios::in);
if(fileobj.fail())
{
cerr<<"nError opening alph.txt";
exit(1);
}
//now write the characters to the file
for(ch = 'A'; ch <= 'Z'; ch++)
{
fileobj<<ch;
}
fileobj.seekg(8L,ios::beg);//skips eight
letters, points to I
fileobj>>ch;
cout<<"nThe 8th character is : "<<ch;
fileobj.seekg(16L,ios::beg);//skips 16 letters,
points to Q
fileobj>>ch;
cout<<"nThe 16th letter is : "<<ch;
fileobj.close();
return 0;
}
Cont…
The seek() functions allow the programmer to move to any position in the file.
Each character in a data file is located by its position in the file.
The first character in the file is located at position 0, the next character at position
1, and so forth.
A character‘s position is referred to as its offset from the start of the file.
Therefore, the first character has a 0 offset, the second character has an offset of 1,
and so on, for each character in the file.
The seek() functions require two arguments: the offset, as a long integer, in the file
and where the offset is to be calculated from, determined by the mode.
Cont…
The three alternatives for the mode are ios::beg, ios::cur, and ios::end, which
denote the beginning of the file, current position, and end of the file.
Therefore, the mode ios::beg means the offset is the true offset from the start of
the file.
The mode ios::cur means the offset is relative to the current position in the file,
and the mode ios::end means the offset is relative to the end of the file.
A positive offset means move forward in the file, and a negative offset means
move backward.
Cont…
To point to the end of a data file, you can use the seekg() function to position the file
pointer at the last byte.
This statement positions the file pointer to the last byte in the file.
Fileobj.seekg(0L,ios::end);
This seekg() function literally reads ―move the file pointer 0 bytes from the end of
the file.‖
The file pointer now points to the end-of-file marker, but you can seekg() backwards
to find other data in the file.
The following program is supposed to read ―c:alph.txt‖ file backwards, printing each
character as it skips back in the file.
Example : Using seekg() and tellg()
Suppose test.dat contains this text
cont…
.
-18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
T h e g r a d e w a s 9 2 . 5 EOF
Opening Random-Access Files
There is really no difference between sequential files and random files in C++.
The difference between the files is not physical, but lies in the method that you use
to access them and update them.
The ostream member function write outputs a fixed number of bytes, beginning at
a specific location in memory, to the specified stream.
When the stream is associated with a file, function write writes the data at the
location in specified by the ―put‖ file position pointer.
The istream member function read inputs a fixed number of bytes from the
specified stream into an area in memory beginning at the specified address.
Cont…
When the stream is associated with a file, function read inputs bytes at the location in the
files specified by the ―get‖ file poison pointer.
Syntax of write: fileobject.write((char*) & name ofobject, sizeof(name of object));
Writing randomly to a random access file
Here is an example that shows how to write a record to a random access file.
#include<fstream.h>
#include<stdlib.h>
struct stud_info{
int id;
char name[20];
char fname[20];
float CGPA;
}student;
Cont…
. int main()
{
clrscr();
char filename[15];
ofstream outdata;
cout<<"nenter file name : ";
cin>>filename;
outdata.open(filename,ios::out);
if(outdata.fail())
{
cerr<<"nError opening "<<filename;
getch();
exit(1);
}
cout<<"nEnter student id : ";
cin>>student.id;
cout<<"nEnter student name : ";
cin>>student.name;
cout<<"nEnter student father name : ";
cin>>student.fname;
cout<<"nEnter student CGPA : ";
cin>>student.CGPA;
//now write to the file
outdata.seekp(((student.id)-1) *
sizeof(student));
outdata.write((char*) &student,
sizeof(student));
outdata.close();
cout<<"nData has been saved";
return 0;
}
Chapter Six
Introduction to Class
A class is way to bind the data and its associated functions together.
It allows data functions to be hidden, if necessary from external use.
A class specification has two parts.
• (i) Class declaration
• (ii) Class function definitions
So, Classes are user-defined (programmer-defined) types.
• Data (data members)
• Functions (member functions or methods)
In other words, they are structures + functions
Declaration of Class
A class definition begins with the keyword class.
The body of the class is contained within a set of braces, { } ; (notice the semi-
colon).
 Within the body, the keywords private: protected : and public: specify the access
level of the members of the class.
• the default is private.
 Usually, the data members of a class are declared in the private: section of the
class and the member functions are in public: section.
Cont…
• Member access specifiers
• public:
• can be accessed outside the class directly.
• The public stuff is the interface.
• private:
• Accessible only to member functions of class
• Private members and methods are for internal use only.
• The default access of a class is private, but it is still a good idea to
use the private key word to explicitly declare private members.
• Protected : Accessible only through inherited class
Cont…
This class example shows how we can encapsulate (gather) a circle information
into one package (unit or class).
No need for others classes to
access and retrieve its value
directly. The class methods are
responsible for
that only.
They are accessible from outside
the class, and they can access the
member (radius)
They are accessible from outside
the class, and they can access the
member (radius)
 The data member and member functions present in private and protected
mode can be accessed by the member function in public mode.
Cont…
The private and protected modes are exactly the same except that protected can be
inherited but private mode cannot be inherited.
Creating an object of a Class
Object is instance of a class i.e variable of a class.
Declaring a variable of a class type creates an object.
Class objects must be defined after the class is declared. Defining a class
object is called the instantiation of a class.
You can have many variables of the same type (class).
Cont…
Once an object of a certain class is instantiated, a new memory location is created
for it to store its data members and code.
The declaration of an object is as follows:-
class –Name object –Name;
We can declare more than one object of a class as follows:-
class –Name object –Name1, class –Name object –Name2,....;
When we declare an object space is allocated to that.
Objects can also be created at the time of class declaration.
Accessing class member
Through object, data member and member function present in public can be
accessed. The general format is :
• Object name . data member ;
• Object name . member function ;
 The dot operator is called the class member access operator.
Member function definition
Member function can be defined in two ways:
(i) Inside the class
(ii) Outside the class
Cont…
• Inside the class : When a member function is defined inside a class, it is
considered to be inline by default. If a member function is very small then it
should be defined inside the class.
class student
{
char name [ 20 ];
int rn ;
float marks ;
public :
void getdata ( )
{
cin >> name >> m >> marks ;
}
Cont…
void putdata ( )
{
cout << name << rn << marks :
}
}; //end of class
Outside the class : When a function has larger code then it should be defined outside the
class declaration. The prototype of such functions, however, must be provided in the class
definition.
The operator ‗: :‘ known as scope resolution operator is used to associate member functions
to their corresponding class.
The format is :
return _type class_name : : function_name
Memory Allocation for objects
The member function are created and placed in the memory space only once when
they are defined in class specification.
All the objects belonging to that class use the same member functions.
Space for member variable is allocated separately for each object because member
variable holds different value for different objects.
Exercise :-
1. Write a c++ object oriented program which perform the sum of two numbers and
return their sum.
2. Write a c++ object oriented program which reads two numbers and display the
smallest of them.
Array within a class
The concept of array within a class is similar to that of array within structure.
class class_Name
{
int a[20];
public:
………;
----------;
};
class class_Name
{
int a[2][3];
public:
………;
----------;
};
Exercise:
1. Write object oriented based C++ program which performs addition, subtraction and
multiplication of matrix.
Array of object
We know that memory is allocated to an object when we declare the object.
Array is a collection of homogeneous data items. Therefore, we can create an
array in which each data item is class type such array is called array of object.
Eg :-The following program reads bio-data of four students and then prints their
bio-data.
class Bio {
char Name[20];
char Address[20];
int phonenumber;
public:
void getData();
void showData();
};
void Bio::getData(){
cout<<―Enter Name‖;
cin>>Name;
cout<<―Enter Address‖;
cin>>Address;
cout<<―Enter phone number‖;
cin>>phonenumber;
}
void Bio::showData(){
cout<<―Name‖<<Name;
cout<<―Address‖<<Address;
cout<<―Phone number‖<<phonenumber;
}
int main(){
Bio bio [4];
for(int i=0;i<=3;i++)
cout<<―Enter ‖<<i+1<<―person bio‖<endl;
bio.getData();
for(int i=0;i<=3;i++)
cout<<―Bio data of ‖<<i+1<<―person is‖<endl;
bio.showData();
return 0;
}
Constructors
A constructor is a special member function that initializes the objects of its class.
It is special because its name is the same as the class name.
It is invoked automatically whenever an object is created. It is called constructor
because it constructs the values of data members of the class.
It does not have any return type, not even void
Constructors must be declared publicly.
class student
{
int rn;
int total ;
public:
student ( )
{
rn = 0 ; total = 0 ;
}
} ;
Cont…
.
Default Constructor
A constructor that accepts no parameter is called default constructor. If no such
constructor is defined, then the compiler supplies a default constructor.
 In that case, it is called nothing-to-do constructor.
Parameterized Constructors
The constructors that can take arguments are called parameterized constructors.
class student
{
int rn, total ;
public
student (int x, int y)
{
rn = x ; total = y ;
}
Cont…
When the object is created, we must supply arguments to the constructor function.
This can be done in two ways:
• By calling the function explicitly
• By calling the function implicitly
The first call is implemented as follows :
• student S1 = student ( 1, 70 ) ;
• The second call is implemented as follows :
• student S1 ( 1, 70 ) ;
The second method is used very often as it is shorter.
Constructor with default arguments
The constructor can be declared with default argument.
For example :
student ( int rn, int total = 0 ) ;
Here the default value of total is zero.
Then the statement
student S1 ( 2 ) ;
assigns the value 2 to rn and 0 to total.
However, the statement
student S2 ( 3, 75 ) ;
assigns 3 to rn and 75 to total. In this case actual parameter takes the priority
over default parameter.
All default values should be on the right side.
Destructor
• A destructor is a member function that is automatically called when an object is
destroyed.
• Destructors have the same name as the class, preceded by a tilde character (~)
• In the same way that a constructor is called then the object is created, the
destructor is automatically called when the object is destroyed.
• In the same way that a constructor sets things up when an object is created, a
destructor performs shutdown procedures when an object is destroyed.
Cont…
This program demonstrates a destructor.
#include <iostream.h>
class Demo
{
public:
Demo(void); // Constructor
~Demo(void); // Destructor
};
Demo::Demo(void)
{
cout << "Welcome to the constructor!n";
}
Demo::~Demo(void)
{
cout << "The destructor is now running.n";
}
void main(void)
{
Demo demoObj; // Declare a Demo obje
cout << "This program demonstrates an
objectn";
cout << "with a constructor and destructor.n
}
Program Output
Welcome to the constructor!
This program demonstrates an object
with a constructor and destructor.
The destructor is now running.
Thank You ...

More Related Content

PPT
Chapter 1.ppt
PPTX
Chapter 1 (2) array and structure r.pptx
PPT
POLITEKNIK MALAYSIA
PPT
Chapter Introduction to Modular Programming.ppt
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
PDF
Chapter 1. Functions in C++.pdf
PDF
Chapter_1.__Functions_in_C++[1].pdf
DOCX
Functions assignment
Chapter 1.ppt
Chapter 1 (2) array and structure r.pptx
POLITEKNIK MALAYSIA
Chapter Introduction to Modular Programming.ppt
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
Chapter 1. Functions in C++.pdf
Chapter_1.__Functions_in_C++[1].pdf
Functions assignment

Similar to All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt (20)

PDF
PPTX
CHAPTER THREE FUNCTION.pptx
PPTX
Functions in C++
PPTX
Functions in C++
PPT
Fp201 unit5 1
PPT
PPTX
Chp8_C++_Functions_Part2_User-defined functions.pptx
DOC
Functions
PPTX
Chapter 4
PDF
PDF
Cpp functions
PPTX
Functions and modular programming.pptx
PDF
Functions in C++.pdf
PDF
(3) cpp procedural programming
PPTX
Chapter One Function.pptx
PPTX
Programming Fundamentals lecture-10.pptx
DOCX
Introduction to c programming
PPT
user defined function
PPT
Lecture 4
PDF
PSPC-UNIT-4.pdf
CHAPTER THREE FUNCTION.pptx
Functions in C++
Functions in C++
Fp201 unit5 1
Chp8_C++_Functions_Part2_User-defined functions.pptx
Functions
Chapter 4
Cpp functions
Functions and modular programming.pptx
Functions in C++.pdf
(3) cpp procedural programming
Chapter One Function.pptx
Programming Fundamentals lecture-10.pptx
Introduction to c programming
user defined function
Lecture 4
PSPC-UNIT-4.pdf
Ad

More from jacobdiriba (8)

PPTX
Chapter Two networking.pptxvggggggggggg n n n n n n n n n n n n n n n
PDF
rk ch 4.pdfBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
PDF
AI Chapter 3.pdfvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
PPT
ch01-Introduction Databases and Database Users.ppt
PPTX
SE_Sumerized.pptx nccccccccccmmmmmmmmmmmmmmmmmmmmmmmmmmmm
PPT
Automata_and_Complexity_Theommmmmmmry-RevisionforExitExam.ppt
PDF
2.Security (1).pdfccccccccccccccccccccccccccccccccccccccccccccc
PPTX
chapter 4&5 system analysis ppt.puyyyyyyyyyyyyyyyyyyyyyyyyptx
Chapter Two networking.pptxvggggggggggg n n n n n n n n n n n n n n n
rk ch 4.pdfBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
AI Chapter 3.pdfvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
ch01-Introduction Databases and Database Users.ppt
SE_Sumerized.pptx nccccccccccmmmmmmmmmmmmmmmmmmmmmmmmmmmm
Automata_and_Complexity_Theommmmmmmry-RevisionforExitExam.ppt
2.Security (1).pdfccccccccccccccccccccccccccccccccccccccccccccc
chapter 4&5 system analysis ppt.puyyyyyyyyyyyyyyyyyyyyyyyyptx
Ad

Recently uploaded (20)

PPTX
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Computing-Curriculum for Schools in Ghana
PPTX
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Paper A Mock Exam 9_ Attempt review.pdf.
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Radiologic_Anatomy_of_the_Brachial_plexus [final].pptx
Final Presentation General Medicine 03-08-2024.pptx
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
LNK 2025 (2).pdf MWEHEHEHEHEHEHEHEHEHEHE
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
LDMMIA Reiki Yoga Finals Review Spring Summer
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Chinmaya Tiranga quiz Grand Finale.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Computing-Curriculum for Schools in Ghana
UNIT III MENTAL HEALTH NURSING ASSESSMENT
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Paper A Mock Exam 9_ Attempt review.pdf.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Final Presentation General Medicine 03-08-2024.pptx
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape

All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt

  • 1. Wolkite University Fundamentals of Programming II CoSc1014 Chapter-One Functions Melaku Kore [email protected]
  • 2. What is Function?  C ++ enables its programmers to break up a program into segments commonly known as functions, each of which can be written more or less independently of the others.  A function is a group of statements that together perform a task.  Every function in the program is supposed to perform a well-defined task.  Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.  A function is a block of code designed to tackle a specific problem.  One of the best ways to tackle a problem is to start with the overall goal, then divide this goal into several smaller tasks. You should never lose sight of the overall goal, but think also of how individual pieces can fit together to accomplish such a goal.  Function makes a program much easier to read, test and debug
  • 3. Cont…  In the figure, we can see that main() calls a function named func1().  Therefore, main() is known as the calling function and func1() is known as the called function.  The moment the compiler encounters a function call, the control jumps to the statements that are a part of the called function.  After the called function is executed, the control is returned to the calling program.
  • 4. Cont… The main() function can call as many functions as it wants and as many times as it wants. For example, a function call placed within a for loop, while loop, or do– while loop may call the same function multiple times till the condition holds true. Not only main(), any function can call any other function.
  • 5. Why? Dividing the program into separate well-defined functions facilitates each function to be written and tested separately. Understanding, coding, and testing multiple separate functions is easier than doing the same for one big function. When a big program is broken into comparatively smaller functions, then different programmers working on that project can divide the workload by writing different functions. Like C/C++ libraries, programmers can also write their own functions and use them from different points in the main program or any other program that needs its functionalities.
  • 6. C++ functions generally adhere to the following rules: 1. Every function must have a name. 2. Function names are made up and assigned by the programmer following the same rules that apply to naming variables. They can contain up to 32 characters, they must begin with a letter, and they can consist of letters, numbers, and the underscore (_) character. 3. All function names have one set of parenthesis immediately following them. This helps you (and C++ compiler) differentiate them from variables. 4. The body of each function, starting immediately after parenthesis of the function name, must be enclosed by braces.
  • 7. Components of Function  Function declaration :-Before using a function, the compiler must know the number of parameters and the type of parameters that the function expects to receive and the data type of value that it will return to the calling program. Placing the function declaration statement prior to its use enables the compiler to make a check on the arguments used while calling that function. It is the interface of a function (also called function prototype) specifies how it may be used. Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function. return_type function_name( parameter list );
  • 8. Cont… return_type:-specifies the data type of the value that will be returned to the calling function as a result of the processing performed by the called function. 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. Parameter names are not important in function declaration only their type is required.
  • 9. Cont… A function definition consists of two parts: interface (prototype or function header ) & body. The function header is same as the function declaration. The only difference between the two is that a function header is not followed by a semi-colon. Function Body − The function body contains a collection of statements that define what the function does. Syntax of function definition return_type function_name( parameter list ) { body of the function } If function definition is done before the main function, then there is no need to put the prototype, otherwise the prototype should be script before the main function starts
  • 10. Function Calling Calling a function means making the instruction of the function to be executed. While creating a C++ function, you give a definition of what the function has to do. When a function call is executed, the arguments are first evaluated and their resulting values are assigned to the corresponding parameters. The function call statement invokes the function. When a function is invoked, the compiler jumps to the called function to execute the statements that are a part of that function. Once the called function is executed, the program control passes back to the calling function.
  • 11. Function calling The following points are to be noted while calling a function:  Function name and the number and the type of arguments in the function call must be same as that given in the function declaration and the function header of the function definition. Names (and not the types) of variables in function declaration, function call, and header of function definition may vary. Arguments may be passed in the form of expressions to the called function. In such a case, arguments are first evaluated and converted to the type of formal parameter and then the body of the function gets executed.  If the return type of the function is not void, then the value returned by the called function may be assigned to some variable as given below. variable_name = function_name(variable1, variable2, ...);
  • 12. Example 1. Write a program to find whether a number is even or odd using functions. int evenodd(int); Function Declaration int main() { int num, flag; cout<<"n Enter the number : "; cin>>num; flag = evenodd(num); Function calling if (flag == 1) cout<< num <<" IS EVEN"; else cout<< num<<―IS ODD"; return 0; } int evenodd(int a) // Function header { // Function body if(a%2 == 0) return 1; else retun 0; }
  • 13. Example 2. Write a function which calculates the area of rectangle. Note the dimensions of the polygon should be provided from the user. void AreaRectangle (int l,int w); void main() { int length,width,area; cout<<Enter Length and width of rectangle‖; cin>>length>>width; AreaRectangle(length,width); } void AreaRectangle (int l,int w) { int area; area=l*w; cout<<―The area of rectangle is=‖<<area; }
  • 14. Example 2 3 . Write a function which return the maximum of two numbers. Note that the numbers should be provided from the user. int max(int num1, int num2) { // local variable declaration int result; if (num1 > num2) result = num1; else result = num2; return result; } void main() { int FirstNum,SecondNum, maximum; cout<<―Enter the two numbers‖; cin>> FirstNum>>SecondNum; maximum=max(FirstNum,SecondNum); cout<<―Maximum of two numbers is=‖<<maximum; }
  • 15. Home Work 3. Write C++ program using function which perform all arithmetic operations for two numbers. Note:- 1. Use different functions for each operation 2. Check divide by zero exception (If denominator is zero your program display error message). 3. Your program display menu for the user to select the operation.
  • 16. Function Parameters A parameter is like a placeholder. Arguments or parameters are divided into two: Formal and Actual parameters o When a function is called some parameters are written within the parenthesis . These are know as actual parameters. eg AreaRectangle (length, width); o Formal parameters are those who are written in the function header. eg void AreaRectangle (int length,int width); The formal parameter and the variable which declare inside the body of function are created when function called and they exist only upto control remain on the function. We can give same name for actual and formal parameters but their implementation is different.  If in any function there is no formal parameters then we can write void instead.
  • 17. Passing Arguments There are 2 ways to pass arguments into a function 1. Passing By value :- The value of the actual parameter is passed to formal parameters when we call the function. • In this method, the called function creates new variables to store the value of the arguments passed to it. • Therefore, the called function uses a copy of the actual arguments to perform its intended task. • If the called function is supposed to modify the value of the parameters passed to it, then the change will be reflected only in the called function.
  • 18. Cont… • In the calling function, no change will be made to the value of the variables. This is because all the changes are made to the copy of the variables and not to the actual variables. void add(int n); int main() { int num = 2; cout<<"nThe value of num before calling the function "<< num; add(num); cout<<"nThe value of num after calling the function = "<<num; return 0; } void add(int n) { n = n + 10; cout<<"n The value of num in the called function = "<< n; }
  • 19. Cont… Output The value of num before calling the function = 2 The value of num in the called function = 12 The value of num after calling the function = 2 Following are the points to remember while passing arguments to a function using the call-by value method:  When arguments are passed by value, the called function creates new variables of the same data type as the arguments passed to it.  The values of the arguments passed by the calling function are copied into the newly created variables.  Values of the variables in the calling functions remain unaffected when the arguments are passed using the call-by-value technique.
  • 20. Cont… 2. Passing By Reference In this method, we declare the function parameters as references rather than normal variables. When this is done, any changes made by the function to the arguments it received are also visible in the calling function. To indicate that an argument is passed using call by reference, an asterisk (*) is placed after the type in the parameter list. A reference parameter, on the other hand, receives the argument passed to it and works on it directly. Any change made by the function to a reference parameter is in effect directly applied to the argument.
  • 21. Cont… void add(int *n); int main() { int num = 2; cout<<"nThe value of num before calling the function "<< num; add(&num); cout<<"nThe value of num after calling the function = "<<num; return 0; } void add(int *n) { *n = *n + 10; cout<<"n The value of num in the called function = "<< n; } Output The value of num before calling the function = 2 The value of num in the called function = 12 The value of num after calling the function = 12
  • 22. Exercise :- What is the output of this program ? void swap_call_val(int, int); void swap_call_ref(int *, int *); int main() { int a=1, b=2, c=3, d=4; cout<<"n In main() a = "<<a<<" and b = "<<b; swap_call_val(a, b); cout<<"n In main() a = "<<a<<" and b = "<<b; cout<<"nn In main() c = "<<c<<" and d = "<<d; swap_call_ref(&c, &d); cout<<"n In main() c =“<<c <<"and d =“<<d; return 0; } void swap_call_val(int a, int b) { int temp; temp = a; a = b; b = temp; cout<<"n In function (Call By Value Method) – a = "<<a <<"and b = "<<b; } void swap_call_ref(int *c, int *d) { int temp; temp = *c; *c = *d; *d = temp; cout<<"n In function (Call By Reference Method) – c ="<<c<<" and d = "<<d, }
  • 23. Global versus local variables 1. Local variables: Variables that are declared inside a function or block are local variables.  They can be used only by statements that are inside that function or block of code.  Local variables are not known to functions outside their own. 2. Global variables; Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
  • 24. Example void sum (); int c; // global variable declaration: int main () { // local variable declaration: int a, b,c1; // actual initialization a = 10; b = 20; c = a + b; cout << c; sum(); return 0; } void sum() { int x=25; int y=45; c1=x+y; // error cout<<―The sum is =‖<<c1; }
  • 25. Cont… It‘s possible to declare local and global variables of the same name. C++ provides the unary scope resolution operator (::) to access a global variable when a local variable of the same name is in scope. The unary scope resolution operator cannot be used to access a local variable of the same name in an outer block. A global variable can be accessed directly without the unary scope resolution operator if the name of the global variable is not the same as that of a local variable in scope.
  • 26. Example #include <iostream> using namespace std; int num =15; int main() { double num=77.5; // display values of local and global variables cout << "Local double value of number = " <<num; cout<< "nGlobal int value of number = " <<::num << endl; } // end main Output Local double value of number =77.5 Global int value of number = 15
  • 27. Const Argument In C++ we can declare constant like the following const datatype variable _name ; const is a reserved word and any variable declared with this keyword is can‘t be modified. While trying to modify any constant argument the compiler gives syntax error which detect that the argument is non-modifiable value. eg int Add (const int c) { c=c+3;// error }
  • 28. Defualt argument  A function in C++ can be called without specifying all its arguments. In such cases the function declaration must provide default values for those arguments that are not specified. The compiler look at the prototype to see how many arguments a function uses and alerts the program for possible default values. Default argument must be added from right to left, we can not provide a default value to a particular argument in the middle or first of an argument list. Eg float Add(int a,int b=2,int c=5); float Add(int a,int b=2,int c); // illegal
  • 29. Example float func(float p,int n,float r=50); void main() { float p,r,A; int n; cout<<―Enter the value of P and n‖; cin>>p>>n; A=func(p,n); cout<<―The value of A for default value of r is =‖<<A; cout<<―Enter the value of p, n and r‖; cin>>p>>n>>r; A=func(p,n,r); cout<<―The value of A for default value of r is =‖<<A; } // Function definition float func(float p,int n,float r) { float temp=1+r/100; float final=p*pow(temp,n); return final; } 1. Write a function which calculates A where A=P*(1+r/100)n for data p,r and n having fixed value of 50.
  • 30. Function overloading Two or more functions having same name but different argument(s) are known as overloaded functions.  It allows the programmer to write functions to do conceptually the same thing on different types of data without changing the name. The overloaded function should be different interns of number of arguments, data type of the arguments and order of argument lists. If two or more functions differ only in their return types, C++ can‘t overload them.  To be execute the compiler identifies the overloaded function based on the difference they encounter while the function is invoked.
  • 31. Example // Overloaded functions based on argument type int square(int x) { return x*x; } double square(double x) { return x*x; } int main() { cout<<"The square of integer 7 is"<<square(7); cout<<"nThe square of double 7.5 is"<<square(7.5); return 0; }
  • 32. Exercise 1. Write a function which prints area of rectangle and circle using function overloading. While developing the function the value of pi is constant. 2. What is the output of this segment code of program void func1(int a, int b) { a*=2; b+=10; cout<<―a=―<<a<‖ and b= ‖<<b<<endl; } void func2(int *x, int *y) { *x*=2; *y+=10; cout<<―x=―<<*x<‖ and y= ‖<<*y<<endl; } int main(void) { int i=10,j=40; cout<<―i=―<<i<‖ and j= ‖<<j<<endl; func1(i,j); cout<<―i=―<<i<‖ and j= ‖<<j<<endl; func2(&i,&j); cout<<―i=―<<i<‖ and j= ‖<<j<<endl; }
  • 33. Recursion Function A recursive function is one that calls itself. void message(void) { cout << "This is a recursive function.n"; message(); } The function above displays the string "This is a recursive function.", and then calls itself. The function is like an infinite loop because there is no code to stop it from repeating. Like a loop, a recursive function must have some algorithm to control the number of times it repeats.
  • 34. Cont… void message(int times) { if (times > 0) { cout << "This is a recursive function.n"; message(times - 1); } return; } The function contains an if/else statement that controls the repetition. As long as the times argument is greater than zero, it will display the message and call itself again. Each time it calls itself, it passes times - 1 as the argument.
  • 35. Cont.. For example, let's say a program calls the function with the following statement: Message(5);
  • 36. The Recursive Factorial Function In mathematics, the notation n! represents the factorial of the number n. The factorial of a number is defined as: n! = 1 * 2 * 3 * ... * n if n > 0 1 if n = 0  Another way of defining the factorial of a number, using recursion, is: Factorial(n) = n * Factorial(n - 1) if n > 0 1 if n = 0 The following C++ function implements the recursive definition shown above: int factorial(int num) { if (num > 0) return num * factorial(num - 1); else return 1; }
  • 37. Cont… // Function prototype int factorial(int); void main(void) { int number; cout << "Enter an integer value and I will displayn"; cout << "its factorial: "; cin >> number; cout << "The factorial of " << number << " is "; cout << factorial(number) << endl; } int factorial(int num) { if (num > 0) return num * factorial(num - 1); else return 1; }
  • 38. Storage classes The storage class of a variable tells about which part of a program can access it and also tells about its existence. In C++ the storage classes are the following: I. Automatic II. Static III. External IV. Register Automatic A variable is defined within a function Also known as local variable A keyword auto is used to specify automatic variable but we can skip the word auto also.
  • 39. Cont… The general syntax for automatic variable is : auto datatype variable_name; An automatic variable is created only when the function is called in which they are defined and automatically destroyed when we return from the function. The time period between the creation and destruction of a variable is called lifetime. The lifetime of automatic variable is the execution time of the function. But if automatic variable is inside main() then that remains until main is executing.
  • 40. Cont… When we create automatic variable then the compiler does not initialize this. Thus it will take an arbitrary value which maybe 0 or something else. But if we want to initialize we have to assign value for the variable. External External variables re also called global variables Defined outside of any function (i.e the variable defined in between the header of the program and main). To declare external variable the keyword extern is used but we can skip. extern datatype variable_name;
  • 41. Cont… External variable exists for the life of a program. Takes memory space when the program begins and remain until the program ends. If external variables are not initialized by the programmer then its initialized to 0 automatically when they are created. Static A static variable has a scope of that of local variables but life time of external variables. Initialized only once at the beginning, they are not reinitialized each time the function is called. static datatype variable name;
  • 42. Cont… The following program demonstrates the difference between static and local variable. void F1(); void F2(); void main() { F1(); F1(); F1(); F2(); F2(); F2(); } void F1() { int n=1; n++; cout<<―n=―<<n<<endl } void F2() { static int m=1; m++; cout<<―m=―<<m<<endl; } Output n=2 n=2 n=2 m=2 m=3 m=4
  • 43. Cont… The value of n is 2 in every call. Because n is automatic variable, this creates when we call the function and destroy when we come back from the function. In every execution the value of n is destroyed and n is created in the next calling. But the value of m is initialized once at the first execution only. Reading assignment Register storage class
  • 44. Chapter Two Array and String An array is a collection of variables of the same type that are referred to by a common name.  Arrays offer a convenient means of grouping together several related variables, in one dimension or more dimensions: • product part numbers: int part_numbers[] = {123, 326, 178, 1209}; • student scores: int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4}; • 3D coordinates: vector coordinates[4][3] = {{0, 0, 0}, {1, 0, 1}, {1, 0, 5} {4, 7, 9}};
  • 45. How To Declare Arrays To declare an array in C++, you should specify the following things The data type of the values which will be stored in the array The name of the array (i.e. a C++ identifier that will be used to access and update the array values) The dimensionality of the array: • One dimensional (i.e. list of values ), • Two-dimension array (a matrix or a table), etc. The size of each dimension • Examples int x[10]; // An integer array named x with size 10 • float GPA[30]; // An array to store the GPA for 30 students • int studentScores[30][5]; // A two-dimensional array to store the scores of 5 exams for 30 students
  • 46. One-dimensional Arrays We use one-dimensional (ID) arrays to store and access list of data values in an easy way by giving these values a common name, e.g. int x[4]; // all values are named x x[0] = 10; // the 1st value is 10 x[1] = 5; // the 2nd value is 5 x[2] = 20; // the 3rd value is 20 x[3] = 30; // the 4th value is 30 All C++ one-dimensional arrays with N entries start at index 0 and ended at index N-1 i.e arrays in C++ are zero bounded. const int N=5; int v[N]; // this array contains 5 entries It is a common error to try to access the Nth entry, e.g. v[5] or V[N], since the index of the last array entry is N-1, not N
  • 47. Initializing One-dimensional Arrays There are two common ways to initialize one-dimensional arrays • Using for loop, e.g. int x[10]; for( int index=0; index<10; index++) x [index] = index+1 ; • Specifying list of values while declaring the 1D array, e.g. int x[10] = {1,2,3,4,5,6,7,8,9,10}; int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values double z[100] = {0}; // this array contains 100 // entries, all of which are initialized by 0 double w[20] = {5,3,1}; // this array contains 20 entries, // the first three entries are initialized by 5, 3, and1 respectively // while the remaining 17 entries are automatically initialized by 0
  • 48. Storing and displaying Values in 1D Arrays int x[10]; // Reading one value at a time from the user: for (int index=0; index<10; index++) cout<<“nEnter the” <<index+1<<“valuen”; cin >> x[index]; int x[10]; // Displaying one value per line to the user: for (int index=0; index<10; index++) cout << x[index] << endl; void main() { int x[5], index; cout << ―Please enter five integer values: ―; for( index=0; index<5; index++) cin >> x[index]; cout << ―The values in reverse order are: ―; for (index=4; index>=0; index--) cout << setw(3) << x[index]; cout << endl; }
  • 49. Representation of Arrays in Memory In C++, any array is mapped to a contiguous memory location. All memory elements reside next to each other. The lowest address corresponds to the first element, and the highest address to the last element. • Example: int a[8]; int j; for(j=0; j<8; j++) a[j] = 7-j;
  • 50. Example about Sum of arrays #include <iostream> using namespace std; int main() { const int arraySize= 10; // constant variable indicating size of array int a[ arraySize ]= { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; int total = 0; // sum contents of array a for ( int i= 0;i <arraySize;++i ) total += a[ i]; cout << "Total of array elements:" << total << endl; return 0; } // end main
  • 51. Exercise Write the output of the following programs(1-2). 1. int main() { int arr[5]={1,3,5,7,9}; //initialize arr array int i; for(i=0;i<5;i++) //output arr array cout<<arr[i]*arr[i+1]<<"t"; return 0; } 2. int main(){ int arr[5]={1,3,5,7,9}; //initialize arr array int i; for(i=4;i>=0;i--) //output arr array cout<<arr[i]<<"t"; return 0; } 3. Write a program which accepts five scores of ten students result and display sum and average of each students score. 4. Write a C++ program which accepts ten integers and prints the maximum and minimum from the lists it also locate the position where the maximum and minimum element is found .
  • 52. Some Restrictions on Array Consider the following statements: int myList[5] = {0, 4, 8, 12, 16}; //Line 1 int yourList[5]; //Line 2 The statement in Line 1 declares and initializes the array myList, and the statement in Line 2 declares the array yourList. These arrays are of the same type and have the same number of components. Suppose that you want to copy the elements of myList into the corresponding elements of yourList. The following statement is illegal: yourList = myList; //illegal
  • 53. Cont… To copy one array into another array, you must copy it component-wise—that is, one component at a time. This can be done using a loop, such as the following: for (int index = 0; index < 5; index ++) yourList[index] = myList[index]; To read data into yourList, you must read one component at a time, using a loop such as the following: for (int index = 0; index < 5; index ++) cin >> yourList[index];
  • 54. Passing Arrays to Functions To pass an array argument to a function, specify the name of the array without any brackets. In C++, arrays are passed by reference only. Because arrays are passed by reference only, you do not use the symbol & when declaring an array as a formal parameter. For example, if array hourlyTemperatures has been declared as int hourlyTemperatures[ 24 ]; the function call modifyArray( hourlyTemperatures, 24 );
  • 55. Cont… When declaring a one-dimensional array as a formal parameter, the size of the array is usually omitted. If you specify the size of a one-dimensional array when it is declared as a formal parameter, the size is ignored by the compiler. void initialize(int list[], int listSize) { int count; for (count = 0; count < listSize; count++) list[count] = 0; } The first parameter of the function initialize is an int array of any size. When the function initialize is called, the size of the actual array is passed as the second parameter of the function initialize.
  • 56. Exercise 1. Write a program which store an array of five numbers using getNumbers function and prints these numbers using printNumbers function. The numbers should be provided from the user. 1. Write a program which calculates the average of ten numbers, where the numbers are initialized during array declaration and passed to a function called getAverage.
  • 57. Multidimensional array Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be imagined as a two-dimensional table made of elements, all of them of a same uniform data type. The general form of an N -dimensional array declaration is: type array_name [size_1] [size_2] … [size_N]; For example, the following declaration creates a 4 x 10 x 20 character array, or a matrix of strings: char string_matrix[4][10][20];
  • 58. Two-Dimensional Arrays A two-dimensional array is a list of one-dimensional arrays. Arrays that require two subscripts to identify a particular element are called two- dimensional arrays or 2-D arrays To declare a two-dimensional integer array matrix of size 10,20 we would write: int matrix[3][4]; The array contains three rows and four columns, so it‘s said to be a 3-by-4 array. In general, an array with m rows and n columns is called an m-by-n array.
  • 59. Cont… This corresponds to a table with 3 rows and 4 columns (for example). The following program generates the above array. int main() { int row=3, col=4; int matrix[row][col]; for(row=0; row < 3; ++row) { for(col=0; col < 4; ++col) { matrix[row][col] = (row*4)+ col +1; cout << matrix[row][col] << ‘ ‘; } cout << ‘n’; } return(0);}
  • 60. Memory Allocation for Two-Dimensional Arrays Storage for all array elements is determined at compile time. The memory used to hold an array is required the entire time that the array is in existence. The following formula determines the number of bytes of memory that will be allocated: bytes = rows * columns * number_of_bytes_in_type For example, an integer array (with two-byte integers) with dimensions 100,100 would require 100 * 100 * 2 = 20,000 bytes.
  • 61. Exercise 1. Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2]. 2. Write a C++ program that adds the values of 4 by 4 matrix, you can initialize all values during declaration. 3. Modify the program written for Exercise 2 to display the total of each row of matrix separately. 4. Write a program which displays multiplication table of 12 by 12 matrix.
  • 62. Cont… 5. Write a C++ program that finds and displays the maximum value in a two-dimensional array of integers. The array should be declared as a 4-by-5 array of integers and initialized with the data 16, 22, 99, 4, 18, -258, 4, 101, 5, 98, 105, 6, 15, 2, 45, 33, 88, 72, 16, and 3. 6. Modify the program written in Exercise 5 so that it also displays the maximum value‘s row and column subscript numbers. 7. Write a C++ program that displays the contents of two dimensional array by passing the array elements as arguments of the function. 8. Write a program that includes two functions named calcavg() and variance(). The calcavg() function should calculate and return the average of values stored in an array named testvals. The array should be declared in main() and include the values 89, 95, 72,83, 99, 54, 86, 75, 92, 73, 79, 75, 82, and 73. The variance() function should calculate and return the variance of the data. The variance is obtained by subtracting the average from each value in testvals, squaring the values obtained, adding them, and dividing by the number of elements in testvals.
  • 63. String • One of the most useful data types supplied in the C++ libraries is the string. • A string is a variable that stores a sequence of letters or other characters, such as "Hello" or "May 10th is my birthday!". • Just like the other data types, to create a string we first declare it, then we can store a value in it. string testString; testString = "This is a string."; • Often, we use strings as output, and cout works exactly like one would expect: • cout << testString << endl; will print the same result as • cout << "This is a string." << endl;
  • 64. Cont… In order to use the string data type, the C++ string header <string> must be included at the top of the program. String manipulation using arrays  The most common use for one-dimensional arrays is to store strings of characters In C++, a string is defined as a character array terminated by a null symbol (‘0’).  To declare an array Str that could hold a 10-character string, one would write: char str[11];
  • 65. Cont… Specifying the size as 11 makes room for the null at the end of the string. Some examples of string constants in C++ are: "hello there" "I like C++." "#$%§@@+*" """ """" "" ""  The null string, “ “, only contains the null terminator and represents the empty string.
  • 66. Reading a String from the Keyboard How to read a string entered from the keyboard? Make an array, that will receive the string, the target of a cin stream. The following program reads (part of) a string entered by the user: int main() { char str[80]; cout << ―Enter a string: ―; cin >> str; // read string from keyboard cout << ―Here is your string: ―; cout << str; return(0);}
  • 67. Cont… Problem: Entering the string ― This is a test‖, the above program only returns ―This ‖, not the entire sentence. Reason: The C++ input/output system stops reading a string when the first whitespace character is encountered. Solution: Use another C++ library function, gets(). To use gets() libraray function we have to include <cstdio> as header. The function takes one argument i.e name of the string.
  • 68. Cont… #include <iostream.h> #include <cstdio.h> int main() { char str[80]; // long enough for user input? cout << ―Enter a string: ―; gets(str); // read a string from the keyboard cout << ―Here is your string: ―; cout << str << endl; return(0); }
  • 69. Some C++ Library Functions for Strings C++ supports a range of string-manipulation functions. The most common are: strcpy() : copy characters from one string to another strcat() : concatenation of strings strlen(): length of a string strcmp(): comparison of strings
  • 70. Cont… • strcpy(to_string,from_string) — String Copy: #include <iostream.h> #include <cstring.h> int main() { char a[10]; strcpy(a, ―hello‖); cout << a; return(0); }
  • 71. Cont… strlen(string) — String Length strlen(str) returns the length of the string pointed to bystr, i.e.,the number of characters excluding the null terminator. int main() { char str[80]; cout << ―Enter a string: ―; gets(str); cout << ―Length is: ― << strlen(str); return(0); }
  • 72. Cont… strcat(string_1,string_2) — Concatenation of Strings The strcat() function appends s2 to the end of s1 . String s2 is unchanged. int main() { char s1[21], s2[11]; strcpy(s1, ―hello‖); strcpy(s2, ― there‖); strcat(s1, s2); cout << s1 << endl; cout << s2 << endl; return(0); }
  • 73. Cont… strcmp(string_1,string_2) — Comparison of Strings The strcmp(str_1, str_2) function compares two strings and returns the following result: • str_1 == str_2 : 0 • str_1 > str_2 : positive number • str_1 < str_2 : negative number The strings are compared lexicographically (i.e., according to dictionary order): • a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd < ...
  • 74. Chapter Three Structure  C/C++ arrays allow you to define variables that combine several data items of the same kind, but structure is another user defined data type which allows you to combine data items of different kinds. Structure is a collection of data items. The data item can be different type, some can be int type, some can be float, some can be char and so on. The data item of structure is called member of the structure. In other words, heterogeneous data types can be grouped to form a structure.
  • 75. Cont… The difference between array and structure is the element of the array has same type, while the element of structure can be different. The other difference is that each element of the array referred by its position while each element of a structure has a unique name. Declaration of structure struct [structure tag] { Data type 1 member 1; Data type 2 member 2; Data type n member n; } ; struct Books { char title[50]; char author[50]; char subject[100]; int book_id; };
  • 76. Creating Structure variable Structure variable can be creating in the following 3 ways. struct [structure tag] { Data type 1 member 1; Data type 2 member 2; Data type n member n; } a, b …; struct [structure tag] { Data type 1 member 1; Data type 2 member 2; Data type n member n; } ; struct structure tag a,b..; struct [structure tag] { Data type 1 member 1; Data type 2 member 2; Data type n member n; } ; structure tag a,b..;
  • 77. S2 Cont… struct student { char Name[30]; int RollNo; char Sex[5]; int age; } S1,S2; Name RollNo Sex age Name RollNo Sex age S1  Unless a structure variable is created memory space is not reserved for members of the structure.
  • 78. Accessing Member of Structure To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. Syntax : stracture variableName.member struct student { char Name[30]; int RollNo; char Sex[7]; int age; } S1,S2; strcpy(S1.Name,‖Helen‖); S1.RollNo=1234; strcpy(S1.Sex,‖Female‖); S1.age=23; Helen 1234 Female 23
  • 79. struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book1; // Declare Book1 of type Book Books Book2; // Declare Book2 of type Book int main() { // book 1 specification strcpy( Book1.title, "Learn C++ Programming"); strcpy( Book1.author, "Chand Miyan"); strcpy( Book1.subject, "C++ Programming"); Book1.book_id = 6495407; // book 2 specification strcpy( Book2.title, "Telecom Billing"); strcpy( Book2.author, "Yakit Singha"); strcpy( Book2.subject, "Telecom"); Book2.book_id = 6495700; // Print Book1 info cout << "Book 1 title : " << Book1.title <<endl; cout << "Book 1 author : " << Book1.author <<endl; cout << "Book 1 subject : " << Book1.subject <<endl; cout << "Book 1 id : " << Book1.book_id <<endl; // Print Book2 info cout << "Book 2 title : " << Book2.title <<endl; cout << "Book 2 author : " << Book2.author <<endl; cout << "Book 2 subject : " << Book2.subject <<endl; cout << "Book 2 id : " << Book2.book_id <<endl; return 0; }
  • 80. Cont… When the above code is compiled and executed, it produces the following result − Book 1 title : Learn C++ Programming Book 1 author : Chand Miyan Book 1 subject : C++ Programming Book 1 id : 6495407 Book 2 title : Telecom Billing Book 2 author : Yakit Singha Book 2 subject : Telecom Book 2 id : 6495700
  • 81. Initialization of structure Like normal variable structures can be initialized at the time of declaration. Initialization of structure is almost similar to initializing array. struct Employee { int Id; char Name[25]; int Age; long Salary; }; void main() { Employee E = {2,"Suresh",35,35000}; cout << "nnEmployee Id : " << E.Id; cout << "nEmployee Name : " << E.Name; cout << "nEmployee Age : " << E.Age; cout << "nEmployee Salary : " << E.Salary; Output : Employee Id : 1 Employee Name : Kumar Employee Age : 29 Employee Salary : 45000
  • 82. Array of Structure Structure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object.  As we know, an array is a collection of similar type, therefore an array can be of structure type. struct structure-name { datatype var1; datatype var2; - - - - - - - - - - - - - - - - - - - - datatype varN; }; structure-name obj [ size ]; Syntax for declaring structure array
  • 83. Cont… struct Employee { int Id; char Name[25]; int Age; long Salary; }; void main() { int i; Employee Emp[ 3 ]; //Statement 1 for(i=0;i<3;i++) { cout << "nEnter details of " << i+1 << " Employee"; cin >> Emp[i].Id>> Emp[i].Name>> Emp[i].Age >> Emp[i].Salary; }
  • 84. Array within Structure Like normal data type, structure can also store an array as well. Syntax for array within structure struct structure-name { datatype var1; // normal variable datatype array [size]; // array variable - - - - - - - - - - - - - - - - - - - - datatype varN; }; structure-name obj; Eg. struct Student { int Roll; char Name[25]; int Marks[3]; //Statement 1 : array of marks int Total; float Avg; };
  • 85. Cont… void main() { int i; Student S; cout << "nnEnter Student Roll : "; cin >> S.Roll; cout << "nnEnter Student Name : "; cin >> S.Name; S.Total = 0; for(i=0;i<3;i++) { cout << "nnEnter Marks " << i+1 << " : "; cin >> S.Marks[i]; S.Total = S.Total + S.Marks[i]; } S.Avg = S.Total / 3; }
  • 86. Structure within structure When a structure contains another structure, it is called nested structure. For example, we have two structures named Address and Employee.  To make Address nested to Employee, we have to define Address structure before and outside Employee structure and create an object of Address structure inside Employee structure. struct structure1 { - - - - - - - - - - - - - - - }; struct structure2 { - - - - - - - - - - - - - - - - - - - - structure1 obj; }; Syntax for structure within structure or nested structure
  • 87. Cont… struct Address { char HouseNo[25]; char City[25]; char PinCode[25]; }; struct Employee { int Id; char Name[25]; float Salary; Address Add; }; void main() { int i; Employee E; cout << "ntEnter Employee Id : "; cin >> E.Id; cout << "ntEnter Employee Name : "; cin >> E.Name; cout << "ntEnter Employee Salary : "; cin >> E.Salary; cout << "ntEnter Employee House No : "; cin >> E.Add.HouseNo; cout << "ntEnter Employee City : "; cin >> E.Add.City; cout << "ntEnter Employee House No : "; cin >> E.Add.PinCode; }
  • 88. Structures as Function Arguments Using function we can pass structure as function argument and we can also return structure from function. Structure can be passed to function through its object therefore passing structure to function or passing structure object to function is same thing because structure object represents the structure. Like normal variable, structure variable(structure object) can be pass by value or by references.
  • 89. Passing Structure by Value The structure object is passed as function argument to the definition of function, here object is representing the members of structure with their values. Eg. struct Employee { int Id; char Name[25]; int Age; long Salary; }; void Display(struct Employee); void main() { Employee Emp = {1,"Kumar",29,45000}; Display(Emp); } void Display(struct Employee E) { cout << "nnEmployee Id : " << E.Id); cout << "nEmployee Name : " << E.Name); cout << "nEmployee Age : " << E.Age); cout << "nEmployee Salary : " << E.Salary); } Output : Employee Id : 1 Employee Name : Kumar Employee Age : 29 Employee Salary : 45000
  • 90. Passing Structure by Reference In this approach, the reference/address structure object is passed as function argument to the definition of function. Eg . struct Employee { int Id; char Name[25]; int Age; long Salary; }; void Display(struct Employee &E); void main() { Employee Emp = {1,"Kumar",29,45000}; Display(Emp); cout<< " n" <<Emp.Id } void Display(struct Employee &E) { E.Id=5; cout << "nnEmployee Id : " << E.Id; cout << "nEmployee Name : " << E.Name; cout << "nEmployee Age : " << E.Age; cout << "nEmployee Salary : " << E.Salary; } Output : Employee Id : 5 Employee Name : Kumar Employee Age : 29 Employee Salary : 45000 5
  • 91. Exercise 1. Write a complete C++ program which shows the details of students. Note that your program include college details, department details and student personal information and all those details should be a record themselves. Your program should consists of the following concepts:-  Nested structure (structure within structure) Array of structure i.e the record should be more than a single record In the student personal information structure you have to apply array within structure.
  • 92. Chapter Four Pointers Introduction In C++, every value is stored somewhere in memory and can therefore be identified with that address. Such addresses are called pointers.  A pointer is a variable which stores the address of another variable. The only difference between pointer variable and regular variable is the data they hold. A pointer is simply the address of an object in memory. Generally, objects can be accessed in two ways: directly by their symbolic name, or indirectly through a pointer.
  • 93. Declaring Pointers Like all variables, pointers must be declared before they can be used to store an address. When you declare a pointer variable, C++ requires also specifying the type of variable that‘s pointed to. Is reserving a memory location for a pointer variable. Syntax: type * pointer_name ; For example, if you wanted to declare a variable px to be a pointer to a double value, you could do so as follows: double *px; Similarly, to declare a variable pptr as a pointer to a Point structure, you would write: Point *pptr;
  • 94. Pointer Operators C++ includes two built-in operators for working with pointers: The address-of operator (&) is written before a variable name (or any expression to which you could assign a value) and returns the address of that variable. Thus, the expression &total gives the address of total in memory. The dereference operator (*) is written before a pointer expression and returns the actual value to which the pointer points.  Suppose, for example, that you have declared and initialized the following variables: double x = 2.5; double *px = &x;  At this point, the variable px points to the variable x, and the expression *px is synonymous with the variable x.
  • 95. Getting Address of a variable int main() { int num; num = 22; cout << "The value stored in num is " << num << endl; cout << "The address of num = " << &num << endl; return 0; } Output The value stored in num is 22 The address of num = 0012FED4  Address information changes, depending on what computer is running the program and how many other programs are currently loaded into memory.
  • 96. Cont… Besides displaying the address of a variable, you can store addresses in suitably declared variables. For example var=25; x=var; ptr = &var;  We have assigned to x the content of variable var as we have done in many other occasions in previous sections, but to ptr we have assigned the address in memory where the operating system stores the value of var , that we have imagined that it was 1776 (it can be any address).
  • 97. Cont…  The content of or dereference operators allows us to get the value at the address held by the pointer.  The * operator, when used with pointers, either declares a pointer or dereferences the pointer‘s value.  The dereference operator can be literally translated to "value pointed by”.  The act of getting to an object via a pointer to it, is called dereferencing the pointer.  Pointer variables are defined to point to objects of a specific type so that when the pointer is dereferenced, a typed object is obtained.
  • 98. Assigning values to pointers Assigning values to pointers is similar to that of assigning values to normal variable, except that the variable is pointer variable. Suppose ptr is a pointer variable then to assign an integer value ,5 int *ptr; === int *ptr=5; ptr=5; OR int x=5; int *ptr;====int *ptr=&x; ptr=&x; cout<<x;//prints the value of x Or by using pointers you can do it as follows cout<<*ptr;//dereferences ptr; cout<<ptr;// print an address (the address of x).
  • 99. Cont… int main() { int *numAddr; // declare a pointer to an int int miles, dist; // declare two integer variables dist = 158; // store the number 158 in dist miles = 22; // store the number 22 in miles numAddr = &miles; // store the address of miles in numAddr cout << "The address stored in numAddr is " << numAddr << endl; cout << "The value pointed to by numAddr is " << *numAddr << "nn"; numAddr = &dist; // now store the address of dist in numAddr cout << "The address now stored in numAddr is " << numAddr << endl; cout << "The value now pointed to by numAddr is " << *numAddr << endl; return 0; } Output The address stored in numAddr is 0012FEC8 The value pointed to by numAddr is 22 The address now stored in numAddr is 0012FEBC The value now pointed to by numAddr is 158
  • 100. Cont… void main(void) { int x = 25, y = 50, z = 75; int *ptr; cout << "Here are the values of x, y, and z:n"; cout << x << " " << y << " " << z << endl; ptr = &x; // Store the address of x in ptr *ptr *= 2; // Multiply value in x by 2 ptr = &y; // Store the address of y in ptr *ptr *= 2; // Multiply value in y by 2 ptr = &z; // Store the address of z in ptr *ptr *= 2; // Multiply value in z by 2 cout << "Once again, here are the values of x, y, and z:n"; cout << x << " " << y << " " << z << endl; }
  • 101. References and Pointers What is the difference between a pointer and a reference? A reference is a named constant for an address; therefore, the address named as a reference can‘t be altered. Because a pointer is a variable, the address in a pointer can be changed. For most applications, using references rather than pointers as arguments to functions is easier and preferred. Why?? The reason is the simpler notation for locating a reference parameter, which eliminates the address operator (&) and indirection operator (*) required for pointers.
  • 102. Cont… Syntax for reference variable :- dataType& newName = existingName; For example, the reference declaration double& sum = total; equates the name sum to the name total. Both now refer to the same variable. A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.
  • 103. Cont… int main() { double total = 20.5; // declare and initialize total double& sum = total; // declare another name for total cout << "sum = " << sum << endl; sum = 18.6; // this changes the value in total cout << "total = " << total << endl; return 0; } Because the variable sum is simply another reference to the variable total, the first cout statement in the program displays the value stored in total. Changing the value in sum then changes the value in total, which the second cout statement in the program displays. output sum = 20.5 total = 18.6
  • 104. Cont… When constructing references, keep two points in mind.  First, the reference should be of the same data type as the variable it refers to. int num = 5; double& numref = num; // INVALID - CAUSES A COMPILER ERROR Second ,a compiler error is produced when an attempt is made to equate a reference to a constant. int& val = 5; // INVALID - CAUSES A COMPILER ERROR
  • 105. Pointer Arithmetic As we know pointer stores the address of another variable, memory location we can perform the following operations. Pointer increment ,p++ or ++p Pointer decrement, p- - or --p Constant addition, p+k Constant subtraction , p-k
  • 106. Pointer Increment If p is a pointer then ++p,p++ is possible with pointer. Pointer increment, p++ or ++p does not mean adding 1 to the pointer but adding the size of that data type to the pointer p. eg int x,*p,*q; short int y; p=&x; q =&y; ++q; p++; Here if both p and q has an address of 1000 after the statement p=&x then p++ will be 1004 which is incrementing the size of (x) and ++q will be 1002 ;
  • 107. Pointer Decrement If p is a pointer then --p,p-- is possible with pointer. Pointer increment, p-- or --p does not mean subtracting 1 from the pointer but subtracting the size of that data type from the pointer p. eg int x,*p,*q; short int y; p=&x; q =&y; --q; p--; Here if both p and q has an address of 1004 after the statement p=&x then p-- will be 1000 which is incrementing the size of (x) and --q will be 1002;
  • 108. Constant addition /subtraction  An integer can be added to or subtracted from a pointer variable. This may be performed with the +, - +=, or -= operators. Eg int main() { int *p,x; x=25; p=&x; *p=*p+10;// same as x=x+10 or p=p+10; cout<<―Now x is‖<<x; // 35 cout<<―The value of x through p:‖<<*p; //35 cout<<―The address of x is‖<<&x; //0x8f51fff4 cout<<―The address of x through p is‖<<x; // 0x8f51fff4 }
  • 109. Pointer to void We cannot assign the address of different type to pointer. If the type of the variable and pointer is different then we can use void as pointer variable. float y; int *x; x=&y; // illegal float *a; int b; a=&b; //illegal float y; void *x; x=&y; void *a; int b; a=&b;
  • 110. Relationship between pointers and arrays Pointers and arrays are strongly related. In fact, pointers and arrays are interchangeable in many cases. For example, a pointer that points to the beginning of an array can access that array by using either pointer arithmetic or array-style indexing. Consider the following program:
  • 111. Relationship between pointers and arrays int main () { int var[3] = {10, 100, 200}; int *ptr; ptr = var; // same as ptr=&var[0]; for (int i = 0; i < 3; i++) { cout << "Address of var[" << i << "] = "; cout << ptr << endl; cout << "Value of var[" << i << "] = "; cout << *ptr << endl; // point to the next location ptr++; } return 0; } Output Address of var[0] = 0xbfa088b0 Value of var[0] = 10 Address of var[1] = 0xbfa088b4 Value of var[1] = 100 Address of var[2] = 0xbfa088b8 Value of var[2] = 200 • Note that the address may be different on different machine.
  • 112. Array of Pointers There may be a situation, when we want to maintain an array, which can store pointers to an int or char or any other data type available. Array of pointer is declared as:- Datatype * array_Name[Size];  Following is the declaration of an array of 10 integers, each element is a pointer type : int *ptr[10]; This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. Consider the following program, to illustrate this concept.
  • 113. Cont… int main () { int var[3] = {10, 100, 200}; int *ptr[3]; for (int i = 0; i < 3; i++) { ptr[i] = &var[i]; // assign the address of integer. } for (int i = 0; i < 3; i++) { cout << "Value of var[" << i << "] = "; cout << *ptr[i] << endl; } return 0; } output Value of var[0] = 10 Value of var[1] = 100 Value of var[2] = 200
  • 114. Cont… You can also use an array of pointers to character to store a list of strings as follows: const int MAX = 4; int main() { char *names[MAX] = {"Zara Ali","Hina Ali","Nuha Ali","Sara Ali"}; for (int i = 0; i < MAX; i++) { cout << "Value of names[" << i << "] = "; cout << names[i] << endl; } return 0; }
  • 115. Pointer to a Pointer A pointer to a pointer is a form of multiple indirection or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
  • 116. Cont… A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk in front of its name.  For example, following is the declaration to declare a pointer to a pointer of type int: int **var; When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires that the asterisk operator be applied twice. Eg. int main () { int var; int *ptr; int **pptr; var = 3000; // take the address of var ptr = &var;
  • 117. Cont… // take the address of ptr using address of operator & pptr = &ptr; // take the value using pptr cout << "Value of var :" << var << endl; cout << "Value available at *ptr :" << *ptr << endl; cout << "Value available at **pptr :" << **pptr << endl; return 0; } When the above code is compiled and executed, it produces the following result: Value of var :3000 Value available at *ptr :3000 Value available at **pptr :3000
  • 118. Pointer as an Argument to a function If a pointer is passed as an argument to a function that is known as pass by address or pass by pointer. The concept is similar to pass by reference but the only difference is that in this case we pass the address of the variable. void swap(int *,int *); void main() { int x,y; x=10; y=20; swap(&x,&y); cout<<―X=‖<<x<<―t‖<<―Y‖<<y; } void swap(int *x,int *y) { int t; t=*a; *a=*b; *b=t; }
  • 119. Memory management through pointer As each variable is defined in a program, sufficient storage for it is assigned from a pool of computer memory locations made available to the compiler. After memory locations have been reserved for a variable, these locations are fixed for the life of that variable, whether or not they are used. For example, int a[100]; reserve 100 space for array a ,but suppose we want to create array at run time then we can do using pointer. When the space is created for a variable at compile time that approach is known as static if the space created at execution /run time its called dynamic. Using dynamic allocation, the amount of storage to be allocated is determined or adjusted at run time • Useful for lists because allows expanding or contracting the memory used
  • 120. Cont… In C++ the new operator is used create space dynamically i.e at run time and the delete operator the is used to release the memory taken by a variable and return memory to the operating system. Dynamic storage requests for scalar variables or arrays are made as part of a declaration or an assignment statement • Example: int *num = new int; // scalar • Example: int *grades = new int[200];// array • Reserves memory area for 200 integers • Address of first integer in array is value of pointer variable grades
  • 121. Chapter Five File Operations (File Input/output) The data created by the user and assigned to variables with an assignment statement is sufficient for some applications. With large volume of data most real-world applications use a better way of storing that data. For this, disk files offer the solution. Storage of data in memory is temporary. Files are used for data persistence permanent retention of data. A File is a collection of information, usually stored on a computer‘s disk.  Information can be saved to files and then later reused.
  • 122. Cont... For example, the C++ programs you store on disk are examples of files. The stored data in a program file is the code that becomes input data to the C++ compiler.  In the context of data processing, however, a C++ program isn‘t usually considered as data, and the term ―file‖ or ―data file‖ typically refers only to external files containing the data used in a C++ program. A file is physically stored on an external medium, such as a disk. Each file has a unique filename, referred to as the file‘s external name. The external name is how the operating system (OS) knows the file.
  • 123. Stream classes Stream is a general name given to flow of data. In C++, there are different types of streams. Each stream is associated with a particular class, which contains member function and definition for dealing with file.  C++ provides the following classes to perform output and input of characters to/from files: • ofstream: represents the output file stream and is used to create files and to write information to files. • ifstream: represents the input file stream and is used to read information from files.
  • 124. Cont... • fstream: represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files. To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
  • 125. Cont... A file stream is a one-way transmission path used to connect a file stored on a physical device, such as a disk or CD, to a program. Each file stream has its own mode that determines the direction of data on the transmission path—that is, whether the path moves data from a file to a program or from a program to a file. A file stream that receives or reads data from a file to a program is an input file stream. A file stream that sends or writes data to a file is an output file stream. The direction, or mode, is defined in relation to the program, not the file; data going into a program is considered input data, and data sent out from a program is considered output data.
  • 126. Cont... .  For each file your program uses, regardless of the file‘s type (text or binary), a distinct file stream object must be created.  If you want your program to read from and write to a file, both input and output file stream objects are required. Input file stream objects are declared to be of type ifstream, and output file stream objects are declared to be of type ofstream.
  • 127. Cont… For example, the following declaration statement declares an input file stream object named inFile to be an object of the ifstream class: ifstream inFile; Similarly, the following declaration statement declares an output file stream object named outFile to be an object of the ofstream class: ofstream outFile; In a C++ program, a file stream is accessed by its stream object name: one name for reading the file and one name for writing to the file. Object names, such as inFile and outFile,can be any programmer-selected name that conforms to C++‘s identifier rules.
  • 128. File Stream Functions Each file stream object has access to the functions defined for its ifstream or ofstream class.  These functions include o connecting a stream object name to an external filename (called opening a file), o determining whether a successful connection has been made, o closing a connection (called closing a file), ogetting the next data item into the program from an input stream, o putting a new data item from the program onto an output stream, and o detecting when the end of a file has been reached.
  • 129. Cont… Opening a file connects a file stream object to a specific external filename by using an open() function, which accomplishes two purposes. • First, opening a file establishes the physical connecting link between a program and a file. • Besides establishing the actual physical connection between a program and a data file, opening a file connects the file‘s external name to the stream object name that the program uses internally. In using the open() function to connect the file‘s external name to its internal object stream name, only one argument is required: the external filename. For example, the following statement connects the external file named prices.dat to the internal file stream object named inFile: inFile.open("prices.dat");
  • 130. Cont… When opening a file for input or output, good programming practice requires checking that the connection has been established before attempting to use the file. You can do this with the fail() function, which returns a true value if the file was opened unsuccessfully (that is, it's true the open failed) or a false value if the open succeeded. Typically, the fail() function is used in code similar to the following, which attempts to open a file named prices.dat for input, checks that a valid connection was made, and reports an error message if the file wasn‘t opened for input successfully:
  • 131. Cont… ifstream inFile; // any object name can be used here inFile.open("prices.dat"); // open the file // Check that the connection was successfully opened if (inFile.fail()) { cout << "nThe file was not successfully opened" << "n Please check that the file currently exists." << endl; exit(1); } • If the fail() function returns a true, indicating the open failed, this code displays an error message. In addition, the exit() function, which is a request to the OS to end program execution immediately, is called.
  • 132. Operation with File • Opening a File To open a file we can use two methods:- using a Constructor or using the open function A file can be created by constructor as follows: ofstream fout(―Hello‖); The above statement creates an object fout (we can give another name also) of stream class and this object a file Hello. The operating system takes the name of the file Hello. In the file Hello we can only write the data because this is created by ofstream class.
  • 133. Cont… A file can be created by using ifstream class through constructor. ifstream infile(―Test‖); The above statement creates an object infile of ifstream class and attached a file Test with this. In the file Test we can perform only input operation (i.e read data from it) because this is created by ifstream class.  These file can be also opened as:- ofstream fout; ofstream fout(―Hello‖); fout.open(―Hello‖); ifstream infile(―Hello‖); ifstream infile(―Test‖); infile.open(―Hello‖);
  • 134. Cont… If you open a file for writing (out access mode), C++ creates the file. If a file by that name already exists, C++ overwrite the old file with no warning. You must be careful when opening files not to overwrite existing data that you want. If an error occurs during opening of a file, C++ does not create a valid file pointer (file object). Instead, C++ creates a file pointer (object) equal to zero. For example if you open a file for output, but use an invalid disk name, C++ can‘t open the file and therefore makes the file object equal to zero. You can also determine the file access mode when creating a file in C++. If you want to use the open function to open a file then the syntax is: fileobject.open(filename,accessmode);
  • 135. Closing File A file is closed by using close() function as follows. infile.close(); outfile.close();  The general syntax is :-file_object_name.close(); Writing to File By using insertion and extraction operator string data can be write and read. void main(){ ofstream outfile(―result‖); outfile<<―Abebe‖; outfile<<―Marks‖; outfile<<―450‖; outfile.close(); }
  • 136. Writing characters to Files A character can be written onto a file using the put() function. See the following code: int main() { char c; ofstream outfile; outfile.open(―c:test.txt‖,ios::out); if(outfile.fail()) { cerr<< ―nError opening test.txt‖; exit(1); } for(int i=1;i<=15;i++) { cout<< ―nEnter a character : ‖; cin>>c; outfile.put(c); } outfile.close(); }//end main
  • 137. Cont…  The above program stores Abebe, Marks and 450 onto file result. Reading From a file Files you open for read access (using ios::in) must exist already, or C++ gives you an error message. You can‘t read a file that does not exist. Open() returns zero if the file does not exist when you open it for read access. If you attempt to read a file that you have completely read the data from, C++ returns the value zero. To find the end-of-file condition, be sure to check for zero when reading information from files. The following code asks the user for a file name and displays the content of the file to the screen.
  • 138. Example . #include <fstream > #include <iostream> #include<cstdlib> using namespace std; ofstream fp; int main() { char name[20],filename[15]; ifstream indata; cout<<"nEnter the file name : "; cin.getline(filename,15); indata.open(filename,ios::in); if(indata.fail()) { cerr<<"nError opening file : "<<filename; exit(1); } while(!indata.eof())// checks for the end-of-file { indata>>name; cout<<name<<endl; } indata.close(); }/
  • 139. Reading Characters from file You can read a character from file using get() function. The following program asks a file name and displays each characters on the screen. int main() { char c,filename[15]; ifstream indata; cout<<"nEnter the file name : "; cin.getline(filename,15); indata.open(filename,ios::in); if(indata.fail()) { cerr<<"nError opening file : "<<filename; exit(1); } while(!indata.eof())// checks for the end-of-file { indata.get(c); cout<<c; } indata.close(); }//end of main
  • 140. File Access Modes • ios::in Open a text file in input mode • ios::out Open a text file in output mode • ios::app Open a text file in append mode • ios::ate Go to the end of the opened file • ios::binary Open a binary file in input mode (default is text file) • ios::trunc Delete the file contents if exists
  • 141. Error handling/ state flags bad() • Returns true if a reading or writing operation fails. For example in the case that 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(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number. eof() • Returns true if a file open for reading has reached the end. good() • It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true.
  • 142. Types of Disk File Access Your program can access files either in sequential manner or random manner. The access mode of a file determines how one can read, write, change, add and delete data from a file.  A sequential file has to be accessed in the same order as the file was written. This is analogues to cassette tapes: you play music in the same order as it was recorded.  Unlike the sequential files, you can have random-access to files in any order you want. Think of data in a random-access file as being similar to songs on compact disc (CD): you can go directly to any song you want to play without having to play or fast-forward through the other songs.
  • 143. Random Access File Concepts Random access enables you to read or write any data in your disk file without having to read and write every piece of data that precedes it.  Generally you read and write file records. A record to a file is analogues to a C++ structure. A record is a collection of one or more data values (called fields) that you read and write to disk. Generally you store data in the structures and write structures to disk. When you read a record from disk, you generally read that record into a structure variable and process it with your program.
  • 144. File Pointer and their Manipulators Each file has two pointers one is called input pointer and second is output pointer. The input pointer is called get pointer and the output pointer is called put pointer. When input and output operation take places, the appropriate pointer is automatically set according to mode. For example when we open a file in reading mode, file pointer is automatically set to start of file. When we open a file in append mode, the file pointer is automatically set to the end of file.  In C++ there are some manipulators by which we can control the movement of the pointer.
  • 146. Cont… . int main(){ fstream fileobj; char ch; //holds A through Z //open the file in both output and input mode fileobj.open("c:alph.txt",ios::out|ios::in); if(fileobj.fail()) { cerr<<"nError opening alph.txt"; exit(1); } //now write the characters to the file for(ch = 'A'; ch <= 'Z'; ch++) { fileobj<<ch; } fileobj.seekg(8L,ios::beg);//skips eight letters, points to I fileobj>>ch; cout<<"nThe 8th character is : "<<ch; fileobj.seekg(16L,ios::beg);//skips 16 letters, points to Q fileobj>>ch; cout<<"nThe 16th letter is : "<<ch; fileobj.close(); return 0; }
  • 147. Cont… The seek() functions allow the programmer to move to any position in the file. Each character in a data file is located by its position in the file. The first character in the file is located at position 0, the next character at position 1, and so forth. A character‘s position is referred to as its offset from the start of the file. Therefore, the first character has a 0 offset, the second character has an offset of 1, and so on, for each character in the file. The seek() functions require two arguments: the offset, as a long integer, in the file and where the offset is to be calculated from, determined by the mode.
  • 148. Cont… The three alternatives for the mode are ios::beg, ios::cur, and ios::end, which denote the beginning of the file, current position, and end of the file. Therefore, the mode ios::beg means the offset is the true offset from the start of the file. The mode ios::cur means the offset is relative to the current position in the file, and the mode ios::end means the offset is relative to the end of the file. A positive offset means move forward in the file, and a negative offset means move backward.
  • 149. Cont… To point to the end of a data file, you can use the seekg() function to position the file pointer at the last byte. This statement positions the file pointer to the last byte in the file. Fileobj.seekg(0L,ios::end); This seekg() function literally reads ―move the file pointer 0 bytes from the end of the file.‖ The file pointer now points to the end-of-file marker, but you can seekg() backwards to find other data in the file. The following program is supposed to read ―c:alph.txt‖ file backwards, printing each character as it skips back in the file.
  • 150. Example : Using seekg() and tellg() Suppose test.dat contains this text
  • 151. cont… . -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 T h e g r a d e w a s 9 2 . 5 EOF
  • 152. Opening Random-Access Files There is really no difference between sequential files and random files in C++. The difference between the files is not physical, but lies in the method that you use to access them and update them. The ostream member function write outputs a fixed number of bytes, beginning at a specific location in memory, to the specified stream. When the stream is associated with a file, function write writes the data at the location in specified by the ―put‖ file position pointer. The istream member function read inputs a fixed number of bytes from the specified stream into an area in memory beginning at the specified address.
  • 153. Cont… When the stream is associated with a file, function read inputs bytes at the location in the files specified by the ―get‖ file poison pointer. Syntax of write: fileobject.write((char*) & name ofobject, sizeof(name of object)); Writing randomly to a random access file Here is an example that shows how to write a record to a random access file. #include<fstream.h> #include<stdlib.h> struct stud_info{ int id; char name[20]; char fname[20]; float CGPA; }student;
  • 154. Cont… . int main() { clrscr(); char filename[15]; ofstream outdata; cout<<"nenter file name : "; cin>>filename; outdata.open(filename,ios::out); if(outdata.fail()) { cerr<<"nError opening "<<filename; getch(); exit(1); } cout<<"nEnter student id : "; cin>>student.id; cout<<"nEnter student name : "; cin>>student.name; cout<<"nEnter student father name : "; cin>>student.fname; cout<<"nEnter student CGPA : "; cin>>student.CGPA; //now write to the file outdata.seekp(((student.id)-1) * sizeof(student)); outdata.write((char*) &student, sizeof(student)); outdata.close(); cout<<"nData has been saved"; return 0; }
  • 155. Chapter Six Introduction to Class A class is way to bind the data and its associated functions together. It allows data functions to be hidden, if necessary from external use. A class specification has two parts. • (i) Class declaration • (ii) Class function definitions So, Classes are user-defined (programmer-defined) types. • Data (data members) • Functions (member functions or methods) In other words, they are structures + functions
  • 156. Declaration of Class A class definition begins with the keyword class. The body of the class is contained within a set of braces, { } ; (notice the semi- colon).  Within the body, the keywords private: protected : and public: specify the access level of the members of the class. • the default is private.  Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section.
  • 157. Cont… • Member access specifiers • public: • can be accessed outside the class directly. • The public stuff is the interface. • private: • Accessible only to member functions of class • Private members and methods are for internal use only. • The default access of a class is private, but it is still a good idea to use the private key word to explicitly declare private members. • Protected : Accessible only through inherited class
  • 158. Cont… This class example shows how we can encapsulate (gather) a circle information into one package (unit or class). No need for others classes to access and retrieve its value directly. The class methods are responsible for that only. They are accessible from outside the class, and they can access the member (radius) They are accessible from outside the class, and they can access the member (radius)  The data member and member functions present in private and protected mode can be accessed by the member function in public mode.
  • 159. Cont… The private and protected modes are exactly the same except that protected can be inherited but private mode cannot be inherited. Creating an object of a Class Object is instance of a class i.e variable of a class. Declaring a variable of a class type creates an object. Class objects must be defined after the class is declared. Defining a class object is called the instantiation of a class. You can have many variables of the same type (class).
  • 160. Cont… Once an object of a certain class is instantiated, a new memory location is created for it to store its data members and code. The declaration of an object is as follows:- class –Name object –Name; We can declare more than one object of a class as follows:- class –Name object –Name1, class –Name object –Name2,....; When we declare an object space is allocated to that. Objects can also be created at the time of class declaration.
  • 161. Accessing class member Through object, data member and member function present in public can be accessed. The general format is : • Object name . data member ; • Object name . member function ;  The dot operator is called the class member access operator. Member function definition Member function can be defined in two ways: (i) Inside the class (ii) Outside the class
  • 162. Cont… • Inside the class : When a member function is defined inside a class, it is considered to be inline by default. If a member function is very small then it should be defined inside the class. class student { char name [ 20 ]; int rn ; float marks ; public : void getdata ( ) { cin >> name >> m >> marks ; }
  • 163. Cont… void putdata ( ) { cout << name << rn << marks : } }; //end of class Outside the class : When a function has larger code then it should be defined outside the class declaration. The prototype of such functions, however, must be provided in the class definition. The operator ‗: :‘ known as scope resolution operator is used to associate member functions to their corresponding class. The format is : return _type class_name : : function_name
  • 164. Memory Allocation for objects The member function are created and placed in the memory space only once when they are defined in class specification. All the objects belonging to that class use the same member functions. Space for member variable is allocated separately for each object because member variable holds different value for different objects. Exercise :- 1. Write a c++ object oriented program which perform the sum of two numbers and return their sum. 2. Write a c++ object oriented program which reads two numbers and display the smallest of them.
  • 165. Array within a class The concept of array within a class is similar to that of array within structure. class class_Name { int a[20]; public: ………; ----------; }; class class_Name { int a[2][3]; public: ………; ----------; }; Exercise: 1. Write object oriented based C++ program which performs addition, subtraction and multiplication of matrix.
  • 166. Array of object We know that memory is allocated to an object when we declare the object. Array is a collection of homogeneous data items. Therefore, we can create an array in which each data item is class type such array is called array of object. Eg :-The following program reads bio-data of four students and then prints their bio-data. class Bio { char Name[20]; char Address[20]; int phonenumber;
  • 167. public: void getData(); void showData(); }; void Bio::getData(){ cout<<―Enter Name‖; cin>>Name; cout<<―Enter Address‖; cin>>Address; cout<<―Enter phone number‖; cin>>phonenumber; } void Bio::showData(){ cout<<―Name‖<<Name; cout<<―Address‖<<Address; cout<<―Phone number‖<<phonenumber; } int main(){ Bio bio [4]; for(int i=0;i<=3;i++) cout<<―Enter ‖<<i+1<<―person bio‖<endl; bio.getData(); for(int i=0;i<=3;i++) cout<<―Bio data of ‖<<i+1<<―person is‖<endl; bio.showData(); return 0; }
  • 168. Constructors A constructor is a special member function that initializes the objects of its class. It is special because its name is the same as the class name. It is invoked automatically whenever an object is created. It is called constructor because it constructs the values of data members of the class. It does not have any return type, not even void Constructors must be declared publicly. class student { int rn; int total ; public: student ( ) { rn = 0 ; total = 0 ; } } ;
  • 170. Default Constructor A constructor that accepts no parameter is called default constructor. If no such constructor is defined, then the compiler supplies a default constructor.  In that case, it is called nothing-to-do constructor. Parameterized Constructors The constructors that can take arguments are called parameterized constructors. class student { int rn, total ; public student (int x, int y) { rn = x ; total = y ; }
  • 171. Cont… When the object is created, we must supply arguments to the constructor function. This can be done in two ways: • By calling the function explicitly • By calling the function implicitly The first call is implemented as follows : • student S1 = student ( 1, 70 ) ; • The second call is implemented as follows : • student S1 ( 1, 70 ) ; The second method is used very often as it is shorter.
  • 172. Constructor with default arguments The constructor can be declared with default argument. For example : student ( int rn, int total = 0 ) ; Here the default value of total is zero. Then the statement student S1 ( 2 ) ; assigns the value 2 to rn and 0 to total. However, the statement student S2 ( 3, 75 ) ; assigns 3 to rn and 75 to total. In this case actual parameter takes the priority over default parameter. All default values should be on the right side.
  • 173. Destructor • A destructor is a member function that is automatically called when an object is destroyed. • Destructors have the same name as the class, preceded by a tilde character (~) • In the same way that a constructor is called then the object is created, the destructor is automatically called when the object is destroyed. • In the same way that a constructor sets things up when an object is created, a destructor performs shutdown procedures when an object is destroyed.
  • 174. Cont… This program demonstrates a destructor. #include <iostream.h> class Demo { public: Demo(void); // Constructor ~Demo(void); // Destructor }; Demo::Demo(void) { cout << "Welcome to the constructor!n"; } Demo::~Demo(void) { cout << "The destructor is now running.n"; } void main(void) { Demo demoObj; // Declare a Demo obje cout << "This program demonstrates an objectn"; cout << "with a constructor and destructor.n }
  • 175. Program Output Welcome to the constructor! This program demonstrates an object with a constructor and destructor. The destructor is now running.