You are on page 1of 66

Arrays

Introduction -Variables in a program have values associated with them. During


program execution these values are accessed by using the identifier associated with
the variable in expressions etc. In none of the programs written so far have very many
-variables been used to represent the values that were required
What is an arrays

An array is a data structure which allows a collective name to be given


to a group of elements which all have the same type. An individual
element of an array is identified by its own unique index (or subscript).
• An array can be thought of as a collection of numbered boxes each
containing one data item.
• An array can be thought of as a collection of numbered boxes each
containing one data item. The number associated with the box is the
index of the item. To access a particular item the index of the box
associated with the item is used to access the appropriate box
One Dimensional Array
An array declaration is very similar to a variable declaration. First a type is given for the elements of
the array, then an identifier for the array and, within square brackets, the number of elements in
the array. The number of elements must be an integer.
Eg float average _temp[100];
Accessing Array Elements

• The first elements in an array in c++ always has the index 0 and if the
array has elements the last element will have the index n-1.
• An array element is accessed by write the identifier of the array
followed by the subscript in square bracket.
• To display the value 55 we should say cout<<mark[3];
• To display the value 88 we should say cout<<mark[6];etc
Initialization of arrays

• The initialization of simple variables in their declaration has already been


covered.
• An array can be initialized in a similar manner.
• In this case the initial values are given as a list enclosed in curly brackets.
• For example initialization an array to hold the first 7 odd number could
be written as follow
• int odd [10]={1,3,5,7,11,13};possible
• int odd[]={1,3,5,7,9,11};possible
• int odd[];not possible
Con…….
• int odd[7]; possible
• Not that if we initialize an array ,it is optional to give the size and We
can omit the array size.
• We can omit the array size however if the array is given a size then
the size must be greater than or equal to the number of elements
• In the initialization list for example
• Int odd[10]={1,3,5,7,9,11,13}
Con……………
• Accessing elements the whole element of the array are accessed
using for loop
• Eg to display all the elements of an array whose name is odd which
has 10 elements
• Write the following code:
• For( int i==0;i<10;i++)
• Cout<<odd[i]<<””;
Multidimensional arrays

• An array may have more than one dimension


• Each dimension is represented as a subscript (index)in the array
• There for a two dimensional array has two subscript ,a three
subscript and so on
• Array can have any numbers of dimensions, although most of the
arrays that you create will likely be of one or two dimensions
Declaration of two dimensional arrays

• Suppose the program contains an array named board


The declaration of array named board that represents 4 by 3 array size then
we can declared int square_board [4][3];
• this implies that the array has 4 group and each group there are 3 individual
values
int square_board[4][3]={{2,3,4};{7,8,9};{2,1,5};{8,3,2}};
• in other word the first number which is 4 implies the number of row
• the second is which is 3 the number of column
• this is illustrated in finger below
The array board[4][3] has 4 rows and 3 columns
Con….

•z
Initializing multidimensional array

• to initialize the multidimensional array you must assign the list of value to
array elements in order
• there for if the program has an array in Ar[5][3] the first three elements go
in to int Ar[0];
the next three in to Ar[1]; and so on
• the program initialization this array by writing
int Ar[5][3]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
• by using initialization group we can identify
int Ar[5][3]={{1,2,3};{4,5,6};{7,8,9};{10,11,12},{13,14,15}};
Conn…

• The compiler ignores the inner bract which clarify how the number are distributed
• Each values should be separated by comma regardless of whether inner bras are
included
• The entire initialization must appear whine bras and it must end with a semicolon
Accessing individual elements of the 2 dimensional array

• We should use two index ,one for the row/group and the other is
column/individual
• In order to access the element in row 2 and column 1 which is 8
Ar[2][1]
Accessing the hole elements of the two dimensional array
• If you want to access all elements of an array Use nested for loops.
String representation and manipulation

• String in c++ is noting but a sequence of character in which the last


