0% found this document useful (0 votes)
4 views62 pages

Understanding Arrays in C++ Programming

Chapter 5 covers arrays, including their declaration, memory layout, and access methods. It explains one-dimensional and two-dimensional arrays, initialization techniques, and how to process array contents. The chapter also includes several example programs demonstrating array usage in C++.

Uploaded by

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

Understanding Arrays in C++ Programming

Chapter 5 covers arrays, including their declaration, memory layout, and access methods. It explains one-dimensional and two-dimensional arrays, initialization techniques, and how to process array contents. The chapter also includes several example programs demonstrating array usage in C++.

Uploaded by

samubiraga4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 5

Arrays
5.1 Introduction
▪ An array is a group of items that can be
identified as similar because they are of the
same nature.
▪ Arrays come in two flavors: one
dimensional and multi-dimensional arrays
▪ Array values are stored in adjacent memory
locations
Declaring array
▪ Like any other variable, the syntax of declaring
an array is:
dataType ArrayName[dimension]
▪ The array is first identified by its kind, which
could be a char, an int, a float, etc; followed by
its name that follows the C++ naming rules. The
name is then followed by square brackets that
specify the dimension of the array or its size.
example
▪ int age[12]; declares a group or array of 12
values, each one being an integer.
Array - Memory Layout
▪ The definition:
int tests[5];
allocates the following memory:

first second third fourth fifth


element element element element element
Array Terminology
In the definition int tests[5];
▪ int is the data type of the array elements
▪ tests is the name of the array
▪ 5, in [5], is the size declarator. It shows the
number of elements in the array.
▪ The size of an array is (number of elements) * (size
of each element)
▪ Examples:
int tests[5] is an array of 20 bytes,
assuming 4 bytes for an int
long double measures[10]is an array of 80
bytes, assuming 8 bytes for a long double
5.2 Accessing Array Elements
▪ The individual elements of an array are
assigned unique subscripts.
▪ These subscripts are used to access the
elements.
▪ Subscripts start at 0
subscripts:
0 1 2 3 4
Accessing Array Elements
▪ Array elements can be used as regular
variables:
tests[0] = 79;
cout << tests[0];
cin >> tests[1];
tests[4] = tests[0] + tests[1];
▪ Arrays must be accessed via individual
elements:
cout << tests; // not legal
Accessing Array Contents
▪ Can access element with constant subscript:
cout << tests[3] << endl;
▪ Can use integer expression as subscript:
for (i = 0; i < 5;i++)
cout << tests[i] << endl;
Program 5-1
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the
// values.
#include <iostream>
using namespace std;

int main()
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
Program continues
cin >> hours[4];
cin >> hours[5];
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
return 0;
}
Program 5-2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include <iostream>
using namespace std;

int main()
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
for (int count = 0; count < 6; count++)
cin >> hours[count];
cout << "The hours you entered are:";
for (count = 0; count < 6; count++)
cout << " " << hours[count];
cout << endl;
return 0;
}
Program 5-3
// This program unsafely accesses an area of memory by writing
// values beyond an array's boundary.
// WARNING: If you compile and run this program, it could cause
// the computer to crash.
#include <iostream>
using namespace std;

int main()
{
short values[3]; // An array of 3 short integers.
cout << "I will store 5 numbers in a 3 element array!\n";
for (int count = 0; count < 5; count++)
values[count] = 100;
cout << "If you see this message, it means the computer\n";
cout << "has not crashed! Here are the numbers:\n";
return 0;
}
5.3 Array Initialization
▪ Can be initialized during program execution with
assignment statements:
tests[0] = 79;
tests[1] = 82; // etc.
▪ Can be initialized at array definition with an
initialization list:
int tests[5] = {79,82,91,77,84};
▪ Initialization list cannot exceed array size
▪ Global array → all elements initialized to 0
▪ Local array → all elements uninitialized by default
Partial Array Initialization
▪ If array is initialized at definition with fewer
initial values than the size declarator of the
array, the remaining elements will be set to 0:
int tests[5] = {79, 82};
▪ Initial values used in order; cannot skip over
elements to initialize noncontiguous range
Implicit Array Sizing
▪ Can determine array size by the size of the
initialization list:
short quizzes[]={12,17,15,11};
12 17 15 11

▪ Must use either array size declarator or


initialization list at array definition
Initializing With a String
▪ Character array can be initialized by enclosing
string in " ":
char fName[6] = "Henry";
▪ Must leave room for \0 at end of array
▪ If initializing character-by-character, must add
in \0 explicitly:
char fName[6] =
{ 'H', 'e', 'n', 'r', 'y', '\0'};
Program 5-5
// This program uses an array of ten characters store
the first ten letters of the alphabet. The ASCII
codes of the characters are displayed.
#include <iostream>
using namespace std;

