CHAPTER 4
Arrays and Strings
Arrays
Literal way Memory case
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.
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
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.
Various types of initializations:
int data[5]={16,2,77,120,9};
0 1 2 3 4
16 2 77 120 9
data
int data[ ]={16,2,77,120,9};// we can leave the size in the rectangular
brace if it is expressed in curly brace.
int data[5]={16,2,77}// the rest of 2 values are 0.
int data[5]={0};// all element will be initialized 0.
Initialization is not the same as an assignment.
Arrays can be initialized, but they cannot be assigned:
float a[7] = { 22.2,44.4,66.6 };
float b[7] = { 33.3,55.5,77.7 };
b=a; //ERROR: arrays cannot be assigned!
Nor can an array be used to initialize another
array:
float a[7] = { 22.2,44.4,66.6 };
float b[7] = a; // ERROR: arrays cannot be used as
initializers!
Accessing the values of an array.
Elements of array are accessed using index.
Syntax: name[index]
NB: In c++ indexing always starts from 0.
For the above are the name which we can use to
refer to each element is the following:
da[5] ={16,2,77,120,9};
da[0] da[1] da[2] da[3] da[4]
16 2 77 120 9
//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];
A program calculate the sum and average of maximum of 20 numbers entered by the user.
#include<iostream>
using namespace std;
const int max=20;
void main()
{ 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<<"average is ="<<average; }}
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
#include <iostream.h>
int main()
{ // Declare the members of the array
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int find, 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; }
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.
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.
• Example
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}}
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;
void 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]; // c= a+b
for( i=0;i<row;i++)
for(j=0;j<col;j++) c[i][j]=a[i][j]+b[i][j];
cout<<"a+b=\n";
for( i=0;i<row;i++)
char name[20];
N.B [Link] need not initialize all the available space (20)
[Link] 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;
cin>> my_string;
With cin space will not be read.
Hence use the following
[Link](char buffer[],int )
Address to store input Max length
Eg. // cin with strings
#include <iostream>
#include <string>
using namespace std;
int main () {
char mystr[100];
cout << "What's your name? ";
[Link](mystr,100);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? ";
[Link](mystr,100); cout << "I like " << mystr
<< " too!\n"; return 0; }
String Manipulations:
Functions to manipulate strings:
Requires string header file in standard c++ and string.h in pre-standard c++.
i)strlen (char buffer[] ) =>retuns the length without the null character ‘\0’;
int main () {
char name[50] = "Abebe Kebede";
int len1, len2;
len1 = strlen(name); // 12
len2 = strlen("Hello World"); // 11
cout<<len1<<" "<<len2;
return 0; }
String concatenation
ii)strcat(str1, str2) =>to concatenate or merge two strings
NB. [Link] first string str1 hold the concatenated string
[Link] size of the first string must be large enough to hold both
strings.
int main()
{char str1[13] = "Hello ";
char str2[] = "World!"
cout<<"Before: "<<str1<<endl;
cout<<"Before: "<<str1<<endl;
strcat(str1, str2);
cout<<"After: "<<str1<<endl;
cout<<"After: "<<str2<<endl;}
String compare
iii)strcmp(str1,str2) => for lexical/alphabetica
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
String copy
iv) strcpy(str1,str2): is used to copy one string to another.
This is because arrays can't be copied using
the assignment operator (=).
Example:
char str1[20];
char str2[] = "Second String";
strcpy(str1, str2);
cout<<"str1: "<<str1<<endl;
strcpy(str2, "Another String");
cout<<"str2: "<<str2<<endl;
String/Numeric Conversion
i)atoi= string to int i)itoa int to string
ii)atof=string to float ii)ftoi float to string
iii)atoll=string to long iii)ltoa long to string
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];
itoa(102, strnum, 10);
Thank U all!!!