Chapter 4 Arrays & Strings1 , lecture notes
Chapter 4 Arrays & Strings1 , lecture notes
1
Objectives
To use the array data structure to represent lists and
tables of values.
To define an array, initialize an array and refer to
individual elements of an array.
To define symbolic constants.
To use arrays to store, sort and search lists and
tables of values.
To define and manipulate multidimensional arrays.
To pass arrays to functions.
C++ strings
2
Arrays
Literal way Memory case
3
ARRAYS: Are series of elements of the same
type placed in contiguous/ continuous
memory locations that can be individually
referenced by adding an index to a unique
name.
4
Declaration of arrays in C++:
Type array_name [array_size];
ARRAY_SIZE: specifies how many elements the
array has to contain.
int data[5]; // 5 elements all are integers
char ch[10];// 10 elements all are characters
double x[100];// 100 elements all are double
5
Initializing array in c++.
If an array is declared as global variable it will be
automatically initialized to zero , other wise all the
elements will be garbage values.
8
//to store the value 75 in the third element of
data
data[2] = 75; and,
// to assign/pass the value of the third element of
data to a variable called a, we could write:
a=data[2];
9
//A program calculate the sum and average of maximum of 20 numbers entered by the user.
#include<iostream>
using namespace std;
int main()
{
const int max=20;
int data[max];
int count=0,n;
float sum=0,average;
cout<<"how many element do want to enter\? \n";
cin>>n;
if(n<=0||n>20)
cout<<"you entered invalied number\n";
else
{
cout<<"enter your data\n";
for(int i=0;i<n;i++)
{
cout<<"data["<<i<<"]=";
cin>>data[i];
sum+=data[i]; }
average=sum/n;
cout<<"The Sum is ="<<sum<<endl<<"The Average is ="<<average<<endl;
}
return 0;
10
}
Operations on Arrays
Arithmetic operations(+,-,*,/)
looking for a value held by one of array members.
To find minimum and maximum value of a list
To sort some list
11
Searching Array
#include <iostream.h>
int main()
{
int numbers[] = {10, 25, 36, 44, 52, 60, 75, 89};// Declare the
//members of the array
int find, i, m = 8;
cout << "Enter a number to search:";
cin >> find;
for (i = 0; (i < m) && (numbers[i] != find); ++i)
continue;
if (i == m) cout << find << " is not in the list" << endl; // Find whether
the number typed is a member of the array
else
cout << find << " is the " << i + 1<< "th element in the list" << endl;
return 0; 12
Multidimensional Array
=> are arrays of arrays or arrays of two or more
dimension
=>Used to work with data requiring
multidimensional arrays - for example,
matrices and data in the form of a table.
13
Declaration int a[3][5]; // 2D array
Char x[3][5][9] //3D array
Example
• To define a 2D array, two size specifiers are
required: the first one is for the number of
rows and the second one is for the number of
columns.
Eg. float scores[3][4];
• To access a certain element indices or
subscript corresponding to each dimension
should be supplied.
14
• Example
15
16
Each element in a 2D array is accessed with
two subscripts: the first one is for its row and
the second for its column.
Various Initialization options:
int a[2][3]={{1,5,7},{2,3,6}};
int a[2][3]={0};
int a[2][3]={{1,5},{2}}
17
2-D Array Example
#include<iostream>
using namespace std;
int main()
{
const int Numstudents=10;
const int NumHW=3;
double grades[Numstudents][NumHW];
for(int i=0;i<Numstudents;i++)
{
for(int j=0;j<NumHW;j++)
{
cout<<"Enter HW"<<j<<"Grade for Student Number"<<i<<endl;
cin>>grades[i][j];
}
}
return 0;
} 18
Example: write a program that add two matrices, input by the user
#include<iostream>
using namespace std;
const int max_row=50;
const int max_col=50;
int main()
{ int col,row,i,j;
int a[max_row][max_col]={0}, b[max_row][max_col]={0}, c[max_row][max_col]={0};
cout<<"enter the number row and column \n";
cin>>row>>col;
cout<<"enter the element of first matrix \n";
for( i=0;i<row;i++)
for( j=0;j<col;j++)
cin>>a[i][j];
cout<<"enter the element of second matrix \n";
for( i=0;i<row;i++)
for( j=0;j<col;j++)
cin>>b[i][j];
cout<<"a+b=\n"; // c= a+b
for( i=0;i<row;i++)
for(j=0;j<col;j++)
c[i][j] = a[i][j] +b[i][j];
for( i=0;i<row;i++)
{ for( j=0;j<col;j++)
cout<<c[i][j]<<"\t";
cout<<endl; 19
Passing Array as an Argument to Function
Passing elements of Array as an argument(one dimensional)
• An indexed variable can be an argument to a function in
exactly the same way that any variable of the array base
type can be an argument
double i, n, a[10];
20
Passing The Entire Array as an argument
(one dimensional)
21
22
23
24
25
26
char name[20];
N.B 1.we need not initialize all the available space (20)
2.the string will terminate by the null character ‘\0’
Initialization
char my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
or char my_string[]=”Hello”
once initialized we can not use the following:
my_string[]=”hello”;
my_string=”Hello”;
my_string[]={‘H’,’e’,’l’,’l’,’o’,’\0’’};
but we can say
my_string [0]=’H’;
my_string[3]=’k’;
cout<< my_string[2];
cout<<my_string; 27
With cin space will not be read.
Hence use the following
cin.getline(char buffer[], int )
28
Eg. // cin with strings
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char mystr[100];
cout<<"What's your name? ";
cin.getline(mystr,100);
cout<<"Hello "<<mystr<< ".\n";
cout<<"What is your favorite team? ";
cin.getline(mystr,100);
cout<<"I like "<<mystr<<" too!\n";
return 0;
}
29
String Manipulations:
i)strlen (char buffer[] ) =>returns the length without the null character ‘\0’;
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
char name[50];
cout<<"Enter Your Name:"" ";
cin>>name;
cout<<"The length of Your Name is“<<" "<<strlen(name)<<endl;
return 0;
} 30
String concatenation
ii)strcat(str1, str2) =>to concatenate or merge two strings
NB. 1.The first string str1 hold the concatenated string
2.the size of the first string must be large enough to hold both
strings.
#include <iostream>
#include <string.h>
using namespace std;
int main ()
{
char str1[13]="Hello ";
char str2[]="World!";
cout<<"Before: "<<str1<<endl;
cout<<strcat(str1, str2)<<endl;
cout<<"After: "<<str2<<endl;
return 0;
} 31
String compare
iii)strcmp(str1,str2) => for lexical/alphabetical
comparison rule:
• 0 if the two strings are equal
• negative if the first string comes before
the second in alphabetical order
• positive if the first string comes after
the second in alphabetical order
32
String copy
34
Eg.
int num = atoi("4123"); //num = 4123
long lnum = atol ("12345678");
float fnum = atof ("2.34");
itoa (not standard): converts an integer to a
string. It accepts three arguments
argument1 - the integer to be converted
argument2 - the string to hold the converted
result
argument3 - the base (8, 10, or 16)
char strnum[4];
35
36
37
Example Using at
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
string n = "Kebede";
cout<<n.at(0)<<endl;
cout<<n.size()<<endl;
cout<<n.at(n.size()-1)<<endl;
return 0;
} 38
Thank U all!!!
39