character is the null character ‘\0’
• The null character indicates the end of the string
• Any array of character can be converted in to string type in c++ by
appending this special character at the end of array sequence
• In c++ string of character are held as an array of character
• one character held in each element
• in addition an special null character represents by ‘\0’(backslash and zero)
• if the string has n character then it requires an n+1 element array to store
Declaration of string

• string variable s1 could be declared as flow char s1[10] ;


initialization of string
• string can be initialized at the time of declaration
eg char s1[]=”example”;
• s1 also initialized like the following char s1[]={‘e’,;x’,’a’,’m’.’p’.’l’.’e’,’\o’};
• inside the memory s1 is stored like the following figure.
Accessing each character of the string
and all string

• Accessing each character of the string


• display individual character from string use the index of character
• eg cout<<s1[4] display the letter p
• cout<<s1[1] display the letter x etc
• accessing all string
• if you want to display the whole element write only the name of the
array
• eg to display all the content of the string s1.write cout<<s1;display
example
Reading string from key board

• When the input stream cin is used space character, newline etc. are
used as separators and terminators
• Thus when inputting numeric data cin skips over any leading spaces
and terminates reading a value
Also if it has a space character in the middle then input will be
terminated on that space character
• The null character will be appended to the end of the string in the
character array by the stream function
• To read a string with several words in it using cin we have to call cin
once for each word .
Example
#include <iostream>
using namespace std;
int main()
{
const int max=80;
char str[max];
cout<<"\n enter a string "<<endl;
cin>>str;
cout<<"\n you entered :"<<str<<endl;
return 0;
}
Reading multiple lines

• We have saved the problem of reading string with embedded blanks


(space)
It turns out that the cin: :get()
• Function can take a third argument to out in this situation
• This argument specifies the character that tells the function to top
reading the default value of this argument is the new line (‘\n’)character
• But if you call the function with some other character for this argument.t
the default will be over ridden by the specified character .
• In the next example we call the function with a dollor sign(‘$’)as third
argument
String read the keyboard up two new line

Usin the cin: :get() g


#include <iostream>
using namespace std;
int main()
{
const int max=80;
char str[max];
cout<<"\n enter a string "<<endl;
cin.get(str,max);
cout<<"\n you entered :"<<str<<endl;
return 0;
}
Reading multiple line string from keyboard

• we call the function with a dollar sign(‘$’)


#include <iostream>
using namespace std;
int main()
{
const int max=80;
char str[max];
cout<<"\n enter a string "<<endl;
cin.get(str,max,'&');
cout<<"\n you entered :"<<str<<endl;
return 0;
}
Structures
• In general can call a structure in collection of data type
• A structure contains number of data type grouped together
• These data types may be or may not be of the same data type
• Declaration of structure
• The key word ‘ struct ‘ is used for creating structure .
Syntax
• Struct structure _name
• {
• data type 1 varname1;
• data type 1 varname2;
• data type 1 varname3;
• };
• Creating the object of structure
• Struct Structure_ name var1,var2,var3;
• Eg struct list{
int roll;
char name[10];
float marks;
};
Struct list a,b,c;
   
Chapter 3:- Pointer

• Pointer are variables which contain memory addresses as their values


• Normally variable directly contain a specific value
• a pointer contains the memory address of a variable that, in turn,
contains a specific value
• in this sense a variable name directly references a value and a pointer
indirectly references value
• referencing a value through a pointer is called indirection.
• each variable in a program occupies a part of the computer’s memory for
example an integer variable occupies 4, char 1, double 8, float 4, short 2
byte of memory
Con….
• the location of the piece of memory used to store a variable is called the address of
that variable
• an address is some kind of numbers similar to house numbers in a kebele that is used
to locate the information stored in that particular variable
• int I; address of I 0*154 10101011
0*155 00001111
0*156 10001000
0*157 11100011
• Char c address of c 0*158 00111011
• Short s address of s 0*159 10111100
0*200 11001100
Con…….
• The operating system organized the memory with unique and
consecutive numbers
• If we talk about location 1776 in the memory
• We know that there is only one location with that address and also
that is between address 1775 and 1777
• Pointer “point” to variable by telling where the variable is located
Declaring variables of the type pointer