int main()
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};

cout << "Character" << "\t" << "ASCII Code\n";


cout << "--------" << "\t" << "----------\n";
for (int count = 0; count < 10; count++)
{
cout << letters[count] << "\t\t";
}
return 0;
}
5.4 Processing Array
Contents
▪ Array elements can be treated as ordinary
variables of the same type as the array
▪ When using ++, -- operators, don’t confuse
the element with the subscript:
tests[i]++; // add 1 to tests[i]
tests[i++]; // increment i, no
// effect on tests
Array Assignment
To copy one array to another,
▪ don’t try to assign one array to the other:
newTests = tests;
▪ assign element-by-element:
for (i=0; i<5; i++)
newTests[i] = tests[i];
Display the Contents of
an Array
▪ Can display character array by using its name:
cout << fName << endl;
▪ For other types of arrays, must go element-by-
element:
for (i=0; i<5; i++)
cout << tests[i] << endl;
Sum of Array Elements
▪ Use a simple loop to add together array
elements:
int tnum[5];
float average, sum = 0;
for(tnum = 0; tnum < 5; tnum++)
sum += tests[tnum];
▪ Once summed, can compute average:
average = sum/5;
Program 5-6

//program to find the smallest number


#include <iostream>
using namespace std;
#define n 10
int main()
{ int i,small, balance[n]={10,4,30,40,60,2,
24,0,3,5};
small = balance[0];
//loop for displaying array content....
for(i=0; i<n; i++)
cout<<balance[i]<<" ";
Cont..
//Another loop for comparing...
for(i=1; i<n; i++)
{
if(small > balance[i])
small = balance[i];
}
cout<<"The smallest value in the given
array is = "<<small<<endl;
return 0;
}
Program 5-7

//Simple sorting program that sort a list


of n integer numbers (ascending)
#include <iostream>
using namespace std;
#define maxsize 100
int main()
{
int temp, i, j, n, list[maxsize];
cout<<"\nEnter your list size: ";
cin>>n;
Cont…
//prompting the data from user store in the list
for(i=0; i<n; i++)
{
cout<<"Enter list's element #"<<i<<"-->";
cin>>list[i];
}
//do the sorting...
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(list[i] > list[j])
{
Cont…
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
cout<<"\nSorted list, ascending: ";
for(i=0; i<n; i++)
cout<<" "<<list[i];
cout<<endl;
return 0;
}
Program 5-8

//Program to calculate Sum and Average of Marks


and //validate also
#include<iostream>
using namespace std;
int main()
{
int m[5],i,sum=0,avg;
cout<<"Enter the marks of five subjects=";
for(i=0;i<=4;i++)
cin>>m[i];
for(i=0;i<=4;i++)
{
Cont…

if(m[i]>100)
{
cout<<"Invalid\n";
break;
}
else
sum=sum+m[i];
}
cout<<"Sum="<<sum;
avg=sum/5;
cout<<"Avg="<<avg;
return 0;
}
5.6 Arrays as Function
Arguments
▪ To pass an array to a function, just use the array
name:
showScores(tests);
▪ To define a function that takes an array
parameter, use empty [] for array argument:
void showScores(int []);
// function prototype
void showScores(int tests[])
// function header
Arrays as Function Arguments
▪ When passing an array to a function, it is common to
pass array size so that function knows how many
elements to process:
showScores(tests, 5);
▪ Array size must also be reflected in prototype,
header:
void showScores(int [], int);
// function prototype
void showScores(int tests[], int size)
// function header
Program 5-9
// This program demonstrates that an array element is passed to a function like any
other variable.
#include <iostream>
using namespace std;
void ShowValue(int); // Function prototype

int main()
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int Cycle = 0; Cycle < 8; Cycle++)
ShowValue(collection[Cycle]);
return 0;
}

void ShowValue(int Num)


{
cout << Num << " ";
}
Program 5-10
// This program demonstrates an array being passed to a
function.
#include <iostream>
using namespace std;
void showValues(int []); // Function prototype

int main()
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
showValues(collection); // Passing address of array
return 0;
}
void showValues(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
Program 5-11
// This program demonstrates an array being passed to a function.
#include <iostream>
using namespace std;
void showValues(int []); // Function prototype

int main()
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16};
showValues(set1);
cout << endl;
showValues(set2);
return 0;
}

void showValues(int nums[])


