Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

Dambi Dollo University Information Technology Dept.

Fundamentals of Programming II

Chapter one
Fundamentals of programming in C ++

Variables

A variable can simply assumed as a name given to a certain portion of the computer’s memory
space by the programmer. Or we can say a variable is a name that can be given a variety of
values. This memory space will be used to store values or the information which is stored at that
location is known as value of the variable. And these values can change during the execution of a
program. We can define variables (we name variables) anywhere in the program, but it is a must
to do so before using them. A variable can hold only one value at a time.

We could have called the variables any names we wanted to invent, as long as they were valid
identifiers. A valid identifier is a sequence of one or more letters, digits or underline symbols
(_). The length of an identifier is not limited, although for some compilers only the 32 first
characters of an identifier are significant (the rest are not limited).

Variables in C++ are given names by the programmer, in the way he/she thinks it is meaningful
and that it reflects clearly what it represents in the program. Variable names may consist of
alphabets (both upper and lower cases), the digits from 0 to 9, and the underscore (_). The
compiler distinguishes the upper and lower case characters differently. But the following
conditions must be fulfilled in naming variables.

 The first character must be a letter or underscore(They can never begin with a digit)
 Blank space is not allowed
 A variable name should not be longer than 32 characters
 It should not be a key word
 It should not have special characters (except the underscore)

Key words: are essential parts of a programming language, having a predefined meaning in the
language and we cannot use them as variable names or any other purpose other than their
predefined usage. Key words in C++ include int, break, if, else, while, switch, for, void, include,
continue, etc.

Special characters: include:

 Punctuation marks like .,;,:,?,, etc


 Arithmetic operators like +,-,*,/,%
 Others like =,(,{,[,$,’,”,# ,& etc

Note: the C ++ language is “case sensitive “, that means that an identifier written in capital letters
is not equivalent to another one with the same name but written in small letters. E.g. the variable
RESULT is not the same as the variable result or Result.

1
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

There are two types of variables based on their visibility. These are:

1. Global variables
Global variables can be referred to anywhere in the source code, within any function after
its declaration. That means, they are visible to anywhere in the source code the program.
2. Local variables
These variable types are limited the code level in which they are declared. In C++ the
scope of local variable is given by the block in which it is declared. (A block is a group of
instructions grouped together within curly brackets {} signs). If it is declared within a
function it will be a variable with function scope, if it is declared in a loop its scope will
be only the loop etc.

Declaration of variables

In order to use a variable in C++, we must first declare it specifying which data type we want it to
be. The syntax to declare a new variable is to write the specified of the desired data type (like int,
float, char …) followed by a valid variable identifier. For example:

int a ;

float my-number;

These are two valid declarations of variables. The first one declares a variable of type int with
the identifier a. The second one declares a variable of type float with the identifier my-number.
Once declared, the variables a and my-number can be used within the rest of their scope in the
program. If you are going to declare more than one variable of the same type, you can declare all
of them in a single statement by separating their identifiers with commas. For example:

int a, b, c ;

This declares three variables (a, b, c), all of them of type int, and has exactly the same as:

int a;
int b;
int c;
Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want
a variable to store a concrete value at the same moment that it is declared. In order to do that, you
can initialize the variable.

Initializing a variable is done by appending an equal sign followed by the value to which the
variable will be initialized:

Data-type identifier = initial –value;

2
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

For example, if we want to declare an int variable called a initialized with the value of 0 at the
moment in which it is declared, we could write: int a= 0;

#include<iostream.h>

#include<conio.h>

int x ; global variable which can be accessed anywhere in the program

void main ()

char x; local variable and its scope is

int y; reserving 2 byte of memory space and named y (i.e. declaration)

int b =34; initializing the variable b by 34

for (int i=3; i<=23, i ++)

float z; local variable whose scope is

----

---

----

getch ();

3
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Constants

Constants are expressions with fixed values. There are three types’ constants in C++.

These are: Literal, defined constants and symbolic (memory constant) constants.

1. Literal constants

These are values typed directly into the program when they are needed and they can be numbers,
characters or strings.

E.g. int num=35;

char char_var=’a’;

35 and ‘a’ above are literal constants. Note that character constants use single quotation marks
around. There are also string constants which use double quotation marks. When we want to use
constant strings of characters we must enclose them between double quotes (“). Literal constants
can be given to variables as in the above example. The program cannot assign value to 35 and ‘a’
and their value can’t be changed, but the variables num and char_var can be re-assigned later in
the program, since they are variables.

2. Defined constants
Although the construction is not popular in C ++, we should note that we can also specify
constants using the preprocessor directive #define. Example #define Pi 3.14

Appending the above code at the beginning of your program specifies that the identifier Pi will
be replaced by the text 3.14 throughout the program.

Example://defined constants: calculate circumference of circle

#include<iostream.h>

#include<conio.h>

#define PI 3.14

void main ()

{ double r = 5.0; // radius

double circm;

circm = 2*PI*r;

Cout<<” The circumference is: “<<circum;

getch();

4
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

3. Symbolic (memory) constants

These are similar to variables in that they are represented by a name and they are data storage
locations. Unlike variables however, the data on constants cannot be changed throughout the
program and they must be initialized when defined. These constants are defined using the key
word const preceding the data type.

Example

const float PI=3.14;

The key word const ensures that the program will not change the given value, or an error
message will be displayed. It is a common style among programmers to name such constants all
in upper cases, like PI above.

The following example demonstrates how the three types of constants can be used to give a
constant value for the variable PI.

//demonstration of the three types of constant declarations


#include<iostream.h>
#define PI 3.14
void main ()
{
const double pi = 3.14;
cout<<”Defined constant PI = “<<PI<<endl;
cout<<”Memory constant pi = “<<pi<<endl;
cout<<”Literal constant Pi = “<<3.14<<endl;
}
Input and output statements

It is obvious that most programs interact with the program users, i.e. the programs take input data
through input devices like the key-board, and display output like processed values, messages, etc
via output devices like the computer’s screen.

In C++, the standard input device is the key-board and the standard output device is the console or
screen. In the iostream.h C++ library, included as a header file, cin is the standard input stream
taking input from the key-board and cout is the standard output stream giving output to the
screen.

5
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Input with cin>>


For input from the key-board, cin is used with the extraction operator >> (a pair of grater than
signs). Extraction operator >> extracts the value of the variable from the input stream cin, which
took the input from the key-board.

E.g. int my_var;

cin>>my_var;

Here in above, the variable my_var is defined as an integer and then waits for an input from the
keyboard in order to store it in this integer variable.

The user of the program should supply correct form of data when it is taken as input from the
keyboard. If the input value is different from the variable’s data type or capacity, then there is a
possibility of erroneous result and erratic behavior of the program. More than one data input can
taken from cin in the following way.

cin>>x>>y>>z;
It is equivalent to
cin>>x;
cin>>y;
cin>>z;
Output with cout<<
For output to the screen, cout is used with the insertion operator << (a pair of less than signs).
Insertion operator << insets the variables, strings or expressions following the insertion operator
to the output stream cout, which then displays it to the computer’s screen.

E.g.
cout<<”Hello There “; //prints Hello There on the screen
cout<<x; // prints the content of variable x on the screen
cout<<”x”; // prints the character x on the screen
cout<<100; // prints number 100 on the screen
cout<< x + y; // prints the result of the sum of the content of variables x and y
The insertion operator << may be used more than once on one statement, even for different types
of output data.
E.g.
X=2;
cout<<”The value on the variable X is “<< X <<”, that’s all”;
The above statement prints on the screen:
The value on the variable X is 2, that’s all

6
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Control structure
Depending upon requirement of the problem, it is often required to alter the normal sequence of
execution in the program. This means that we may desire to selectively or repetitively execute a
program statement.

A number of C++ structure known as control structures are available for the flow of processing.

1. Conditional statement
They are mainly used for making decisions. Depending on the value of an expression decision
can be made. The following are conditional statements in C ++.

i. If statement
The if statement is the simplest of the decision statement.

Syntax: if (expression)
Body of if;
Expression is evaluated first if this is true then body of if is executed. If the expression is false
then the body of if is skipped and execution continues with the next statement.
If body of if is simple statement, then

If (expression)
Statement;
Or
If (expression)
{
Statement;
}

If body of if is compound or block, then


If (expression)
{
Statement1;
Statement2;
Statement3;
.
.
.
Statement n;
}
If the expression is true then all the statements within the block are executed. In case expression
is false all the statements within the block are skipped.

7
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The following diagram shows the execution of if statement.

Expressi False
on

True
Body of
if

ii. If else statement

Syntax: if (expression)
Body of if;

else

Body of else;

Body of if and body of else may be simple and may be compound. If body of if and body of else
is simple then,

If (expression)

Statement;

else

Statement;

If body of if and body of else is compound, then

If (expression)
{
Statement 1;
Statement 2;
….
Statement n;
}
else
{
Statement 1;
Statement 2;

Statement n;
}

8
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

If else structure execute like follow. Expression is evaluated first if that is true then the if body is
executed otherwise else body is executed. Following diagram shows its execution.

Expressi False
on

True Body of else

Body of
if

iii. Nested if-else statement

In if statement of if-else statement in place of body we can also use again if or if-else. This
concept is known as nested structure.

Syntax:

If (expression 1)
9
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

{ If (expression 2)

Statement 1;

Statement n;

Else

Statement 1;


statement 2;

Else

{ If (expression 3)

Statement1;

Statement n;

Else

Statement 1;

Statement n;

iv. Switch statement


10
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The switch statement is an alternate of nested if-else structure. This is a multi way decision
maker that tests whether an expression matches one of the numbers of values.

Syntax:

Switch (expression)

Case value 1:

Statements;

Break;

Case value 2:

Statements;

Break;

Case value n:

Statements;

Break;

Default:

Statements

 First expression (called the switch tag) is evaluated, and the outcome is compared to each
of the case labels, in the order they appear, until a match is found. The statements
following the matching case are then executed. Note the plural: each case may be
followed by zero or more statements (not just one statement). Execution continues until
either a break statement is encountered or all intervening statements until the end of the
switch statement are executed. The final default case is optional and is exercised if none
of the earlier cases provide a match.
 Note: the control expression must be integer or character type. That means value 1,
value2,.., value n are also integer or character data type.

2. Loop statement or Repetitive statement

11
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Loop causes a section of our program to be repeated a certain number of times. The repetition
continues up to when a condition is true.

There are three kinds of loop in C++. These are for loop, while loop and do…while loop.

i. for loop

Syntax: for (<expr1>; <expr2>; <expr3>)

Statement(s);

Statement (s) is/are executed repeatedly UNTIL the value of <expr2> is 0 (false).

BEFORE the first iteration, <expr1> is evaluated. This is usually used to initialize variables for
the loop.

AFTER each iteration of the loop, <expr3> is evaluated. This is usually used to increment a loop
counter.

In C++, <expr1> can be an expression or a declaration. The scope of any declared identifier
extends to the end of the control statement only.

All the expressions are optional. If <expr2> is left out, it is assumed to be 1 (true).

Example; //Calculates the sum of numbers 1 through n

#include<iostream.h>
#include<conio.h>
void main ( )
{
int sum=0, n ;
cout<<”Enter the maximum number :”<< endl;
cin>>n;
for(int i=0;i<=n; i++)
sum+=i;
cout<<”The sum of numbers from 1 to “<<n<<” is =:”<<sum;
}

ii. while loop

12
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Repeats execution

Syntax: while (<expression>)

Statement(s);

Statement(s) is/are executed repeatedly as long as the value of <expression> remains non-zero.

The test takes place before each execution of the statement/s.

Example: // the while logic for summing numbers from 1 through n

#include<iostream.h>
#include<conio.h>
void main ( )
{
int sum=0, n , i=1;

cout<<”Enter the maximum number :”<< endl;

cin>>n;

while(i<=n)

sum+=i++;

cout<<”The sum of numbers from 1 to “<<n<<” is =:”<<sum;

iii. Do ... while loop

Syntax:

do

Statement(s);

} while (<expression>);

Statement(s) is/are executed repeatedly as long as the value of <expression> remains non-zero
(true).

The test takes place after each execution of the statement/s.


13
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Example : // the do… while logic for summing numbers from 1 through n

#include<iostream.h>
#include<conio.h>
void main ( )
{
int sum=0, n , i=1 ;

cout<<”Enter the maximum number :”<< endl;

cin>>n;

do

sum+=i;

i++;

} while (i<=n);

cout<<”The sum of numbers from 1 to “<<n<<” is =:”<<sum;

3. Jump statements

i. Break statement

Passes control

Syntax: break;

The break statement causes control to pass to the statement following the innermost
enclosing while, do, for, or switch statement. This statement causes exist from a loop or
decision block. It takes the control from the inner block to the outer (out of the following
closing brace). In switch statement it is used to exit from the switch statement. A break
statement only applies to the loop or switch immediately enclosing it. It is an error to use the
break statement outside the loop or a switch.

Example: /* this program converts characters from small case to upper case if they are
written in small cases. The loop body will be prematurely terminated by the break statement
if ‘N’ is pressed. */
14
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

#include<iostream.h>

#include<conio.h>

#include<ctype.h>

void main()

char ch;

for(int i=1;i<=26;i++)

cout<<"Enter the character:";

cin>>ch;

char up=toupper(ch);

cout<<"Upper case "<<up;

cout<<"\n continue [Y/N]";

cin>>ch;

if(ch=='N')

break;

cout<<"Thanks";

getch();

ii. Continue statement

Passes control

Syntax: continue;
15
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Causes control to pass to the end of the innermost enclosing while, do, or for statement, at
which point the loop continuation condition is re-evaluated.

The continue statement terminates the current iteration of a loop and instead jumps to the
next iteration. It applies, just like the break statement, to the loop immediately enclosing the
continue statement. In while and do loops, the next iteration commences from the loop
condition. In a for loop, the next iteration commences from the loop’s third expression.

Example: // the following program displays even natural numbers below 100

#include<iostream.h>

#include<iomanip.h>// for setw ( ) built in function

#include<conio.h>

void main()

for(int i=0;i<=100;i++)

if(i%2!=0)

continue;

else

cout<<setw(4)<<i<<" ";

getch();

iii. goto statement

Transfers control

Syntax: goto <identifier>;

16
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Control is unconditionally transferred to the location of a local label specified by


<identifier>.

Example:

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

cout<<”Please enter your password: “;

cin>>password;

if(Verify(password)) // check password for correctness

goto out; // drop out of the loop

cout<<”Incorrect! \n”;

out:

// etc ….

iv. The return statement

The return statement enables a function to return a value to its caller.

Syntax: return expression;

where expression denotes the value returned by the function. The type of this value should match
the return type of the function. For a function whose return type is void, expression should be
empty:

return;

(This is more discussed on functions).

Chapter Two
Array and String Manipulation
Introduction
An array consists of a set of objects (called elements), all of which are of the same type
and are arranged contiguously in memory. In general, only the array itself has a symbolic
17
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

name, not its element. Each element is identified by an index which denotes the position
of the element in the array. The number of elements in array is called its dimension. The
dimension of an array is fixed and predetermined; it cannot be changed during program
execution.
Arrays are suitable for representing composite data which consist of many similar,
individual items. Examples include: a list of names, a table of world cities and their
current temperatures, or the monthly transactions for a bank account.
Defining Array
Like any other variable, array must be defined before it can be used to store data. The array
definition comprises the variable type (which could be a char, an int, a float, etc), the name of
array and size in square brackets.
Syntax
Data_type ArrayName [size];
E.g. int age [12];
float grade [100];
double angle [360];
The items in an array are called elements. The elements in an array should have same data type.
Only their values vary.
E.g. int num [10]; (assuming this array has the elements 20, 30, 70… 21, it looks the
following in the computer’s memory).
The first element in an array has an index value of 0, the second 1, and so on. If an array has 10
elements, then the first element has index value of 0 and the 10th element has an index value of 9.
20 num[0]
30 num[1]
70 num[2]
64 num[3]
29 num[4]
37 num[5]
16 num[6]
19 num[7]
26 num[8]
21 num[9]
Memory

Accessing Array Elements


To do some activities with the elements of the array, you have to access it first. Accessing the
array elements consists of name of the array, square brackets, and the array index inside the
square brackets.
18
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

E.g.
num [3] – access the fourth array element
num [0] – access the first element
num [9] – access the last array element
Attempting to access a nonexistent array element (e.g. num [-1] or num [10]) leads to a serious
runtime error (called ‘index out of bounds’ error).
Example 1
The following program stores 10 natural numbers in one array and displays them (with
enough space between the numbers when displayed).
#include<iostream>

#include<iomanip>

using namespace std;

int main ( )

int n [3];

for (int i=0; i<3; i++)

cout<<"Enter natural numbers "<<i+1<<" ";

cin>> n [ i ];

cout <<"Now displaying ";

for(int j=0; j<3; j++)

cout<<setw (2) << n[ j ];

Exercise:

Write a program in the above array that puts the elements of the array that are entered by the user in a
reverse order.

19
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Initializing Arrays
It is possible to initialize the elements of the array during defining arrays. When initializing
arrays there is no need to write the array size in the square brackets.
Syntax
Data_type ArrayName [ ] = {initializes};
e.g. int nums [3] = {5, 10, 15};
This initializes the three elements of nums to 5, 10, and 15 respectively. When the numbers of
values in the initializer is less than the number of elements, the remaining elements are initialized
to zero:
int nums [3] = {5, 10}; // nums [2] initializes to 0
When a complete initializer is used, the array dimension becomes redundant, because the number
of elements is implicit in the initializer. The first definition of nums can therefore be equivalently
written as:
int nums [ ] = {5, 10, 15}; // No dimension needed
The following program displays the sum of the initialized array elements.
Example 1
#include<iostream>
using namespace std;
int billy [ ] = {10, 20, 30, 40, 50};
int n, result = 0;
int main ( )
{
for (n=0; n<5; n ++)
{
result += billy [n];
}
cout<<result;
return 0;
}
Example 2
The following program finds average of numbers that are stored in array
#include<iostream>
using namespace std;
int main ( )
{
int num [ 3] = {10, 20,30};
float sum=0, av;
for (int i=0; i<3; i ++)
sum += num [ i ];
av = sum/3;
cout<<"The average is \t"<<av;
}

20
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Operations on the Array


Each member of an array is a pseudo-variable and can be processed as such. This means that you
can add the values of two members of the array (Number [2] + Number [0]), you can subtract the
value of one of the members from another member (member [1] – Number [4]). In the same way,
you can perform multiplication, division, or remainder operations on members of an array.
One of the regular operations performed on an array consists of adding the values of the
members to produce a sum. Here is an example:
#include<iostream>
using namespace std;
int main ( )
{
// we know that we need a constant number of elements
const int max = 3;
int number [max];
// we will calculate their sum
int sum = 0;
cout<<"Please type 3 integers.\n";
for (int i = 0; i < max; i ++)
{
cout<<"Number "<< i+1<<":";
cin>>number[i];
sum += number [i];
}
cout<<"\n The sum of these numbers is "<<sum <<"\n";
return 0;
}
This would produce:

Please type 3 integers.


Number1: 20
Number2: 30
Number3: 40

The sum of these numbers is 90

Another type of operation regularly performed on an array consists of looking for a value held by
one of its members (i.e. searching). For example, you can try to know if one of the members
holds a particular value you are looking for. Here is an example:
#include<iostream>
using namespace std;
int main ( )

21
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

{
// declare the members of the array
int numbers [ ] = { 8, 25, 36, 44, 52, 60, 75, 89};
int find;
int i, m=8;
cout<<"Enter a number to search:";
cin>>find;
for (i=0;( i < m) && (numbers[ i ] != find); ++ i)
continue;
//Find whether the number typed is a member of the array
if(i==m)
cout<<find<<"is not in the list."<<endl;
else
cout<<find<<"is the"<<i+1<<"th element in the list."<<endl;
return 0;
}
This would produce:

Enter a number to search: 44


44 is the 4th element in the list.

One of the most regular operations preformed consist of comparing value of different members
to get the lowest value of the members. Here is an example:

22
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

//Example of finding the minimum member of any array


#include<iostream>
using namespace std;
int main ( )
{

//The member of the array


int numbers [ ]={8,25,36,44,52,60,75,89};
int minimum = numbers [0];
int a=8;
//compare the members
for (int i=1;i<a;++i){
if(numbers [ i ]<minimum)
minimum = numbers [ i ];
}
//Announce the result
cout<<"The lowest member value of array is"<<minimum<<"." <<endl;
return 0;
}This would produce:
The lowest member value of the array is 8.

You can use the same approach to get the maximum value of the member of any array.
Here is an example
//Example of finding the maximum member of any array
#include<iostream>
using namespace std;
int main ( )
{
//The member of the array
int numbers [ ]={8,25,36,44,52,60,75,89};
int maximum = numbers [ 0 ];
int a=8;
//compare the members
for (int i=1;i<a; i++)
{
if (numbers [ i ] > maximum)

23
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

maximum = numbers [i ] ;
}
//Announce the result
cout<<"The highest member value of the array is"<<maximum<<"."<<endl;
return 0;
}

Multi Dimensional Arrays


An array may have more than one dimension (i.e. two, three, or higher). The organization of the
array in memory is still the same (a contiguous sequence of elements), but the programmer’s
perceived organization of the elements is different. For example, suppose we wish to represent
the average seasonal temperature for three major Ethiopia cities.

Spring Summer Autumn Winter


Addis Abeba 26 34 22 17
Adama 24 32 19 13
Awasa 28 38 25 20

This may be represented by a two dimensional array of integers:

int seasonTemp [3] [4];

The organization of this array in memory is as 12 consecutive integer elements. The


programmer, however, can imagine it as three rows of four integer entries each (see the
following).

Organization of seasonTemp in memory

…… 26 34 22 17 24 32 19 13 28 38 25 20 ……

First row Second row Third row

Initializing Multidimensional Arrays


Like a one dimensional arrays, it is also possible to initialize multidimensional arrays.
Syntax: Data_type ArrayName [value 1] [value 2] . . . [value n]
= {{x, y, z}, {a, b, c}, {d, e, f}. . . {l, j, k}};
e.g.
int num [ ] [3] = { {1, 2, 3}, {4, 5, 6} };

24
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

As before, elements are accessed by indexing the array. A separate index is needed for each
dimension. For example, Addis Abeba‘s average summer temperature (first row, second column)
is given by seasonTemp [0] [1]. The array may be initialized using a nested initializer as :

int seasonTemp [3] [4] = {


{26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};

Because this is mapped to a one dimensional array of 12 elements in memory, it is equivalent to:

int seasonTemp [3] [4] = {26, 34, 22, 17, 24, 32, 19, 13, 28, 38, 25, 20};
The nested initializer is preferred because as well as being more informative, it is more versatile.
For example, it makes it possible to initialize only the first element of each row and have the rest
default to zero:

int seasonTemp [3] [4] = {{26}, {24}, {28}};

We can also omit the first dimension (but not subsequent dimensions) and let it be derived from
the initializer as:

int seasonTemp [ ] [4] = { {26, 34, 22, 17},


{24, 32, 19, 13},
{28, 38, 25, 20}
};
Example 1: The following program finds the highest temperature out of the three cities and
the four seasons.
#include<iostream>
using namespace std;
int main ( )
{
const int rows = 3;
const int columns = 4;
int seasonTemp [rows ] [columns ] = { {26, 34, 22, 17},
{24, 32, 19, 13},
{28, 38, 25, 20}
};
int highest = 0;
for (int i=0;i<rows; ++i)
{
for (int j=0; j<columns; ++j)
if (seasonTemp [ i ] [ j ] > highest)
{
highest = seasonTemp[ i ] [ j ] ;
}
//Announce the result
cout<<"The highest temperature is ="<<highest<<"."<<endl;
25
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

return 0;
}
}

Example 2: The following program stores sales of commodities in 5 stations for 3 months.
You can also display what you stored for checkup purpose.
#include<iostream>
#include<iomanip>
using namespace std;
int main ( )
{
float sales [5] [3];
for (int s = 0; s < 5; s++)
for (int m=0; m<3; m++)
{
cout<<"Enter sales for station "<<s+1;
cout<<"\month "<<m+1<<" " ;
cin>>sales[s] [m];
}

for(int j = 0; j <= 4; j++)


for(int i = 0; i <= 2; i++)
{
cout<<"sales "<< j+1<<" month"<<i+1;
cout<<setw(4)<<sales[ j ] [ i ];
if(i== 2)
cout<<"\n";
}
}

26
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Strings

Since you have some understanding about arrays, it is very simple to examine strings.
Strings are arrays of characters. In the arrays of characters, the null character is always added to
the end of the characters. The null character is ‘\0’; with ASCII value of 0. In C++ there is no
means to check the array bounds. Therefore, be careful when putting data into arrays not to
exceed its maximum bounds. When we display strings, characters inside an array are displayed
until a null (‘\0’) character is encountered.
Examples
The following C++ program reads your name from keyboard and displays it.
#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
char name [ 20 ];
cout<<”Enter your name \t”;
cin>>setw(20)>>name;
cout<<name;
getch( );
}

If you need to read a string with blank spaces in between, the extraction operator >> considers
the space to be a terminating character of a string. Thus, characters after a space will be ignored.
To avoid this problem you can use the function cin. get ( ). This helps to read strings along with
blank spaces.
E.g.
The following program reads your name and father’s name and displays it.
#include<iostream.h>
#include<conio.h>
void main( )
{
char str [ 20 ];
cout<<”Enter your full name \t”;
cin.get (str, 20);
cout<<”Your name and fathers name is \n”<< str;
getch( );
}

27
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Reading multiple lines of strings


Some time it is necessary to read multiple lines of string from the keyboard. The default
terminating character is the new line (‘\n’) character. But it is possible to override the default
character with some other characters so that we can read multiple lines of text until that
terminating character is typed.
This can be achieved by adding the terminating character in the cin.get ( ) function as an
argument.
Example
The following program reads multiple lines of text and stores it in array.
#include<iostream.h>
#include<conio.h>
void main( )
{
char str [ 100 ];
cout<<”Enter a string and $ when finish \n”;
cin.get (str, 100, ‘$’);
cout<<”You entered \n”<< str;
getch( );
}

Arrays of strings
Like arrays of arrays, it is also possible to have arrays of strings. This is important to store arrays
of names of people, or other strings for some other purpose. To define such constructions, we
should write the size of the array and the maximum size of each string.
Example
The following program stores list of people in an array and display it.
#include<iostream.h>
#include<conio.h>
void main( )
{
char name [5] [10] = {“Kebede”, “Ayele”, “Tufa”, “Almaz”, “Kasa”};
for (int i=0; i<5;i++)
cout<<name[ i ]<<’\n’;
getch( );
}

String Manipulation

strlen ( ): This C++ library function finds the length of a string, i.e. how many characters are in
the string, excluding the null (‘\0’) character. This function takes the name of the string variable
or constant as an input (argument) and returns an integer value. We must include the <string.h>
header file to use this function.
Example
The following program takes your name and tells the length of your name.
#include<iostream.h>
#include<string.h>
28
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

#include<conio.h>
void main( )
{
char name [25];
cout<<”Enter your name: “;
cin>>name;
cout<<”Your name is “<<strlen (name) <<” characters long.”;
getch( );
}

strcpy( ): It is a common process to copy one string into another. You can have many ways to
copy a string. Copying a string character by character is one option to do so. It needs to access
characters of a string character by character. Using the built in function strcpy ( ) to copy a string
is another easier method.
strcpy ( ) takes two arguments and copies the second variable ( the right hand side or the source
string) to the first (left hand side or the destination string) variable.

Example
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main( )
{
const int SIZE = 100;
char str1 [SIZE];
char str2 [SIZE];
cout<<”Enter a string \n”;
cin.get(str1, SIZE);
strcpy(str2, str1);
cout<<”Copy of your string is \n”<<str2;
getch( );

strncpy( ):
It is used to copy at most maxlen characters of source string to destination string.

Declaration:
strncpy (destination string, source string, maxlen);

Remarks:
strncpy copies up to maxlen characters from source into destination, truncating or null-padding
destination.
Example
char Str1 [5];
Str2 = “Honey”;
cout<<strcpy (Str1,Str2);// will be Honey
cout<<strncpy(Str1,Str2,3); // will be Hon
29
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

strcat ( ): This function two arguments and concatenates (appends) the second variable to the
first one.
Example
#include<iostream.h>
#include<string.h>
#include<conio.h>
void main( )
{
char ch1 [50], ch2 [100] = “I am proud “;
cout<<ch2<<endl;
cout<<”Enter a string to concatenate: \n”;
cin.get (ch1, 50);
strcat (ch2, ch1);
cout<<”The concatenated string is: \n”<<ch2;
getch( );

strncat()
It appends a portion of one string to another. It takes three arguments.

Declaration:
strncat ( destination string , source string , maxlen);

Remarks:
strncat copies the first maxlen characters of source and appends to the end of destination string.

Example
Str1 = “Hi”;
Str2 = “Honey”;
cout<<strcat (Str1,Str2);// will be HiHoney
cout<<strncat(Str1,Str2,3); // will be HiHon

strcmp ( ): This function takes two string arguments and compares them. The result of the
comparison is an integer value of either negative, positive, or zero based on the following facts.
Example
strcmp (str1, str2);
 0 if str1 is the same as str2
 +ve (>0) if str2 comes first alphabetically
 -ve (<0) if str1 comes first alphabetically

strncmp(str1, str2, n): It is used for comparing the first n characters.


Example:
The following program takes two words from a user and compares their alphabetical precedence.
#include<iostream.h>
#include<string.h>
#include<conio.h>

30
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

void main( )
{
const int p = 15;
char ch1 [p], ch2 [p];
cout<<”Enter first string:”;
cin>>ch1;
cout<<”Enter second string: “;
cin>>ch2;
if (strcmp (ch1, ch2) == 0)
cout<<”The two words are the same”;
else if (strcmp (ch1, ch2) > 0)
cout<<ch2<<” comes first alphabetically. “;
else if (strcmp (ch1, ch2) < 0)
cout<<ch1<<” comes first alphabetically.”;
getch( );
}

strrev( ): This function reverse a string.

Example
The following C++ program reads your name from keyboard and display it in reverse order.
#include<iostream.h>
#include<string.h>
#include<conio.h>
#include<iomanip.h>
void main( )
{
char name[20 ];
cout<<”Enter your name \t”;
cin>>setw(20)>>name;
cout<<strrev (name);

/* or
for(int i = (strlen(name) – 1); i >= 0; i--)
cout<<name [i];
*/
getch( );
}

31
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Chapter Three
Functions
Function is group of program statements that can act on data and return a value. Every C++
program has at least one function, main ( ). When your program starts, main ( ) is called
automatically. main ( ) might call other functions, some of which might call still others. The
reason why we use functions is to aid modularization of a program. A function reduces program
size. Any fragments of code that are needed frequently in a program are best candidates to be
written as a function. A function provides a convenient.
Any function has its own name, and when that name is encountered, the execution of the
program branches to the body of that function. When the function returns, execution resumes on
the next line of the calling function. The function body is placed in one place in memory. But it
could be invoked in several places in the program.
Function Declaration / Prototype Declaration
As you can’t use variables before declarations (telling the compiler what the variable is), you
can’t use function before * telling the compiler what this function is. The common approach to
declare functions is at the beginning of the program. The function declaration (function
prototype) tells the compiler that later on the program a function introduced in the declaration is
going to be used.
Example
void getnumber ( ); this is a function declaration. Void shows that the function doesn’t have a
return type. Function declaration is terminated with semicolon. If the function has arguments,
then they should be indicated in the declaration.
Function Definition
A function definition consists of two parts: interface and body. The interface of a function (also
called its prototype) specifies how it may be used. It consists of three entities.

 The function name. This is simply a unique identifier.


 The function parameters (also called its signature). This is a set of zero or more typed
identifiers used for passing values to and from the function.
 The function return type. This specifies the type of value the function returns.
A function which returns nothing should have the return type void. The body of a function
contains the computational steps (statements) that comprise the function.

32
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Example
void getnumber ( ) function header (interface)
{
int x;
cout<<”Enter number \n”; function body
cin>>number;
cout<<”The number you entered is :”<< number;
}
The function body is placed in one place in memory. But it could be invoked in several places in
the program.
Calling functions
Calling functions is invoking it to execute. The function call involves the function name,
followed by parentheses. The function call is similar to its declaration except that the return type
is not mentioned. The call is terminated by semi colon. Executing the call statement causes the
function to execute, i.e. control is transferred to the function, and the statements in the function
definition are executed and then control returns to the statement following the function call.
The following program demonstrates what we have discussed so far.
#include<iostream.h>
#include<conio.h>
void add ( );// Function declaration
void sub ( ); // Function declaration
void main ( )
{
char ch;
cout<<”What do you want? A: add, S: subtract\n”;
cin>>ch;
switch (ch)
{
case ‘A’: // A for addition
add ( ); // Function call
break;
case ‘S’: // S for subtraction
sub ( ); // Function call
break;
}
}
void add ( )
{
int a, b, c;
cout <<” Enter two numbers\n”;
cin >>a>>b;
c = a + b;
cout << “The sum is “<<c;
}
33
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

void sub ( )
{
int a, b, c;
cout<<” Enter two numbers \n”;
cin>>a>>b;
c = a – b;
cout<<”The difference is “<<c ;
}

A simple function
The example below shows the definition of a simple function which raises an integer to the
power of another, positive integer.

int Power (int base, unsigned int exponent)

{
int result = 1;
for (int i = 0;i < exponent ; + + i)
result *= base;
return result;
}

The function interface starts with the return type of the function (int in this case). The function
name appears next followed by its parameter list. Power has two parameters (base and exponent)
which are of type int and unsigned int, respectively. Note that the syntax for parameters is similar
to the syntax for defining variables: type identifier followed by the parameter name. However, it
is not possible to follow a type identifier with multiple commas separated parameters like:

int Power (int base , exponent) // Wrong !

the for loop raises base to the power of exponent and stores the outcome in result. Finally, the
function returns result as the return value of the function. Below, example 2 illustrates how this
function is called. The effect of this call is that first the argument values 2 and 8 are respectively,
assigned to the parameters base and exponent, and then the function body is evaluated.

Example 2:

#include<iostream.h>
void main
{ cout <<”2 ^ 8 = “<<Power (2, 8) <<endl;
}

When run, this program will produce the following output:


2^8 = 256
In general, a function should be declared before it is used.
34
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Example 3:
#include<iostream.h>
int Power (int base, unsigned int exponent); // Function declaration
void main
{
cout << “2^8 = “<<Power (2, 8) <<endl;
}
int Power (int base, unsigned int exponent)
{
int result = 1;
for (int i = 0; i < exponent; + + i)
result *= base;
return result;
}

Parameters and Arguments

C++ supports two styles of parameters: value and reference. A value parameter receives a copy
of the value of the argument passed to it. As a result, if the function makes any changes to the
parameter, this will not affect the argument. For example, in the following simple program:

#include<iostream.h>
#include<conio.h>
void Foo (int num);
int main ()
{int x =10;
Foo (x);
cout<<” x = “<<x<<’\n’;
getch( );
return 0;
}
void Foo (int num)
{ num = 0;
cout<<”Num “<<num<<”\n”;
}
The single parameter of Foo is a value parameter. As far as this function is concerned, num
behaves just like a local variable inside the function. When the function is called and x passed to
it, num receives a copy of the value of x. As a result, although num is set to 0 by the function, this
does not affect x. the program produces the following output.
Num = 0
x = 10
35
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

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. Within the context of function calls, the two styles of passing arguments are,
respectively, called pass-by-value and pass-by-reference. It is perfectly valid for a function to
use pass-by-value for some of its parameters and pass-by-reference for others. The former is
used much more often in practice.
Example
We can rewrite the above example so that the value x is passed by reference
#include<iostream.h>
#include<conio.h>
void Foo (int &num);
int main ()
{int x =10;
Foo (x);
cout<<” x= “<<x<<’\n’;
getch( );
return 0;
}
void Foo (int &num)
{ num = 0;
cout<<”Num “<<num<<”\n”;
}
The output is:
Num = 0
x=0
Another example
#include<iostream.h>
#include<conio.h>
void getdata (int &dividend, int &divisor);
void divide (int dividend, int divisor, int &quotient, int &reminder);
void print (int quotient, int reminder);
void main ( )
{
int a, b, c, d;
getdata (a, b);
divide (a, b, c, d);
print (c, d);
getch ( );
}

36
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

void getdata (int &dividend, int &divisor)


{
cout<<”Enter two numbers:”;
cin>>dividend>>divisor;
}
voids divide (int dividend, int divisor, int &quotient, int &remainder)
{
quotient = dividend / divisor;
remainder = dividend % divisor;
}
void print (int quot, int remd)
{
cout<<”Quotient is = “<<quot<<endl;
cout<<”Remainder is = “<<remd<<endl;
}

Scope operator
Because a local scope overrides the global scope, having a local variable with the same name as
a global variable makes the latter inaccessible to the local scope. For example, in

int x; // global variable


void main ( )
{
int x; // local variable
}
The global x is inaccessible inside main, because it is overridden by the local x parameter. This
problem is overcome using the unary scope operator :: which takes a global entity as argument.

#include<iostream.h>
int x = 12;
void main ( )
{
int x = 5;
if (x >= ::x)
cout<<”The local x is grater and its value is = “<<x<<endl;
}
else if (x = = ::x)
cout<<”Both are equal, the local x = “<<x<<” the global x is =”<<::x<<endl;
else
cout<<”The global x is greater and its value is = “<<::x<<endl;
}

Default Argument
37
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Default argument is a programming convenience which removes the burden of having to specify
argument values for all of a function’s parameters. For example, consider a function for reporting
errors:

void Error (char message, int severity = 0);

Here, severity has a default argument of 0; both the following calls are therefore valid:

Error (‘x’, 4); // severity set to 4


Error (‘R’); // severity set to 0

As the first call illustrates, a default argument may be overridden by explicitly specifying an
argument. Default arguments are suitable for situations where certain (or all) function parameters
frequently take the same values. In Error, for example, severity 0 errors are more common than
others and therefore a good candidate for default argument. A less appropriate use of default
argument would be:

int Power (int base, unsigned int exponent = 1);

Because 1 (or any other value) is unlikely to be a frequently-used one in this situation.

A default argument need not necessarily be a constant. Arbitrary expressions can be used, so
long as the variables used in the expression are available to the scope of the function definition
(e.g. global variables).

The accepted convention for default arguments is to specify them in function declarations, not
function definitions. Because function declarations appear in header files, this enables the user of
a function to have control over the default arguments. Thus different default arguments can be
specified for different situations. It is, however, illegal to specify two different default arguments
for the same function in a file.
Example
#include<iostream.h>
int divide (int a, int b = 2);
void main( )
{
cout<<divide (12); // Here the default value 2 is passed as a second argument
cout<<endl;
cout<<divide (20, 4);
}
int divide (int a, int b)
{return a / b;
}

Overloaded functions

38
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Two different functions can have the same name if the prototype of their arguments is different.
That means that you can give the same name to more than one function if they have either a
different number of arguments or different types in their arguments.

Example
#include<iostream.h>
int divide (int a, int b = 2);
int divide (int z, int r, int y);
float divide (float a, float b);
int main ( )
{
int x = 20, y = 2;
float n = 5.0, m = 2.0;
cout<<divide (x, y);
cout<<divide (n, m);
cout<<endl;
cout<<divide (x, y, x);
cout<<endl;
return 0;
}
int divide (int a, int b)
{
return a / b;
}
int divide (int a, int b, int c)
{
int w = a / b;
return w / c;
}
float divide (float x, float y)
{
return x / y;
}
In this case we have defined two functions with the same name, but one of them accept two
arguments of type int and the other accepts them of type float the compiler knows which one to
call in each case by examining the type when the function is called. If it is called with two ints as
an argument it calls to the function that has two int arguments in the prototype if is called with
two floats it will call to the one which has two floats its prototype.

For simplicity I have included the same code with both functions, but this is not compulsory.
You can make two functions with the same name but with completely different behavior.

39
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Note: Return type of a function has no effect in overloading. That means, if the prototype of two
functions is differ by return type only, we can’t say that they are overloaded.

Recursion
A function which calls itself is said to be recursive. Recursion is a general programming
technique applicable to problems which can be defined in terms of themselves. Take the factorial
problem, for instance, which is defined as:
 Factorial of 0 is 1.
 Factorial of a positive number n is n times the factorial of n – 1.
The second line clearly indicates that factorial is defined in terms of itself and hence can be
expressed as a recursive function:

Int Factorial (unsigned int n)


{
return n = 0? 1: Factorial (n—1);
}
For n set to 3, the table below provides a trace of the calls to Factorial. The stack frames for
these calls appear sequentially on the run time stack, one after the other.

Call n n==0 n * Factorial(n – 1 ) Returns


First 3 0 3 * Factorial(2 ) 6
Second 2 0 2 * Factorial(1 ) 2
Third 1 0 1 * Factorial(0 ) 1
Fourth 0 1 1

A recursive function must have at least one termination condition which can be satisfied.
Otherwise, the function will call itself indefinitely until the run time stack overflows. The
Factorial function, for example, has a termination condition n = = 0 which, when satisfied,
causes the recursive calls to fold back. (Note that for a negative n this condition will never be
satisfied and Factorial will fail).

As a general rule, all recursive functions can be rewritten using iteration. In situations where the
number of stack frames involved may be quite large, the iterative version preferred. In other
cases, the elegance and simplicity of the recursive version may give it the edge. For factorial, for

40
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

example, a very large argument will lead to as many stack frames. An iterative version is
therefore preferred in this case:

#include<iostream.h>
int Factorial (unsigned int n);
int main ( )
{
int n;
cout<<”Enter a positive number”;
cin>>n;
cout<<”!”<<n<<” = :”<< Factorial (n);
return 0;
}
int Factorial (unsigned int n)
{
if (n = = 0)
return 1;
else
return (n * (Factorial (n – 1)));
}

Chapter Four

User Defined Data Types

41
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Enumerated data types

An enumerated data type is a set of values represented by identifiers called enumeration


constants. This is useful for declaring a set of closely-related constants.
The general format (syntax) of enumerated data type is:-
enum enum_name {number_1, number_2, - - -, number_n};

Here, enum is a reserved word, enum_name is the name given by the programmer by the
identifier rules. Number_1, number_2, - - - , number_n are members of the enumerated data type.

Declaration
Once the enumerated data type is defined it can be declared by the following ways:-
enum enum_name variable1, variable2, - - - , variable;

For example,
enum day {Mon, Tue, Wed, Thu, Fri, Sat, Sun}; introduces seven
enumerators(members).
enum day day1, day2, day3; day1, day2 and day3 are enumerated data type variables. We
can assign any member to day1, day2 and day3 variables as like as follows:
day1 = Mon;
day2 = Sun;
day3 = Tue;
Etc….
When we declare an enumerated data type C++ compiler assign integer value 0, 1, 2, - - - etc to
members according to their order.
In above example compiler assigns:
0 to Mon
1 to Tue
2 to Wed
3 to Thu
4 to Fri
5 to Sat
6 to Sun
These integers are normally chosen automatically but they can also be specified by the
programmer i.e. the default numbering of enumerators can be overruled by explicit initialization
as follows.
enum day {Mon, Tue, Wed = 10, Thu, Fri, Sat = 20, Sun};
enum day day1, day2, day3;
in above example compiler assign
0 to Mon
1 to Tue but after this 10 is assigned to wed by the programmer. Therefore the value
assigned to other member is
10 to Wed
11 to Thu
12 to Fri
Now again 20 is assigned to sat by the programmer so the value assigned to member are
20 to Sat
42
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

21 to Sun
If suppose you write a statement as follows:
day1= Mon; and after that suppose you want to print the value of day1 like the
following:
cout<< day1;
The above statement cout<<day1; prints 0 value onto the screen, because the compiler assigned 0
to Mon, which is now in day1.
By the assignment statement day1 = Mon;
i.e. whenever we print the enumerated variable that print an integer value. That integer value is
the value of a member which is assigned to variable.
Enumerations are particularly useful for naming the cases of a switch statement.
switch (day1) {
case Mon: //...
case Tue: //...
case Wed: //...
case Thu: //...
default: //...
}
Structures
In many occasions what we want to store are not mere sequences of elements of the same data
type (as in arrays), but sets of different elements with different data types. Structures offer a way
of joining these heterogeneous elements together to form complex structures.
A structure is a group of data elements grouped together under one name. These data elements
known as members (also called fields) can have different types, some can be int, some can be
float, some can be char and so on, and different lengths.
The difference between array and structure is the element of an array has the same type while the
elements of structure can be of different type. Another difference is that each element of an array
is referred to by its position while each element of structure has a unique name.
Declaration
Structures are declared in C++ using the following syntax:
struct structure_name
{
Member_type 1 member_name1;
Member_type 2 member_name2;
Member_type 3 member_name3;
.
.
} object_names;
Where struct is a keyword, structure_name is a valid identifier name for the structure type;
object_name can be a set of valid identifiers for objects that have the type of this structure.
Within braces { } there is a list with the data members, each one is specified with a data type and
a valid identifier as its name.

43
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The first thing we have to know is that a structure creates a new type: Once a data structure is
declared, a new type with the identifier specified as structure_name is created and can be used in
the rest of the program as if it was any other type.
For example:
struct person {
float height;
int eye_color;
char name [20];
};
person mother;
person friend, spouse;

We can also declare the structure objects mother, friend and spouse at the moment we define the
structure as like as follows:
struct person {
float height;
int eye_color;
char name [20];
} mother, friend, spouse;

mother friend spouse


name name name

eye_color eye_color eye_color

height height height

This set up a structure called person and declares three variables of that type. Each of these
people will have a name, a height and an eye_color. The declaration does not set up these values:
they start off as random values and characters, whatever happens to be in the memory allocated
at the time. The data is set up as follows.

friend.name = “Diane”;
44
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

friend.eye_color = 1;
friend.height = 1.61;
mother.name = “Mary”;
mother.eye_color = 2;
mother.height = 1.44;
spouse.name = “Helen”;
spouse.eye_color = 1;
spouse.height = 1.7;
mother friend spouse
name name name
Mary Diane Helen

eye_color eye_color eye_color


2 heig 1 hei 1
ht ght height

1.44 1.61 1.7

Creating structure variables


The structure variables are created in different ways.
1. We can create structure variables at the time of declaration
Example
struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
} stud1, stud2, stud3;

2. We can create structure variables in such a way


struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
};
struct student stud1, stud2, stud3;

3. We can also create structure variables as follows


45
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

struct student
{
char name [20];
char Idd [10];
char Department [25];
int age;
};
student stud1, stud2, stud3;
Note: for each structure variables from above 57 byte of memory is reserved (i.e. 20 + 10 + 25 + 2)
Accessing structure Members
We use the dot operator (.) to access members of a structure. We use this format to read
(accept), to write (display) or assign data to members of a structure. We can assign value to the
name stud1 as follows:
Stud1.name = “Abraham”; i.e.
Structure_variable_name. member_name
Generally, structure members are treated just like other variables.
Example: Demonstration of structures
#include<iostream.h>
#include<conio.h>
struct student
{
char name [20];
char Idd [10];
int age;
};
void main ()
{
student stud1;
cout<<”Enter name of student: “;
cin >>stud1.name;
cout<<”Enter id number: “;
cin>>stud1.Idd;
cout<<”Enter age of student: “;
cin>>stud1.age;
cout<<”\n\t Name: “<<stud1.name;
cout<<”\n\t ID Number: “<<stud1.Idd;
cout<<”\n\t Age :”<< stud1.age;
getch ( );
}

Initializing structure variables


46
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

It is possible to give values to the structure members at the point of definition like the following.
#include<iostream.h>
#include<conio.h>
const int NAME = 25;
const int ID = 11;
struct student
{
char name [NAME];
char Idd [ID];
char Department [20];
int age;
};
void main ( )
{
// creating and initializing structure variables
student stud1 = {“Josef”, “09/1035”, “CSIT”, 25};
student stud2;// creating another structure variable
stud2 = stud1;
cout<<”Name: “<<stud1.name;
cout<<”\n Id :”<< stud1.Idd;
cout<<”\n Department: “<<stud1.Department;
cout<<”\n Age :”<< stud1.age;
cout<<”\n Copied data”<<endl;
cout<<” Copied Name: “<<stud2.name;
cout<<”\n Copied Id :”<< stud2.Idd;
cout<<”\n Copied Department: “<<stud2.Department;
cout<<”\n Copied Age :”<< stud2.age;
getch ( );
}

47
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Nesting structures (structure within another structure)


Structures can also be nested so that a valid element of a structure can also be on its turn another
structure.
Example
In the following program, we have the structure address nested in structure employee to access
member of a nested structure, we use the dot operator twice.
#include<iostream.h>
#include<conio.h>
#define STR 30
struct address
{
char street [STR];
int post;
float distance;
};
struct employee
{
address branch;
address home;
};
void main ( )
{
employee emp1;
cout<<”Enter branch street of the employee: “;
cin>>emp1.branch.street;
cout<<”Enter branch post address”;
cin>>emp1.branch.post;
cout<<”Enter distance of the branch”;
cin>>emp1.branch.distance;
cout<<”Employee’s branch street is “ << emp1 . branch. street <<” and it is “<<
emp1.branch.distance<<” kms away”;
getch ( );
}

48
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Union
Union, like structures, contains members whose individual data types may differ from one
another. However, the members that compose a union all share the same storage area within the
computer’s memory whereas each member within a structure is assigned its own unique storage
area. Thus, unions are used to conserve memory. A union is a class all of whose data members
are mapped to the same addresses within its object (rather than sequentially). The size of an
object of a union is, therefore, the size of its largest data member.
Union is similar to structure data type but it stores value of different types in a single location.
Union will contain much different type of values but only one is stored at a time. If a new
assignment is made, the previous value is automatically erased.
Declaration of union
-The declaration of union is the same as structure. The only difference is in place of struct key-
word. The general syntax for declaring union is:
union tag_name
{
Member_type 1 member_name1;
Member_type 2 member_name2;
Member_type 3 member_name3;
.
.
} object_name(s);
Where union is a keyword, tag_name is a valid identifier name for the union type; object_name
can be a set of valid identifiers for objects that have the type of this union.

Creating union variables


The union variables are created in different ways as like as structure variables.
1. We can create union variables at the time of declaration
Example
union data
{
int a;
float f;
} d1, d2;

2. We can create union variables in such a way


union data
{
int a;
float f;
}
union data d1,d2;

49
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

3. We can also create union variables as follows


union data
{
int a;
float f;
}
data d1,d2;

 Elements of a union are accessed in the same manner as a struct.


 For accessing the members of the union, we use the dot operator as the same as structures
variables.

For example: the following program assigns and displays union members.
#include<iostream.h>
#include<conio.h>
// declaring a union named data having two data members: i and f
union data
{
int i;// member of the union
float f;// member of the union
};
void main ( )
{
data d;// creating union variable named d
d.i = 10; // assigning a value of the variable for the first member
d.f = 20.5; // assigning a value of the variable for the second member
cout<<”First member: “<<d.i<<endl;
cout<<”Second member:”<<d.f<<endl;
/* by the above two statements the value of i is wrong because the current value is
assigned for f; whereas the value of f is correct. */
// if the order of i and f is in the following way
d.f = 20.5;
d.i = 10;
cout<<”First member: “<<d.i<<endl;
cout<<”Second member:”<<d.f<<endl;
/* here only the value of i is correct but not f because the current value is assigned to i. */

getch( );
}

Note: For the above union, 4 byte of memory is reserved (because the size of a union
takes the size of its largest data member: from this example float).

50
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Anonymous union
If we define a union without a name or tag, it is called anonymous union. The syntax for
this union type is the following.
union
{
Member_type 1 member_name1;
Member_type 2 member_name2;
Member_type 3 member_name3;
.
.
} object_name(s);
In anonymous union the members are accessed by their name directly.
Note: If the anonymous union is declared before main function, static key-word is needed before
union a follows.
static union
{
Member_type 1 member_name1;
Member_type 2 member_name2;
Member_type 3 member_name3;
.
.
} object_name(s);
For example:
#include<iostream.h>
#include<conio.h>
// declaring anonymous union before main function
static union
{
int i;
float f;
};
void main ( )
{
cout<<”Enter integer number: “;
cin>>i;
cout<<”Enter float number: “;
cin>>f;
cout<<”Integer = “<<i<<endl;
cout<<”Float = “<<f<<endl;
getch ( );
}
The above program prints the value of f is correct but the value of i is wrong, because cin>>f
statement is after statement cin>>i; that means currently the value of f is read, not i, therefore f is
valid.

51
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Chapter 5
Pointers
Every data in the computer’s memory is stored in addressed places called bytes. The amount of
byte a data takes in the computer’s memory depends on its type i.e. whether the data is char, int,
float, double, etc .though it differs from machine to machine, char data type takes 1 byte
memory; int takes 2 bytes, etc.
Every byte in the computer’s memory has an address number. So, when your program is loaded
into memory, every variable in your program occupies portions of these addressed bytes starting
at a particular address and extends a certain range of bytes; based on the data type, it extends 1
address long for char data type, 2 addresses for int, etc note that this amount changes from
machine to machine.

Declaration of pointer
Syntax: data-type * pointer-name;
Pointer-name is any valid identifier name and data-type is any data type of c ++, like int, float etc.
When a variable name is preceded by asterisk (*) then that is pointer variable. When we declare pointer
variable, it stores the address of data type which is written in front of that.
E.g. int *p;
The address of operator (&)
A variable in the computer’s memory is placed starting at a particular address and the address of
operator (&) gives us that address number.
Example
#include<iostream.h>
void main ( )
{
int my_var = 10;
cout<<&my_var;// displays the address from where my_var starts in memory
}
The insertion operator << interprets the address in hexadecimal arithmetic and 0x is a prefix of
the address number. That means, the address of memory is expressed in hexadecimal.
Pointer variables
A pointer is a variable that holds a memory address number.
The value that is found by the address of (&) operator is a constant address number. This
address value is stored in variables called pointer variables or pointers. Hence, pointers are
variables that store the address values of variables.
Example: #include<iostream.h>
void main ( )
{
int my_var = 10;
int *ptr;
ptr=&my_var;
cout<<ptr;// displays the address my_var like the previous program
}
52
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

When a pointer is assigned address of a variable, that pointer starts to point to the address of the
given variable.
When pointers are defined, they are given a data type like int, char, float, etc and this means that
the pointer variable can hold the address of the same data type variable. There are also pointers
with no data type called void pointers (see the following). Naming a pointer variable is the same
as naming any other identifier, except that each pointer identifier is preceded by the asterisk (*).

N.B whenever you declare a pointer, make sure that it is assigned an address. This is to avoid
pointers from pointing randomly to unwanted memory locations, even locations out of your
program in memory.

Pointers to void (void pointers)


Note that we cannot assign the address of a float type variable to a pointer to int as follows.
float f;
int *P;
P = &f; // this is illegal statement

Similarly
float *P;
int x;
P = &x; // again this is illegal

That means, we can assign the address of variable to pointer variable only when variable data type and
pointer data type is the same (identical). Then if both are different type, then we can’t assign the address
of variable to pointer variable.
But, in C++ this is possible by declaring pointer variable as a void as follows:
void *P;
The above pointer is called pointer to void type or void pointer. That means pointer P point any type of
data type; int, float, char, etc.

void *P;
int x;
float y;
P = &y; // ok
P = &x; // ok, because P is void pointer.
Accessing the variable pointed to
We say earlier that an asterisk (*) before a variable name in a declaration tells the compiler that
this is a pointer.

Example: int *pi;


int j;
pi = &j; pointer pi is assigned the address of the variable j( not the content of j)

53
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

But, an asterisk before a pointer variable in the code (i.e. after the pointer is declared) indicates
that we are referring to the variable, (the contents of the variable) which the pointer is pointing.
Example *pi = 4; means we are assigning 4 to the memory location which is addressed by the
pointer pi.
Example
#include<iostream.h>
void main ( )
{
int num1 = 10, num2 = 20;
int *p;
p = &num1;
cout<<p<<endl; // displays address of num1
cout<<*p<<endl; // displays content of the address (i.e. 10)
*p = 15; // changing the contents of the address p
cout<<num1<<endl; // displays 15 (not 10)
p = &num2; // pointer points to num2
cout<<*p<<endl; // displays content of the address (i.e. 20)
*p = 120; // assigning 120 to the contents of the address in p
cout<<num2<<endl; // displays 120 (not 20)
}
Using the asterisk (*) to access the value stored in an address is called indirect addressing or
sometimes dereferencing the pointer.
E.g. int v;
int *p;
p = &v;
v = 3; // assigns 3 to v
*p = 3; // also assigns 3 to v, since p has the address of v
*&v = 3; // this too assigns 3 to v

Applications of pointers
I) Pointers and arrays
When an array is declared, the name of the array is its address.
Example: int iArray [3] = {8, 12, 15};
Assume this array is stored in memory like the following.

001 8 iArray [0]


Address 002
Number 003 12 iArray [1]
004
15
005 iArray [2]
In this case, iArray is a constant containing the address 001(you can assume iArray as another
name for 001).
54
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Hence, cout<<iArray; displays 001, (remember that cout<<iArray [0]; displays 8 in this case).
cout<<*iArray; displays the contents of the address iArray (i.e. 8)
cout<<*(iArray + 1); displays 12
The following piece of code can display the contents of the above array one by one.
.
.
.
for (int j=0; j<3; j++)
cout<<*(iArray + j) <<endl;
.
.
.
In the above case, we cannot say iArray++ since iArray is an address constant and it is not
possible to change a constant by using the increment operator. But, we can assign the address
constant to a pointer variable; and then it is possible to use the increment operator ++ on the
pointer variable (changing the pointer variable by incrementing its current value by 1). In
performing mathematical arithmetic on pointers, there is one core issue to note. When adding 1
to an address for example, the compiler, instead of referring to a location simply 1 byte next, it
considers the type of data stored on the address (like whether it is int, char, float etc) and
performs the arithmetic on the address according to the amount of bytes that the data on that
address consumes.

e.g. iArray + 1; in the above case is referring to a location 2 bytes next, since iArray is an
int array it contains 2 bytes. In computers that give 4 bytes to float data
types, adding 1 to the address in the same way means referring to an
address next to 4 bytes of memory.

#include <iostream.h>
void main ( )
{
int iArray [3] = {25, 26, 36};
int *ptr;
ptr = iArray; // no need of & since array name is an address by itself
// ptr = &iArray [0]
for (int j = 0; j < 3; j++)
cout<<*(ptr + +) < <endl;

This program displays all the contents of the array using for loop. Here, the increment operator +
+ is used with a pointer variable (ptr), though it is not possible to use it with address constant
(iArray).

55
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

II). Pointers and strings


Since strings are array of type char, pointer notations on arrays can be applied to the characters
in strings.
Example
#include<iostream.h>
void main ( )
{
char str1 [ ] = “First string”;
char *str2 = “Second string”;
cout<<str1<<endl; // displays First string
cout<<str2<<endl; // displays Second string
// str1 ++; // cannot do this, because str1 is constant
str2 ++; // this is ok, because str2 is a pointer variable
cout<<str2<<endl; // displays “econd string” because it was incremented by 1 byte
}
In this program, we initialized two strings: first on the address constant str1, and second on a
pointer variable str2. Since the first one is an address constant, we can’t change its value by
incrementing using ++ operator, while we can change pointer variables like the second one in the
above way.

III). Pointers and functions


We can use pointers to pass value from calling program to a function. Like passing values by
reference, passing values to functions by pointers is also used when the function is intended to
modify variables in the calling program.

Example #include<iostream.h>
void to_celsius (float *);
void main ( )
{
float fahr;
cout<<”Enter temperature in Fahrenheit: “;
cin>>fahr;
to_celsius (&fahr);
cout<<”In Celsius, it is: “<<fahr;
}
void to_celsius (float *f)
{
*f = (*f – 32)*5/9;
}

In this program, the function to_celsius ( ) takes the address of the variable fahr in main ( ) and
changes its content based on the instruction.

56
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The most common use of references is for function parameters. Reference parameters facilitate
the pass-by-reference style of arguments, as opposed to the pass-by-value style which we have
used so far. To observe the differences, consider the three swap functions in the following
example.
void swap1 (int x, int y)
{
int temp = x;
x = y;
y = temp;
}
void swap2 (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void swap3 (int &x, int &y)
{
int temp = x;
x = y;
y = temp;
}
Although swap1 swaps x and y, this has no effect on the arguments passed to the function,
because swap1 receives a copy of the arguments. What happens to the copy does not affect the
original.
Swap2 overcomes the problem of swap1 by using pointer parameters instead. By dereferencing
the pointers, swap2 gets the original values and swaps them.

Swap3 overcomes the problem of swap1 by using reference parameters instead. The parameters
become aliases for the arguments passed to the function and therefore swap them as intended.

Swap3 has the added advantage that its call syntax is the same as swap1 and involves no
addressing or dereferencing. The following main function illustrates the differences:
void main ( )
{
int i = 10, j = 20;
swap1 (i, j); cout<<i<<”, “<<j<<”\n”;
swap2 (i, j); cout<<i<<”, “<<j<<”\n”;
swap3 (&i, &j); cout<<i<<”, “<<”\n”;
}
When run, it will produce the following output:
10, 20
20, 10
10, 20
57
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

IV) Pointers and two dimensional arrays


By using pointer we can display elements of two a dimensional array as follows.

Example:
#include<iostream.h>
void main ()
{
int AA [ ] [3] = {7, 9, 3, 4, 1, 8};
for (int i=0; i<2; i++)
{
for (int k=0; k<3; k++)
cout<<*(*(AA + i) +k) <<” “;
cout<<endl;
}
}

58
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Chapter 6
File-oriented Input/output
So far, we saw programs taking input data from the user via keyboard using the extraction
operator >> with the object cin, and displaying output to the user via the monitor using the
insertion operator << with the object cout. Treated this way, the data that is processed by your
program is lost by the time the program is stopped or when the computer is turned off, because
your program used the computer’s volatile memory (RAM). It is obvious that most useful
programs need to read and write data to disk files. This part of the course deals with handling a
programs data in relation with disk files.

Header files

Data flow in general (to and out of the program) is called stream in C ++. We include the header
file iostream.h for data flow to the monitor and from the keyboard using the objects cout and cin.
For data streams to/from disk files, we include the header file fstream.h, in which the iostream
class and other classes for disk file input/output like ofstream, ifstream and fstream are defined.
(If we include fstream.h, we don’t need to include iostream.h).

Creating objects for file streams

Earlier, we used the predefined cout and cin objects of the iostream class for stream output to
video display and input from keyboard respectively. In file input/output, we create our own
objects for both file output and input purposes using ofstream, ifstream and fstream classes. All
these classes are defined in fstream.h header file.

ofstream: used to create objects for output data to files.


ifstream: used to create objects for input data from files.
fstream: used to create object that can be used for both input/output data from and to file.

That is:
If a file is declared by ofstream class, then the file can be used for only writing onto file purpose.
If a file is declared by ifstream class, then the file can be used for only reading from file
purpose.
If a file is declared by fstream class, then the file can be used for both reading & writing
onto/from file purpose.

Syntax: for creating an object is:


class_name object_name;
Note: object_name should be a valid identifier.

59
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Opening and closing files


i. Opening a file
A file can created by the above three classes through constructors as follows.
Syntax: the general syntax to open a file is
Object_name. open (file name of the file );

A. ofstream fout (“hello.txt”);


The above statement creates an object fout of ofstream class and this object with a file hello (we
can give any other valid name). But in file hello we can only write the data (i.e. output data to it)
because this is created by ofstream class.

B. ifstream infile (“test.txt”);

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. we can only read data from it) because this
is created by ifstream class.

C. fstream iofile (“help.txt”);


The above statement creates an object iofile of fstream class and attached a file help with this. In
the file help we can perform both input and output operation (i.e. we can read data from it or
write data to it) because this is created by fstream class.

The above files can be opened by open ( ) function as follows.

a. ofstream fout (“hello.txt”);


The effect of this is the same as
ofstream fout;
fout. open (“hello.txt”);

b. ifstream infile (“test.txt”);


Has the same effect with
ifstream infile;
infile. open (“test.txt”);

c. fstream iofile (“help.txt”);


Has the same effect with
fstream iofile;
iofile. open (“help.txt”);

60
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

ii. closing a file


A file can be closed after the operation is done on the file by close ( ) function as follows.
Example: for the above three files
a. fout. close( );
b. infile. close( );
c. iofile. close( );
The general syntax for closing a file is:
object_name. close ( );

In above examples, fout, infile and iofile are objects.

Reading and writing string (string input output)

By using the insertion and extraction operator string data can be writing and read to/from a file.
Example: The following program writes strings The following program writes strings to a file
to a file using ofstream class object. using fstream class object.
#include<fstream.h> // for ofstream
#include<fstream.h> // for fstream
#include<conio.h>
#include<conio.h>
void main()
void main()
{
{
ofstream my_file ("test.txt"); // creating an object
fstream my_file ("test.txt", ios::out); //
and opening a file at a time
creating //an object and opening a file at a time
/* /*
Or the file can be opened as follows: Or the file can be opened as follows:
ofstream my_file; // object creation fstream my_file; // object creation
my_file. open(“test.txt”); // file opening my_file. open (“test.txt”, ios::out); // the 2nd
// or my_file. open (“test.txt”, ios::out); // the 2 nd // //argument is mandatory
argument is optional */
*/ my_file <<"This a trial text\n";
my_file <<"This a trial text\n"; my_file <<"to be written in disk file\n";
my_file <<"to be written in disk file\n"; my_file <<"by file name \"Test\".\n";
my_file <<"by file name \"Test\".\n"; my_file. close (); // this is optional
my_file. close (); // this is optional getch();
getch(); }
}
In this program, we created an object called my_file using the ofstream class, which is used to create
objects for output data to files, and at the same time the file name test (to be created on the desk) is given
to our output object as an argument in quotations.

A file with .txt extension will be created in the folder where..tc\ is located in. You can set the drive for the
above program as: ofstream my_file (“a: test.txt”); if you want the file to be created on a floppy disk.

Using the insertion operator << with our object my_file, the program outputs the text to the file. Note that
the above program displays no output to the screen.

61
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Example: The following program reads string from a The following program reads string from a file using
file using ifstream class object. fstream class object.
#include<fstream.h> // for ifstream #include<fstream.h> // for fstream
#include<conio.h> #include<conio.h>
void main() void main()
{ const int MAX=80; { const int MAX=80;
char line[MAX]; char line[MAX];
ifstream my_ifile; fstream my_ifile;
my_ifile. open (“test.txt”); my_file. open (“test.txt”, ios::in);
// or my_file. open (“test.txt”, ios::in); // the 2nd argument is mandatory
// the 2nd argument is optional while (my_ifile)
while (my_ifile) {
{ my_ifile. getline (line.MAX);
my_ifile. getline (line.MAX); cout<<line<<endl;
cout<<line<<endl; }
} my_ifile. close();
my_ifile. close(); getch();
getch(); }
}
Here, we created our object my_ifile using the ifstream class, which is used to create objects for input data from files.
The name of the file to be opened from disk for reading by the program is given to the object as an argument.
In this case, we did not use the extraction operator >> to read data from file and put it on the string variable line
because this operator has a problem in reading embedded spaces in strings, as we saw it in earlier chapters. Instead,
the getline ( ) function is used; this function reads characters including embedded spaces until it encounters ‘\n’
character, and places the resulting string in the variable supplied as an argument. The maximum size of the variable
is given as the second argument. In this program, the contents of the variable line are displayed to the screen after
each line is read from the file “test”;
Detecting End—of—File
An ifstream object, such as my_ifile in the above program, has a value that can be tested for various error conditions.
If the error condition is true, the object (my_ifile in our case) returns a zero value; otherwise it is non zero.
The while loop here is used to check the End — of — File (EOF), which is a signal from the hard ware when a read
or write operation has reached the end of file. When EOF is reached in the above program, zero value is returned
from the object and the while loop makes the control jump the reading operation.
Before we go to see how to read/write data other than in string format to files, let us summarized what we did so
far. To read or write string to/from files, we simply create objects using either ofstream or ifstream classes. We can
give whatever name we like to these objects like we give names to variables. Then we use << with our object to
write the string from the program to the opened file, in the same way we used << with cout to display an output to
the monitor.
Also to read strings from file to our program, we defined a string variable and used the getline ( ) function to read the
string from file to the variable. This function is similar with the cin.get ( ) function that reads strings with embedded
blanks from the keyboard.

As mentioned earlier, we can also use the extraction operator >> to read strings from file to variables in
our programs, but as you already saw, using the function getline ( ) is more advantageous in reading
strings from file.

62
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

Character Input Output (Reading and Writing character)


In addition to writing and reading strings to files, we also need to do so with single characters. We use the
put ( ) and get ( ) functions in such cases. They output and inputs single character at a time.

Example: The following program writes as The following program writes as string,
string, character by character, to a file using character by character, to a file using fstream
ofstream class object. class object
#include<fstream.h> // for ofstream #include<fstream.h> // for fstream
#include<conio.h> #include<conio.h>
#include<string.h> // for strlen ( ) function #include<string.h> // for strlen ( ) function
void main() void main()
{ {
char str [ ] = “This string will be written to a file char str [ ] = “This string will be written to a file
character by character “; character by character “;
ofstream o_file (“test2.txt”); fstream o_file (“test2.txt”, ios::out);
// or ofstream o_file(“test.txt”, ios::out); // the 2nd argument is mandatory
for (int i = 0; i < strlen(str); i++) for (int i = 0; i < strlen(str); i++)
o_file.put(str[i]); o_file.put(str[i]);
o_file. close ( ); o_file. close ( );
getch ( ); getch ( );
} }
In the program, we used the put ( ) function in combination with our ofstream object o_file. The string is
treated to be written character by character using for loop to the file “test2”.

Example: The following program reads characters from a file and displays them to the monitor, using
ifstream object.
#include<fstream.h> // for ifstream
#include<conio.h>
void main()
{
char ch;
ifstream i_file (“test2.txt”);
// or ifstream i_file(“test2.txt”,ios::in);
while (i_file)
{
i_file.get(ch);
cout<<ch;
}
i_file. close ( );
getch ();
}

63
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The following program reads characters from a file and displays them to the monitor, using fstream
object.
#include<fstream.h> // for fstream
#include<conio.h>
void main()
{
char ch;
fstream i_file(“test2.txt”, ios::in);
// the 2nd argument is mandatory
while (i_file)
{
i_file.get(ch);
cout<<ch;
}
i_file. close ( );
getch ();
}

The while loop in this program reads characters from the opened file “test2”, puts the character on the
variable ch, and displays it to the monitor, until the EOF is reached. We could use the statement
i_file>>ch; to read characters from the file to the program, but this operator ignores the blank spaces in
between the words, so it is better to use get ( ) function.

Writing /Reading Structures’ Data To / From Files


As we saw earlier in this course, structures are collections of different data types; they are not simple
characters to be written to or read from files using the functions we’ve used before, such as <<, >>, get
( ), and put ( ). We use the write ( ) and read ( ) functions to do file read write operations on user defined
data types likes structures. The data stored in the structure is treated as a sequence of bytes. This way of
data handling is called binary file (unlike the previous characters files in the above programs).

We can create objects of the fstream class, to use same object for both reading and writing purposes to a
file. (We already saw ifstream and ofstream classes).

E.g. fstream my_rec; // creating an object called my_rec for both reading and writing data from/to file.

The open ( ) function

In previous examples of character files, we created a file object and initialized it with a file name, i.e. the
file to be created on the disk, in the same statement.

E.g. ofstream my_ofile (“test.txt”);

But in binary file operation, we usually create a disk file in one statement and open it in another, using the
open ( ) function, which is a member of the fstream class.

e.g. fstream my_rec;


my_rec. open (“file1”,ios::app|ios::out|ios::in);
64
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

In the open ( ) function we include several mode bits to specify certain aspects of the file object we are
opening.

The most common mode bits for the open ( ) functions are:

 app start reading or writing at end of file (Append).


 in open file for reading (default for ifstream).
 out open file for writing (default for ofstream).

In writing the structure data to a file, we use the write ( ) function as mentioned earlier.

E.g. the following program writes structure data to a file.


#include<fstream.h> my_rec. open("record1.dat",ios::app | ios::out);
#include<conio.h> do
#include<ctype.h> // for toupper ( ) {
function cout<<"Enter name:";
struct person cin>>pers.name;
{ cout<<"Enter age:";
char name[25]; cin>>pers.age;
int age; my_rec. write((char *)& pers, sizeof(pers));
}; cout<<"Add more?(Y/N)";
void main() cin>>ans;
{ ans=toupper(ans);
clrscr(); }while(ans=='Y');
char ans; my_rec. close ( );
person pers; getch();
fstream my_rec; }

The above program accept name and age of a person from a user, using the structure data type pers, and
write the structure data to the disk file record1; the program continues accepting and writing the data as
much as the user wants to continue (because of the do while loop).

In the program, we created an fstream object called my_rec. We wanted this object only to write data to
the disk file and hence used the mode bit ios::out. (Note that it is also possible to add the mode bit ios::in
at the same time if we wanted both to write and read using the object my_rec). We also wanted the object
to write the data in the specified file (record1) at the end of the previous contents of the file, i.e. to append
the data (if there is any); that is the reason for opening it in ios::app mode. This mode bit avoids
overwriting (deleting) the data contained in the disk file if it was already created and has data.

In the program the contents of the pers structure are written to disk, each time the user enter, using the
write ( ) function. This function takes two arguments: the address of structure to be written and the length
of the structure in bytes. We use the sizeof ( ) to find the length of the pers structure. The address of the
structure must be cast to type pointer to char.

For the above case, sizeof (pers) returns 27 byte as length of the pers structure, if the machine you’re
working on assigns 1 byte for char and 2 bytes for int.

65
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

We read structures from file using another but similar function, read ( ). The arguments of this function
are the same as that of the write ( ) function.

In reading data from file to a program, from which point or position of the disk file do you think the read (
) function starts reading?

It starts reading from where the file pointer is.

File pointers

File pointers are integer numbers that starts from 0, according to the byte number in the file where reading
or writing will take place. (Don’t confuse file pointers with the variable address pointers that we saw
earlier; file pointers are simply numbers).

When input and output operation takes place, 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.
And when we open a file in appended mode the file pointer is automatically set at the end of file.

There are built in functions to access the file pointer, and hence to make us be able to or read from a
specific location in the file, as we need.

We use the seekg ( ) and tellg ( ) functions to take the file pointer to some position in the file or to read
(get) the position of the file pointer when the file is opened for reading.

And we use the seekp ( ) and tellp ( ) functions to take the file pointer or read (get) its position like the
above case when the file is opened for writing.

seekg ( ): set the file pointer in the file to the position of the number of bytes given to it as an argument.
As mentioned above, we use this function when reading the file.

E.g. object_name. seekg (0); // this makes reading to start from the beginning of the file when the
// file pointer is not at the beginning (since files start from byte 0).

This function can also take a second argument; the first argument represents the offset from a particular
location in the file, and the second specifies the location from which the offset is measured. Thus:

 ios::end end of file


 ios::beg beginning of file
 ios::cur current pointer position in the file

e.g. object_name. seekg (-22,ios::end); // takes the pointer 22 byte back from the of file

tellg ( ): this function returns the current position of the file pointer when the file is opened for reading.

Example: int pos;


pos = my_rec. tellg( ); // assigns the current file pointer position (in byte no.) to the variable pos
seekp ( ): this function is the same as seekg ( ) except it is used for writing file pointer .

66
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

tellp( ): this function returns the current position of the file pointer when the file is opened for
writing.
In addition to the earlier error handling mechanisms we saw for EOF, we can use eof ( ). This
function returns a non-zero value when an EOF is encountered.
The following program receives person’s name and age, until the user wants to stop using a
structure to a file. The program then displays what is available in the opened file to the monitor.
Note that the program displays not only the data entered currently, but also data entered
previously to the file. This is because we put the file pointer at the beginning position of the file
using seekg ( ).

#include<fstream.h> cout<<"Enter age:";


#include<conio.h> cin>>pers.age;
#include<ctype.h> // for toupper ( ) my_rec. write((char *)& pers, sizeof(pers));
function cout<<"Add more?(Y/N)";
struct person cin>>ans;
{ ans=toupper(ans);
char name[25]; }while(ans=='Y');
int age; cout<<”\n the data in the file is: \n”;
}; my_rec. seekg (0);
void main() my_rec. read ((char *) &pers, sizeof (pers));
{ while(!my_rec.eof( ))
clrscr();
{
char ans;
cout<<”\n Name: “<<pers.name<<endl;
person pers;
fstream my_rec; cout<<” Age: “<<pers.age<<endl;
my_rec. open(“record2.dat”, ios::app | ios::out | my_rec. read ((char *) &pers, sizeof(pers));
ios::in); }
do my_rec. close ( );
{ getch();
cout<<"Enter name:"; }
cin>>pers.name;
After the while loop and before closing the opened file in the above program, you can add the
following piece of code to know how many person’s data is in the opened file.
.
.
int post;
my_rec. seekg (0, ios::end);
pos = (my_rec. tellg ( )/sizeof (pers));
cout<<”\n There are “<<pos<<” people in the file”;
.
.
Remember that the function tellg ( ) returns the file pointer byte number (an integer value).

67
Dambi Dollo University Information Technology Dept. Fundamentals of Programming II

The following program can also read a person’s information at a specific number in the file (the
file created by the above program).
#include<fstream.h>
#include<conio.h>
struct person
{
char name[25];
int age;
};
void main()
{
clrscr();
int num, pos;
person pers;
ifstream my_rec(“record2.dat”);
cout<<”Enter the person’s number: “;
cin>>num;
pos = (num-1) *sizeof(pers);
my_rec. seekg (pos);
my_rec. read((char *) &pers, sizeof(pers));
cout<<”\n Name: “<<pers.name<<endl;
cout<<”Age: “<<pers.age<<endl;
getch();
}

68

You might also like