• Pointer is a special data variable which is introduced to hold memory address of


other variables
• Syntax :type *pointer _name ;
• Eg to declared a pointer variable p that can “point” to variable of type double *p;
• The asterisk identifies as pointer variable
• To declare multiple pointers in a statement us the asterisk before each pointer
variable
• Eg int *p1,*p2,v1,v2;
• *p1 and p2 point to variable of type int
• * v1 and v2 are variables of type int
The address operator

• The address operator :


• The & operator can be used to determine the address of variable which can be assigned
to pointer variable
• Example : int *p1;v1;
• P1=&v1;p1 is now a pointer to v1
• V1 can be “the variable pointed to by p”;
• The dereferencing operator
• Here the *_is the dereferencing operator
• The “phrase “ the variable pointed to p is translate in to c++ as *p
• & and* are invers they cancel each other out eg cout<<p1;
cout<<&(*P);*p means v1 &v1 is p1 p1 and v1 is equal then cancel each other
• int I =17; 0*1054
• int *ptr;
• ptr=&;  
17
• cout<<*ptr<<endl;  

 
Example
#include <iostream>
using namespace std;
int main ()
{
int*p1,v1;
v1=0;
p1=&v1;//v1 and p1 now refer to the same variable
*p1=42;
cout<<v1<<endl;
cout<<*p1<<endl;
cout<<&v1<<endl;
return 0;
}
Pointer assignment
• The assignment operator= is used to assign the value of one pointer
to another
• Example :
• Then p2=p1 causes *p2,*p1,and v1 all to name the same variable eg
*p1.v1=6*p2 v2=9 then p2=6 then p1 and p2 the same
• Same care is required making assignments to pointer variables
• P1=p3;//change the location that p1 “points” to
• *p=*p3//change the value at the location that p1 “points
Arithmetic of pointer

• Arithmetic of pointer
• Any addition and subtraction operation are allowed to be conducted
• But both addition and subtraction have a deferent behavior with pointer according to the size
of the data type of which they point
• When we saw that some occupy more or less space then other in the memory
• For example, in the case of integer numbers char occupies 1 byte short occupies 2byte and int
occupies 4 bytes
• Let’s suppose that we have 3 pointes
• Char *_ my char;
• Short ­*_my short;
• Int *_ my long;
• And that we know that point to memory location 1000,2000,3000 respectively
Arithmetic of pointer
• So we write
• Mychare++;
• Myshort++;
• Mylong++;
• 
• Mychar as you my expected contain the value 10001
• Myshort would contain the value 2002 and myint3004
• The reason is when adding 1 to pointer we are making it to point to the
following element of the same type with which it has been defined and there
for the size in byte of the type pointed is added to the pointer .
Example
#include <iostream>
using namespace std;
int main()
{
int x,*p1,*p2,*p3;
p1=&x;
p2=p1--;
p3=--p1;
cout<<p1<<endl<<p2<<endl<<p3<<endl;
return 0;
}
•If address of x is 100 then after statement p1=&x,
•P1 contains 1000 after p2=p1--; then p2 is 1000
•After statement p3=--p1; then p1 is 992 and p3 also 992
Pointer and array

• The pointer is identifier of an array is equivalent of the address of its first element
• Int num [20];
• int *p;
• the following a collection would be valid
• p=num;//you can also Say p=num[0];
• at this point p and num are equivalent
• they only deference that we could assign another value to the pointer p where as num
(constant)
• will always point to the first of the 20 integer number of type in with which it was defined
• some unlike p that is an array variable pointer num is a constant pointer( that is an array a
constant pointer )the following allocation is num=p;
• because num is an array (constant pointer ) and no values can be assigned to constant identifier
Pointer and string

• We now string are array of characters


• There for pointer notation can be applied to the character in string s
• But in the case of string if we initialize the string at the time of
declaration the string name is constant
• See the following examples
example
• #include <iostream>
• using namespace std;
• int main()
•{
• char*str="i love ethiopian";
• cout<<str<<endl;
• str++;
• return 0;
•}
Chapter 4 -File management