{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
Program 5-12
// This program uses a function that can display the contents
// of an integer array of any size.
#include <iostream>
using namespace std;
void showValues(int [], int); // Function prototype

int main()
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[4] = {2, 4, 6, 8};
int set3[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
showValues(set1, 8);
cout << endl;
showValues(set2, 4);
cout << endl;
showValues(set3, 12);
return 0;
}
void showValues(int nums[], int elements)
{
for (int index = 0; index < elements; index++)
cout << nums[index] << " ";
}
Modifying Arrays in Functions
▪ Array names in functions are similar to
reference variables – changes made to array
in a function are reflected in actual array in
calling function
Program 5-13
// This program uses a function that doubles the contents of
// the elements within an array.
#include <iostream>
using namespace std;
void doubleArray(int [], int); // Function prototype
const int arraySize = 12;

int main()
{
int set[arraySize] = {1, 2, 3, 4, 5,6,7, 8, 9, 10, 11, 12};
cout << "The arrays values are:\n";
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
doubleArray(set, arraySize);
cout << "After calling doubleArray, the values are:\n";
Program continues
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
return 0;
}

void doubleArray(int nums[], int size)


{
for (int index = 0; index < size; index++)
nums[index] *= 2;
}
5.7 Two-Dimensional Arrays
▪ A two-dimensional array is like several
identical arrays put together. It is useful for
storing multiple sets of data.
▪ Use two size declarators in definition:
int exams[4][3];
▪ First declarator is number of rows; second is
number of columns
Two-Dimensional Array
Representation
int exams[4][3];
columns
exams[0][0] exams[0][1] exams[0][2]
r
o exams[1][0] exams[1][1] exams[1][2]
w exams[2][0] exams[2][1] exams[2][2]
s
exams[3][0] exams[3][1] exams[3][2]
▪ Use two subscripts to access element:
exams[2][2] = 86;
Initialization at Definition
▪ Two-dimensional arrays are initialized row-by-
row:
int exams[2][2] = { {84, 78},
84 78 {92, 97} };
92 97
▪ Can omit inner { }, some initial values in a
row – array elements without initial values
will be set to 0 or NULL
Passing Two-dimensional Arrays to
Functions
▪ Use array name as argument in function call:
getExams(exams, 2);
▪ Use empty [] for row, size declarator for column
in prototype, header:
void getExams(int [][2], int);
// prototype
void getExams(int exams[][2], int rows)
// header
Program 5-14
// This program demonstrates a two-dimensional array.

#include <iostream>
using namespace std;
int main()
{
float sales[3][4]; // 2D array, 3 rows and 4 columns.
float totalSales = 0; // To hold the total sales.
int r, c; // Loop counters.
for (r = 0; r< 3; r++)
{
Program continues
for (c = 0; c < 4; c++)
{
cout << “row " << (r + 1);
cout << ", column " << (c + 1) << ": $";
cin >> sales[r][c];
}
cout << endl; // Print blank line.
}
// Nested loops to add all the elements.
for (r = 0; r < 3; r++)
for (c = 0; c < 4; c++)
totalSales += sales[r][c];
cout << "The total sales for the company are: $";
cout << totalSales << endl;
return 0;
}
Program 5-14

//Program to Print Square of given Matrix using


//Multidimensional Array.
#include<iostream>
#define MAX_ROWS 3
#define MAX_COLS 4
using namespace std;
void print_square(int [ ] );
int main()
{
int row;
int num [MAX_ROWS][MAX_COLS] ={{0,1,2,3},
{4,5,6,7},{8,9,10,11} };
Cont…

for(row=0; row< MAX_ROWS; row++)


print_square(num[row]);
return 0;
}
void print_square(int x[ ])
{
int col;
for (col = 0; col< MAX_COLS; col++)
cout<<"\t"<<x[col] * x[col];
cout<<"\n";
}
Program 5-15

// Program to Transpose the matrix using Multidimensional array.


#include<iostream>
using namespace std;
int main()
{
int a[4][4],i,j,b;
for(i=0;i<4;i++)
{
cout<<"\nEnter elements of row "<<i+1<<" of Matrix:\n";
for(j=0;j<4;j++)
cin>>a[i][j];
}
Cont…

for(i=0;i<4;i++)
{ for(j=i+1;j<4;j++)
{ b=a[i][j];
a[i][j]=a[j][i];
a[j][i]=b; } }
cout<<"\n Transposed Matrix:\n\n";
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
cout<<a[i][j]<<" ";
cout<<"\n"; }
return 0; }
5.8 Array of Strings
▪ Use a two-dimensional array of characters
as an array of strings:
char students[3][10] =
{ "Ann", "Bill", "Cindy" };
▪ Each row contains one string
▪ Can use row subscript to reference the string:
cout << students[i];
Program 5-16
// This program displays the number of days in each month.
// It uses a two-dimensional character array to hold the
// names of the months and an int array to hold the number
// of days.
#include <iostream>
using namespace std;
int main()
{
char months[12][10] = {"January", "February", "March",
"April", "May", "June",
"July", "August", "September”,
"October", "November","December"};
int days[12] ={ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << months[count] << " has ";
cout << days[count] << " days.\n";
}
return 0;
}
5.9 STANDARD C STRING FUNCTIONS

