Chapter 4_Array (1)
Chapter 4_Array (1)
Arrays
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
Declaration Of Arrays
When 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
int x[SIZE] ;
int y[SIZE] ;
x[i] = y[i];
MULTIDIMENSIONAL ARRAYS
C++ also allows an array to have more than one dimension.
int Array[NUMROWS][NUMCOLS];
Initializing Multidimensional Arrays
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
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.*/
Note however:
#include <string>
int main () {
char mystr[100];
cin.getline(mystr,100);
cin.getline(mystr,100);
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
=>to concatenate or merge two strings
NB. 1.Tii)strcat(str1, str2) the first string str1 hold the concatenated
string
2.the size of the first string must be large enough to hold both
strings.
int main()
cout<<"Before: "<<str1<<endl;
cout<<"Before: "<<str2<<endl;
strcat(str1, str2);
cout<<"After: "<<str1<<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
• END OF CHAPTER 4