• Most of the application have their own feature to save some data to
the local disk and read data from the disk again.
• File which are on the secondary storage device are called physical file.
• In order to process file through program logical file must be created
on the RAM.
• This logical file is nothing but an object having ifstream¸ofstream or
fstream data type.
• Eg ifstream. ofstream
Streams and files

• The I/O system supplies a consistent interface to the c++ programmer


independent of the actual device being accessed.
this provides a level of a abstraction b/n the programmer and the
device
• This abstraction is called stream the actual device is called file
• The c++ file system is designed to work with a wide variety of device,
disk drives and tab drives
eg write the file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile1;
outfile1.open("ethio1.txt");
outfile1<<"Hello word";
outfile1.close();
return 0;
}
Read the file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string x;

ifstream infile1;
infile1.open("ethio1.txt");
infile1>>x;
cout<<x<<endl;
infile1.close();
return 0;
}
Conn..
• Even though each device is very different, the c++ file system transforms
each in to logical device called stream
• Stream- a sequence of character
• You associate a stream with a specific file by performing an open
operation
infile.open (“hello .dat”;ios::in);
• once a file is open information can be exchanged between it and program
• if the file can support position request opening that file also initialize the
file position indicator to the start of the file.
• As each character is read from or written to the file the position indicator
is incremented
• You disassociate a file from a specific stream a close operation.
Conn..
• if you close a file opened from output, then contents, if any of its
associated stream are written to the external device, this process is
referred to as flushing the stream
• all files are closed automatically when the program terminates
normally.
How to increment to read the file(all file
read)

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile1;
outfile1.open("ethio.txt");
outfile1<<"programming !!!";
outfile1.close();
return 0;
How to increment to read the file(all file read)
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string x,y,z;

ifstream infile1;
infile1.open("ethio1.txt");
infile1>>x;
cout<<x<<endl;
infile1>>y;
cout<<y<<endl;
infile1>>z;
cout<<z<<endl;
infile1.close();
return 0;
Class for stream I/O in c++

• To perform file, I/O the header file fstream.h is required fstream.h


defines several classes including ifstream, ofstream,and fstream
• Three files I/o classes are used for file read/write operations.
• Ifstream -can be used for file read/input operations
• Ofstream- can be used for file write/output operations
• Fstream-can be used for both read /write c++ file I/o operation
Continue
Conn……….
• Ios is the base class
• -istream and ostream inherit from ios
• -ifstream inherits from istream (and ios)
• -ofstream inherits from ostream(and ios)
• -iostream inherits from istream and ostream (&ios)
• -fstream inherits from ifstream ,iostream and ofstream
Types of file (Text and Binary)

• In file processing, files are generally classified into two as


• Text file and
• Binary file
• Text file is a file in which its content is treated as a sequence of
characters and can be accessed sequentially. Where as binary file is a
file in which its content is treated as record sequence in a binary
format. Binary format refers to the actual format the data is going to
be placed and processed in the memory which is directly related to its
data type.
File access methods (sequential and random access files)

 file can access either in sequential manner or random manner


 The access mode of file determines how one can read, write, change, add
and delate from file
 A sequential file has to be accessed in the same order as the file written.
 This is analogues to cassette tapes you play music in the same order as it
was recorded.
• Unlike sequential file you can have random access to file in any order you
went.
• Think of data in random access file as being similar to music on compact
disk (cd)
Sequential file concepts

