Arrays: Introduction - Variables in A Program Have Values Associated With Them. During
Arrays: Introduction - Variables in A Program Have Values Associated With Them. During
• 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
•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
• 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
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
• 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
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++
• 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
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;