▪ The C header file <cstring>, also called the C-


String Library, includes a family of functions that
are very useful for manipulating C-strings.
strlen() function
▪ The strlen() function takes one argument, which is the
string you are considering. The function returns the
number of characters of the string. syntax : int
strlen(char Value);
▪ Example
#include <iostream>
#include <cstring>
int main()
{ char s[] = "ABCDEFG";
cout <<strlen(s) << endl;
return 0;
}
strcat() Function

▪ syntax: char strcat(char s2, char s1);


▪ takes two arguments.
▪ appends the C-string s2 onto the end of s1.
▪ It really ends up changing the destination string
by appending the second string at the end of the
first string.
Cont…

int main()
{ char s1[] = "ABCDEFG";
char s2[] = "XYZ";
cout << "Before strcat(s1,s2):\n";
cout <<s1<<strlen(s1) << endl;
cout << s2 <<strlen(s2) << endl;
strcat(s1,s2);
cout << "After strcat(s1,s2):\n";
cout <<s1<<strlen(s1) << endl;
cout <<s2<<strlen(s2) << endl;
}
strncat() function
▪ allows you to specify the number of characters from the source
string that you want to append to the destination string.
▪ syntax: char strncat(char s2, char s1, int n);
example
int main()
{
char Make[] = "Ford ";
char Model[] = "Explorer";
cout << "Originally, Make = " << Make;
strncat(Make, Model, 3);
cout << "\n\nAfter concatenating, Make = " << Make;
return 0;
}
strcpy() function
▪ used to copy one string into another string. or to
replace one string with another.
▪ syntax :char strcpy(char s2, char s1e);
▪ This function takes two arguments. The call
strcpy(s1,s2) copies C-string s2 into C-string s1.
▪ There are two scenarios suitable for the strcpy()
function: To replace an existing string or to initialize
a string.
▪ Char carName[20]
▪ strcpy(CarName, "Toyota Camry");//initializing a
string
Program 5-17

int main()
{
char carName1[] = "Ford Escort";
char carName2[] = "Toyota 4-Runner";
cout << "The String Copy Operation";
cout << "\nFirst Car: " << carName1;
cout << "\nSecond Car: " << carName2;
strcpy(carName2, carName1);
cout << "\n\nAfter using strcpy()...";
cout << "\nFirst Car: " << carName1;
cout << "\nSecond Car: " << carName2 << endl;
return 0;
}
strncpy() Function
▪ allows you to specify the number of characters
that the compiler would copy from the source
string.
▪ syntax:char strncpy(char s2, char s1, int n);
▪ n specifies the number of characters that will be
copied from the Source string.
Program 5-8
int main()
{
char CarName1[] = "Ford Escort";
char CarName2[] = "Toyota 4-Runner";
cout << "The String Copy Operation";
cout << "\nFirst Car: " << CarName1;
cout << "\nSecond Car: " << CarName2;
strncpy(CarName2, CarName1, 8);
cout << "\n\nAfter using strncpy() for 8characters";
cout << "\nFirst Car: " << CarName1;
cout << "\nSecond Car: " << CarName2 << endl;
return 0;
}
strcmp() Function
▪ The strcmp() function compares two strings and
returns an integer as a result of its comparison.
syntax: int strcmp(char S1, char S2);
It returns
▪ A negative value if S1 is less than S2
▪ 0 if S1 and S2 are equal
▪ A positive value if S1 is greater than S2
Cont…
int main()
{char *FirstName1 = "Andy";
char *FirstName2 = "Charles";
char *LastName1 = "Stanley";
char *LastName2 = "Stanley";
int Value1 = strcmp(FirstName1, FirstName2);
int Value2 = strcmp(LastName1, LastName2);
cout << "The result of comparing " << FirstName1<<
" and " << FirstName2 << " is\t" << Value1 << endl;
cout << "The result of comparing " << LastName1<< " and
" << LastName2 << " is\t" << Value2;
return 0;
}
strncmp() Function
▪ compares two strings using a specified number of characters and
returns an integer as a result of its findings.
▪ Its syntax is:int strncmp(char S1, char S2, int Number);
▪ This function takes three arguments. The first two arguments are the
strings that need to be compared. The 3rd argument specifies the
number of characters considered for the comparison. It returns
A negative value if S1 is less than S2
0 if S1 and S2 are equal
A positive value if S1 is greater than S2
5.10 Arrays with Three or More
Dimensions
▪ Can define arrays with any number of
dimensions:
short rectSolid[2][3][5];
▪ When used as parameter, specify all but 1st
dimension in prototype, heading:
void getRectSolid(short [][3][5]);

You might also like