Chapter 4 Array
Chapter 4 Array
Chapter 4
Array and String
1. Array
So far, we have used variables to store values in memory for later reuse. We now explore a means to
store multiple values together as one unit, the array.
An array is a fixed number of elements of the same type stored sequentially in memory. Therefore, an
integer array holds some number of integers; a character array holds some number of characters, and
so on. The size of the array is referred to as its dimension. To declare an array in C++, we write the
following:
Type ArrayName[dimension];
To declare an integer array named arr of four elements, we write int arr[4];
The elements of an array can be accessed by using an index into the array. Arrays in C++ are zero-
indexed, so the first element has an index of 0. So, to access the first, second and third element in
arr, we write arr[0], arr[1] and arr[2] respectively. The value returned can then be used just like any
other integer.
Like normal variables, the elements of an array must be initialized before they can be used; otherwise
we will almost certainly get unexpected results in our program. There are several ways to initialize
the array. One way is to declare the array and then initialize some or all of the elements:
int arr[4];
arr[0] = 6;
arr[1] = 0;
arr[2] = 9;
arr[3] = 6;
Another way is to initialize some or all of the values at the
time of declaration:
int arr[4] = { 6, 0, 9, 6 };
Sometimes it is more convenient to leave out the size of the array and let the compiler determine the
array's size for us, based on how many elements we give it:
int arr[] = { 6, 0, 9, 6, 2, 0, 1, 1 };
Here, the compiler will create an integer array of dimension 8.
Example 1: Define an array and insert vales into an array and display the values from the
array.
#include<iostream>
using namespace std;
void main()
{
int i,j,n,a[10];
cout<< ”Enter the size of the array”;
1|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
cin>>n;
cout<< ”Please insert the values into array”;
for(i=0 ; i<n ; i++)
{
cout<< ”insert value”;
cin>>a[i];
}
cout<< ”The values in array are ……”;
for(i=0 ; i<n ; i++)
{
cout<<a[i];
}
}
Array can be categorize based on the number of dimensions used in the array declaration into three
categories.
1. One Dimensional Arrays
2. Two Dimensional Arrays
3. Multi-Dimensional Arrays
Example 2: Display Sum and Average of Array Elements Using for Loop
#include<iostream>
using namespace std;
int main()
{
int arr[10], i, sum=0, avg=0;
cout<<"Enter 10 array elements: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nThe array elements are: \n";
for(i=0; i<10; i++)
cout<<arr[i]<<" ";
for(i=0; i<10; i++)
{
cin>>arr[i];
sum = sum + arr[i];
}
cout<<"\n\n Sum of all elements is: "<< sum;
avg = sum/10;
cout<<"\n And average is: "<< avg;
return 0;
}
2|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
#include<iostream>
using namespace std;
int main()
{
int arr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int arr[100], total, large, i;
cout<<"Enter the Size (max. 100): ";
cin>>total;
cout<< "Enter " << total << "Array Elements: ";
for(i=0; i < total; i++)
cin>>arr[i];
large = arr[0];
for(i=1; i<total; i++)
{
if(large < arr[i])
large = arr[i];
}
cout<<"\n Largest Number = " << large;
cout<<endl;
return 0;
}
3|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
#include<iostream>
using namespace std;
int main()
{
int n, i, arr[50], j, temp;
cout<<"Enter the Size (max. 50): ";
cin>>n;
cout<<"Enter "<<n<<" Numbers: ";
for(i=0; i<n; i++)
cin>>arr[i];
cout<<"\n Sorting the Array using Bubble Sort Technique..\n";
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
cout<<"\nArray Sorted Successfully!\n";
cout<<"\nThe New Array is: \n";
for(i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
4|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
int twoDimArray[2][4] = { 6, 0, 9, 6, 2, 0, 1, 1 };
int twoDimArray[2][4] = { { 6, 0, 9, 6 } , { 2, 0, 1, 1 } };
#include<iostream>
using namespace std;
int main()
{
int i,j,n,m,a[10][10];
cout<<”Enter the order of the matrix”;
cin>> n >> m;
cout<<”Please insert the values into matrix”;
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
cout<< ”insert value”;
cin>>a[ i ][ j ];
}
}
cout<< ”The Given Matrix is \n”;
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
cout>>a[ i ][ j ]<<”\t”;
}
cout<<”\n”;
}
return 0;
}
5|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
#include<iostream>
using namespace std;
int main()
{
int mat1[3][3], mat2[3][3], i, j, mat3[3][3];
cout<<"Enter Elements of First Matrix: ";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>mat1[i][j];
}
cout<<"Enter Elements of Second Matrix: ";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>mat2[i][j];
}
cout<<"\nAdding the Two Given Matrix...\n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
cout<<"Addition Result of Two Given Matrix is:\n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<mat3[i][j]<<" ";
cout<<endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int mat[3][3], i, j, matT[3][3];
cout<<"Enter 9 Elements for 3*3 Matrix: ";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>mat[i][j];
}
cout<<"\nOriginal Matrix is:\n";
for(i=0; i<3; i++) {
6|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
for(j=0; j<3; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
// copying the transpose of given matrix to matT[][]
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
matT[j][i] = mat[i][j];
}
cout<<"\nTranspose of Given Matrix is:\n";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cout<<matT[i][j]<<" ";
cout<<endl;
}
cout<<endl;
return 0;
}
2. Strings
String literals such as “Hello, world!” are actually represented by C++ as a sequence of
characters in memory. In other words, a string is simply a character array and can be manipulated
as such.
Consider the following program:
#include <iostream>
using namespace std;
int main()
{
char helloworld[] = { 'H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0' };
cout << helloworld << endl;
return 0;
}
This program prints Hello, world! Note that the character array hello world ends with a special
character known as the null character. This character is used to indicate the end of the string.
Character arrays can also be initialized using string literals. In this case, no null character is
needed, as the compiler will automatically insert one:
char helloworld[] = “Hello, world!”;
7|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
#include <iostream>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
cin >> str;
cout << "You entered: " << str << endl;
cout << "\nEnter another string: ";
cin >> str;
cout << "You entered: "<<str<<endl;
return 0;
}
Example 12: Program to Compare Two Strings (strings with equal length)
#include<iostream>
using namespace std;
int main()
{
char str1[50], str2[50];
int i=0, chk=0;
cout<<"Enter the First String: ";
cin>>str1;
cout<<"Enter the Second String: ";
cin>>str2;
while(str1[i]!='\0' || str2[i]!='\0')
{
if(str1[i]!=str2[i]) {
chk = 1;
break;
}
i++;
}
if(chk==0)
cout<<"\nStrings are Equal";
else
cout<<"\nStrings are not Equal";
cout<<endl;
return 0;
}
8|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
Program given below first finds the length of string and then checks whether length of both strings
are equal or not. If it is equal, then will proceed to compare the strings. Otherwise print a message
like unequal length.
#include<iostream>
using namespace std;
int main()
{
char str1[50], str2[50];
int i, chk=0, len1=0, len2=0;
cout<<"Enter the First String: ";
cin>>str1;
cout<<"Enter the Second String: ";
cin>>str2;
i=0;
while(str1[i]!='\0') {
len1++;
i++;
}
i=0;
while(str2[i]!='\0') {
len2++;
i++;
}
if(len1==len2) {
i=0;
while(str1[i]!='\0' || str2[i]!='\0') {
if(str1[i]!=str2[i]) {
chk = 1;
break;
}
i++;
}
if(chk==0)
cout<<"\nStrings are Equal";
else
cout<<"\nStrings are not Equal";
}
else
cout<<"\nString Length must has to be same, to Compare!";
cout<<endl;
return 0;
}
The individual characters in a string can be manipulated either directly by the programmer or by
9|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
using special functions provided by the C++ libraries. These can be included in a program through
the use of the #include directive. Of particular note are the following:
• cctype (ctype.h): character handling
• cstdio (stdio.h): input/output operations
• cstdlib (stdlib.h): general utilities
• cstring (string.h): string manipulation
#include <iostream>
#include <cstring>
using namespace std;
int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
// copy str1 into str3
strcpy( str3, str1);
cout << "strcpy( str3, str1) : " << str3 << endl;
return 0;
}
10 | P a g e
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
{
char str[200], strTemp[200];
int len, i=0;
cout<<"Enter the String: ";
gets(str);
while(str[i]!='\0')
i++;
len = i;
strTemp[len] = '\0';
len--;
i = 0;
while(str[i]!='\0')
{
strTemp[len] = str[i];
i++;
len--;
}
i=0;
while(strTemp[i]!='\0')
{
str[i] = strTemp[i];
i++;
}
cout<<"\nReverse = "<<str;
cout<<endl;
return 0;
}
11 | P a g e
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String
cout<<endl;
return 0;
}
12 | P a g e