HAWASSA UNIVERSITY
INSTITUTE OF TECHNOLOGY
FACULTY OF ELECTRICAL ENGINEERING
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
Chapter FOUR[4]: ARRAYS
By: Dejene H.
INTRODUCTION
Ø Array - a collection of a fixed number of components
where all of the components have the same data type
Ø Arrays in general are
– Structures of related data items
– Same name and type (int, char, double, float etc.)
Ø An individual element of an array is identified by its own
unique index (or subscript).
Ø The index must be an integer and indicates the position of the
element in the array
Cont…
ONE DIMENTIONAL ARRAYS
Declaration Of Arrays
vWhen declaring arrays, specify
üData Type of array:-Any data type
üName of array
üNumber of elements(should be
constant number)
Syntax:
type arrayName[arraySize ];
Example:
int list[ 10 ];
float d[ 3284 ];
Accessing Array Elements
Ø An array element is accessed by writing the identifier of the array
followed by the index(subscript ) in square brackets.
Ø first element is at index 0, then the ith element is at index (i-1).
Ø A one-dimensional array is usually processed via a for loop.
ü for giving inputs
ü for accessing values and calculations
ü for displaying
Initializing arrays
q Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
ØArray size must be greater than or equal to the number of
elements in the initialization list.
ØIf the size is greater, initializes rightmost elements to 0
ØBut array index must always be greater than or equal to
the number of elements in the initialization unless error
will occur.
qTo set every element to same value
int n[ 5 ] = { 0 };//or int n[ 5 ] = { };
qIf array size omitted, initializes determine size
int n[] = { 1, 2, 3, 4, 5 };
• 5 initializes, therefore 5 element array
1 // Program :Initializing an array with a declaration.
2 //What is the output of the following program?
3 #include<iostream>
4 #include<iomanip>
5 using namespace std;
6 int main()
7 {
8 int n[ 10]={32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
9 cout <<"Element"<< setw( 13 ) << "Value" << endl;
10 for (int i=0; i<10; i++ )
11 cout <<setw(7)<< i <<setw(13)<<n[i]<< endl;
12 return 0;
13 }
Output:
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Copying Arrays
Ø The assignment operator cannot be applied to array variables:
const int SIZE=10
int x[SIZE] ;
int y[SIZE] ;
x=y; // Error – Illegal
Ø Only individual elements can be assigned using the index operator,
e.g…, x[1] = y[2]
Ø Loop to do copying, one element at a time
for(int i = 0 ; i < SIZE; i++)
x[i] = y[i];
MULTIDIMENSIONAL ARRAYS
q C++ also allows an array to have more than one dimension.
q For example, a two-dimensional array consists of a certain number of rows
and columns:
const int NUMROWS = 3;
const int NUMCOLS = 7;
int Array[NUMROWS][NUMCOLS];
Initializing Multidimensional
Arrays
Ø A two-dimensional array may be processed with a nested for loop:
ü for giving inputs
ü for accessing values and calculations
ü for displaying
for (int Row = 0; Row < NUMROWS; Row++)
for (int Col = 0; Col < NUMCOLS; Col++)
Array[Row][Col] = 0;
}
Coloumn
What is the output of the following program?
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int row=2, column=3;
int array[row][column]={{1,2,3},{4,5,6}};
cout<<"The result is as shown below:"<<endl;
for(int row=0;row<2;row++)
{for(int column=0;column<3;column++)
cout<<array[row][column]<<" ";
cout<<endl;}
return 0;
}
Omitting the Array Size
q If a one-dimensional array is initialized, the size can be omitted as
it can be found from the number of initializing elements:
int x[] = { 1, 2, 3, 4} ;
/* This initialization creates an array of four elements.*/
q Note however:
int x[][] = { {1,2}, {3,4} } ;
// error and is not allowed. and must be written
int x[2][2] = { {1,2}, {3,4}};
Example : What is the output of the ff
program?
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int MyArray[5][2]={{0,0},{1,2},{2,4},{3,6}, {4,8}};
for( int i=0; i<5; i++)
for(int j = 0; j<2;j++)
{
cout<<"MyArray["<<i<<"]["<<j<<"] ="<<setw(10)<<MyArray[i][j];
cout<<endl;
}
return 0;}
Example 1:Matrix addition
Write a c++ program that adds array P and Q?
char name[20];
N.B [Link] need not initialize all the available space (20)
[Link] string will terminate by the null character ‘\0’
q Initialization
char my_string[]={‘H’,’e’,’l’,’k’,’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’’};
q but we can say
my_string [0]=’H’;
my_string[3]=’k’;
cout<< my_string[2];
cout<<my_string;
cin>> my_string;
Cont…
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? “<<endl;
[Link](mystr,100);
cout << "Hello " << mystr << ".\n";
cout << "What is your favorite team? “<<endl;
[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’;
Example
#include<iostream>
#include<string>
using namespace std;
int main()
{char name[50]="Abebe Kebede";
int len1, len2;
len1=strlen(name);
len2=strlen("Hello World");
cout<<len1<<" "<<len2;
return 0; }
String concatenation
=>to concatenate or merge two strings
NB. [Link])strcat(str1, str2) the first string str1 hold the concatenated string
[Link] size of the first string must be large enough to hold both strings.
Example
#include<iostream>
#include<string>
using namespace std;
int main()
{char str1[13]="Hello ";
char str2[]="World!";
cout<<"Before:"<<str1<<endl;
cout<<"Before:"<<str2<<endl;
strcat(str1, str2);
cout<<"After: "<<str1<<endl;
cout<<"After: "<<str2<<endl;
return 0;}
String compare
iii)strcmp(str1,str2)=>forexical/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
#include<iostream>
#include<string>
using namespace std;
int main()
{char str1[20];
char str2[]="Second String";
strcpy(str1, str2);
cout<<"str1: "<<str1<<endl;
strcpy(str2, "Another String");
cout<<"str2: "<<str2<<endl;
return 0;}
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
Cont…
Example
q int num = atoi("4123"); //num = 4123
q long lnum = atoll ("12345678");
q float fnum = atof ("2.34");
q 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);
`
• END OF CHAPTER 4