• You can perform three operation on sequential disk file you can crate
disk file, add to disk file read from disk files, closing (declared, open
file, write/read and close)
Opening and closing sequential files
• When you open a disk file you only have to inform c++ the file name
and what you want to do with it
• C++ and your operating system work together to make sure that the
disk is ready and they crate an entry in your file directory for the file
name (if you are creating a file)
• When you close a file c++ writes any remaining data to the file
releases the file from the program and updates the file directory to
reflect the file new size
• You can use either of the two method to open a file in c++ using a
constructor or using the open function
continue
• The following c++ statement will create an object with the name fout of
ofstream class and this object will be associated with file name
Ofstream fout(“hello.txt”’);
• This statement uses the constructor method
• The following c++ statement will create an object with the name fout of
ofstream class and this object will be associated with file name “hello
.txt”;
• Fout.open(“hello.txt”);
• If you open a file for writing (out access mode),c++ crates the file
• If a file that name already exits C++ over write the old file with no waring.
• You must be careful when opening file not to overwrite existing data that
you want.
continue
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile1;
outfile1.open("ethio programming.txt",ios::app);
outfile1<<" \nprogramming gggggggg !!!";
outfile1.close();
return 0;
}
Checking state flags

• In addition to eof(), which checks if the end of file has been reached, other member functions
exist to check the state of a stream (all of them return a bool value):

•.
Continue
• If an error occurs during opening of a file, C++ does not create a vailed file
pointer (file object)
• Instead c++ crates a file pointer (object) equal to zero
fstream mystream;
mystream.open (“test”, ios::in/ios::out);
if open () fail,mystream will be zero
if(mystream) {
cout<<”can not open a file /n;
//handle error
}
contnue
• For example, if you open a file for output, but use an invalid disk
name c++ can’t open the file and there for makes the file object equal
to zero
Continue
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile1;
outfile1.open("ethio1.txt");
outfile1<<"hi all students ";
outfile1.close();
return 0;
}
Continue
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string x,z;
char y,a;
fstream outfile1;
outfile1.open("f:\\ethio1.txt",ios::app);
if(outfile1.fail())
{
cerr<<"the file is not open !!!!\n";
}
outfile1<<"ethio programing";
Continue
#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
ofstream fp;
int main()
{
fp.open("d:\\names.txt",ios::out);
if(fp.fail())
{
cerr<<"\nerror opening the file ";
}
fp<<"my team is out of the game "<<endl;
fp<<"idon't like the tournament"<<endl;
fp.close();
}
Continue
• The first 2 program message is the file is not open !!!!b/c local disk in the
computer is not found(the physical file not matching to logical file ) the 3rd
one is the message display is error opening the file b/c the program is not
created first (not written the file)
• You can also determine the file access mode when crating a file in c++.
• If you went to use the open function to open a file then the syntax is
• Fileobject.open(filename, access mode);
• File name is a string containing valid file name for your computer
• Access mode is the required operation to be take on the file and must be
one the value in the following table
Continue
Reading and writing text files

• Reading and writing text files


• Simply used the << and >> operator in the same way you when performing
console, I\o except that instead of using cin and out you substitute a stream that is
linked to the file
• There are two ways to write and read binary data to and from a file.
• get ( ) and put ( )
• read ( ) and write ( )
• get ( ) and put ( )
• These functions are byte-oriented.
• get ( ) will read a byte of data.
• put ( ) will write a bye of data.
Opening, random access files

Opening, random access files


• The istream member function read input a fixed number of bytes
from the specific stream in to an area in memory beginning at the
specified address
• When the stream is associated with a file function read input bytes at
the location in the file specified by the “get” file position pointer
syntax of write :
• Fileobject.write((char*) &NameOfObject,sizeof(name of object))
• Function write expects data type const char * as its first argument.
Continue
#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main()
{
ofstream outdata;
outdata.open("ethio prog.dat",ios::binary);
if(outdata.fail())
{
cerr<<"\nerror opening a file";
exit(1);
}
int x;
cout<<"\n enter a number :";
cin>>x;
outdata.write((char*) &x,sizeof(x));
outdata.close();
cout<<"\n data has been saved";
Continue
#include <iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main()
{

int x;
ifstream indata;
indata.open("ethio.dat",ios::binary);
if(indata.fail())
{
cerr<<"\n error opening a file ";
exit(1);
}
indata.read((char*)&x,sizeof(x))
cout<<x<<endl
indata.close();
return 0;

You might also like