0% found this document useful (0 votes)
1 views

Chapter 4 Array

Chapter 4 of the Computer Programming course focuses on arrays and strings in C++. It explains the concept of arrays, including one-dimensional and two-dimensional arrays, their declaration, initialization, and various operations such as searching, sorting, and matrix manipulation. Additionally, it covers strings as character arrays, their initialization, and comparison methods.

Uploaded by

Khalil Etana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Chapter 4 Array

Chapter 4 of the Computer Programming course focuses on arrays and strings in C++. It explains the concept of arrays, including one-dimensional and two-dimensional arrays, their declaration, initialization, and various operations such as searching, sorting, and matrix manipulation. Additionally, it covers strings as character arrays, their initialization, and comparison methods.

Uploaded by

Khalil Etana
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Course Title: Computer Programming

Course Code: ECEg1052


Chapter 4: Array and String

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

1.1 One Dimensional Arrays:


In one dimensional array, the array contains only one dimension in declaration. It means in this we
can work with either a row or a column only.

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;
}

C++ Array Out of Bounds


If we declare an array of size 10, then the array will contain elements from index 0 to 9. However, if
we try to access the element at index 10 or more than 10, it will result in Undefined Behaviour (array
index out of bound error).

2|Page
Course Title: Computer Programming
Course Code: ECEg1052
Chapter 4: Array and String

Example 3: Linear Search program in C++


What is Linear Search?
To search any element, present inside the array in C++ programming using linear search technique,
we have to ask from user to enter any 10 numbers as 10 array elements and then ask to enter a
number to search as shown in the program given below.

#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;
}

Example 4: Program to find and print largest number in an array.

#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

Example 5: Program to print reverse of an array.


#include<iostream>
using namespace std;
int main()
{
int arr[10], i;
cout<<"Enter 10 Array Elements: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nThe Original Array is:\n";
for(i=0; i<10; i++)
cout<<arr[i]<<" ";
cout<<"\n\nThe Reverse of Given Array is:\n";
for(i=(10-1); i>=0; i--)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}

Example 6: Program to sort an array in ascending order.

#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

1.2 Two Dimensional Arrays:


In two dimensional arrays, the array contains two dimensions in declaration. It means in this we can
work with both row and column.
For better understanding the concept of a two-dimensional array we will discuss the concept for
matrix and its applications because a matrix is a combination of both row and column.
The array will have dimension1 x dimension2 elements of the same type and can be thought of as an
array of arrays. The first index indicates which of dimension1 subarrays to access, and then the
second index accesses one of dimension2 elements within that subarray. Initialization and access thus
work similarly to the one-dimensional case:
The array can also be initialized at declaration in the following ways:
Type ArrayName[dimension1][dimension2];

int twoDimArray[2][4] = { 6, 0, 9, 6, 2, 0, 1, 1 };
int twoDimArray[2][4] = { { 6, 0, 9, 6 } , { 2, 0, 1, 1 } };

Example 7: Program to insert and display the values for matrix

#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

Example 8: Program to add two 3*3 matrices.

#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;
}

Example 9: Program to transpose a matrix.

#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:

Example 10: Program to understand simple string (character array).

#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

Example 11: Program to display a string entered by user.

#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;
}

What if User enters Strings of Unequal length?

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.

Example 13: Program to Compare Two Strings

#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

C++ supports a wide range of functions that manipulate null-terminated strings −

strcpy(s1, s2); Copies string s2 into string s1.


strcat(s1, s2); Concatenates string s2 onto the end of string s1.
strlen(s1); Returns the length of string s1.
strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

Example 14: Program to understand string functions.

#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;

// concatenates str1 and str2


strcat( str1, str2);
cout << "strcat( str1, str2): " << str1 << endl;

// total lenghth of str1 after concatenation


len = strlen(str1);
cout << "strlen(str1) : " << len << endl;

return 0;
}

Example 15: Program to Reverse a String


#include<iostream>
#include<stdio.h>
using namespace std;
int main()

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;
}

Example 16: Program to Swap Two Strings using Library Function


#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
char strOne[50], strTwo[50], strTmp[50];
cout<<"Enter the First String: ";
gets(strOne);
cout<<"Enter the Second String: ";
gets(strTwo);
cout<<"\n String before Swap: \n";
cout<<"First String = "<< strOne<<"\t Second String = "<< strTwo;
strcpy(strTmp, strOne);
strcpy(strOne, strTwo);
strcpy(strTwo, strTmp);
cout<<"\n \n String after Swap: \n";
cout<<"First String = "<< strOne<<"\t Second String = "<< strTwo;

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy