Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: C++ Programming. No Comments on Arrays and Strings in C++ Programming

This article provides a comprehensive overview of arrays and strings in C++ programming language along with example programs.

 

Arrays

Introduction

An array is a group of elements forming a complete unit. Characteristics of an array are as follows:

  • An array is a collection of elements.
  • All elements in an array are of the same type.
  • Collection of elements forms a complete set.

 

Elements in an array are stored in order and sequentially inside the memory.

 

Need for arrays

 

Think that we have to store five values in a program. We can declare five variables to store those five values as follows:

 

int var1;

int var2;

int var3;

int var4;

int var5;

 

We can declare an array which can store five integers to solve the above problem as follows:

 

int numbers[5] = {0};

 

In the above statement, numbers is the array name and 5 is the number of elements we can store in the array. All the 5 elements in the array will have an initial value of 0 which is specified by {0}.

 

Now, let’s think that we have to store 5000 values. It is inappropriate to declare 5000 variables to store those values. Instead we can declare a single array which can store 5000 values as follows:

 

int numbers[5000] = {0};

 

The arrays which you have seen above are called as static arrays because the number of elements the array contains and its memory is fixed at the compilation time.

 

Declaring and initializing static arrays

 

In C++ the syntax for declaring a static array is as follows:

 

type  array-name[no. of elements];

 

Consider the following example for array declaration:

 

int  nums[10];

 

In the above statement nums is the name of the array which is capable to store 10 integers and the data type of all the elements is int.

 

We can declare and initialize all the elements in the array as shown in the below example:

 

int  nums[5] = {1, 4, 2, 3, 6};

 

We can initialize all the elements in an array to a default value as shown in the below example:

 

int  nums[5] = {10};

 

We can initialize only some of the elements in an array as shown below:

 

int  nums[5] = {2, 6};

 

In the above statement, the first two elements are initialized to 2 and 6. Remaining elements contain garbage value or some compilers might initialize them to 0.

 

We can also leave out the size of array in its declaration. But we have to specify the values as shown below:

 

int  nums[ ] = {2, 4, 6, 8, 10};

 

In the above statement compiler automatically deduces the size of array nums as 5 based on the number of values.

 

We can also initialize array elements individually as shown in below example:

 

int nums[3];

nums[0] = 10;

nums[1] = 20;

nums[2] = 30;

 

Accessing and modifying array elements

 

Elements of an array can be accessed using the index or subscript. The index value of arrays starts from 0. The index of Nth element is N-1. For example index of 5th element is 4. Syntax for accessing an array element is as follows:

 

array-name[index]

 

Consider the following program which demonstrates reading and displaying array elements:

 

#include<iostream>
using namespace std;
int main()
{
	int nums[5] = {0};
	cout<<"Enter five values: ";
	for(int i=0;i<5;i++)
	{
		cin>>nums[i];
	}
	cout<<"Elements in the array are: ";
	for(int i=0;i<5;i++)
	{
		cout<<nums[i]<<" ";
	}
	cout<<endl;
	return 0;
}

Input and output for the above program is as follows:

Enter five values: 2 4 1 5 8
Elements in the array are: 2 4 1 5 8

 

Note: Remember that while accessing elements outside the array bounds does not give any errors. Such access might lead to undesirable behavior and often might lead to program crash. So, it is a good practice to check whether the array access is within the bounds or not.

 

Multidimensional Arrays

 

Until now the arrays we discussed are one-dimensional arrays. C++ also supports storing data in multiple dimensions. A two-dimensional array can represent tabular data i.e., in rows and columns. Syntax for declaring a two-dimensional array is as follows:

 

type  array-name[rows][coulumns];

 

We can initialize a two-dimensional array at the time of declaration itself as shown below:

 

int  data[3][3] = {{1,2,3},{4,5,6},{7,8,9}};

 

In the above statement, data is a two-dimensional array having three rows and three columns. We can imagine a two-dimensional array as an array of arrays. Consider the following program which demonstrates reading and displaying elements in a two-dimensional array:

 

#include<iostream>
using namespace std;
int main()
{
	int data[3][3];
	cout<<"Enter data for three rows and three columns: ";
	for(int i=0;i<3;i++)
	{
		for(int j=0;j<3;j++)
		{
			cin>>data[i][j];
		}
	}
	cout<<"Elements in the array are: "<<endl;
	for(int i=0;i<3;i++)
	{
		for(int j=0;j<3;j++)
		{
			cout<<data[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;
	return 0;
}

Input and output for the above program is as follows:

Enter data for three rows and three columns: 
1 2 3
4 5 6
7 8 9
Elements in the array are: 
1 2 3 
4 5 6 
7 8 9

 

Observe how nested for loops are used to read and print the array elements effectively.

 

Dynamic Arrays

 

Consider you are writing a program to store student records which are bound to increase over time. There is now way to assume the size of the array before hand. In such cases static arrays are a bad choice. Instead, use dynamic arrays.

 

Dynamic arrays can be created in C++ programs using vector class which is available in the header file vector. Since vector uses template syntax and they are not at discussed, let’s look at a program which demonstrates creating and using a vector:

 

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<int> nums(3);
	nums[0] = 1;
	nums[1] = 2;
	nums[2] = 3;
	cout<<"Size of the array is: "<<nums.size()<<endl;
	cout<<"Enter a number to store in the array: ";
	int n;
	cin>>n;
	nums.push_back(n);
	cout<<"New size of the array is: "<<nums.size()<<endl;
	return 0;
}

Input and output for the above program is as follows:

Size of the array is: 3
Enter a number to store in the array: 10
New size of the array is: 4

 

In the above program, size() function returns the size of the vector (array) and push_back() function inserts the given element at the end of the vector (array).

 

Strings

 

It is common in many programs to work with strings. A string is a collection of characters. Those who are familiar with C language know that strings are maintained using character arrays. Also people face many problems with the string termination character ‘\0’ in C strings.

 

C++ eliminates such difficulties altogether by providing pre-defined string class. It is available in the header file string.

 

Creating strings

 

We can create strings in two ways using the string class. First way is create a variable with type string and assign a string literal to it as shown below:

 

string  str = “hello”;

 

Second way is to use the string constructor which accepts a single string parameter to initialize the string variable as shown below:

 

string  str(“hello”);

 

Consider the following program which demonstrates reading strings as well as concatenating, copying, and finding the size of the string.

 

#include<iostream>
#include<string>
using namespace std;
int main()
{
	string str1;
	cout<<"Enter first string: ";
	getline(cin, str1);
	string str2;
	cout<<"Enter second string: ";
	getline(cin, str2);
	cout<<"First string is: "<<str1<<endl;
	cout<<"Second string is: "<<str2<<endl;
	string catstr;
	catstr = str1+" "+str2;
	cout<<"Concatenated string is: "<<catstr<<endl;
	string copystr;
	copystr = catstr;
	cout<<"Copied string is: "<<copystr<<endl;
	cout<<"Length of copied string is: "<<copystr.length()<<endl;
	cout<<"Size of copied string is: "<<copystr.size()<<endl;
	return 0;
}

Input and output for the above program is as follows:

Enter first string: hello
Enter second string: world
First string is: hello
Second string is: world
Concatenated string is: hello world
Copied string is: hello world
Size of copied string is: 11
Size of copied string is: 11

 

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

Your email address will not be published. Required fields are marked *