Arrays & Strings in C/C++

Introduction:

Here we are with the 6th tutorial of the short series of tutorials for the beginners in C++. In this tutorial we are going to introduce you with the most fundamental data structure i-e: Numbered Array in C++.

We will discuss the most basic arrays along with its syntax and functionalities. Later on we will move into more complex arrays such as two dimensional arrays.

In the second part of this tutorial we are going to have some fun with strings in C++. We will discuss its usage and will define several string manipulation functions which can be applied on strings to get the desired results. So let the fun begin!

As usual, we will write a basic console application in order to elaborate the topics mentioned above. Following is the basic console application program in C++.


#include <iostream>

using namespace std;

int main()

{

	//code here

return 0;

}

 

Contents:

1-Arrays

One dimensional Arrays.

Two dimensional Arrays.

2- Strings

I. C-Strings

strlen()

strcat()

strspn()

strcpy()

strcmp()

II. Standard C++ Strings

3- Projects

1. Student Result Card.

2. Login System.

 

1-ARRAYS:

Whenever we need to store an element we declare its data type and then assign it a value. For example if we need to store a number ‘5’, we declare a data type “int” and assign it a value “5”. This technique works for one or two number. Now, suppose if we want to store prices of 10 food items, it will be very cumbersome to declare 10 variables of type “int” and then assign value to each variable. This technique is time consuming, less efficient and requires lots of coding.

In such situations we use arrays. Arrays hold a series of elements of same data type. Array occupies contiguous memory locations in memory and elements of same type can be stored using a single array. These elements are stored and accessed using array index which we will explain in the coming section. Let’s first have a look at how arrays are defined in C++.

One Dimensional Arrays:


	int prices [10];

This is the syntax for array declaration in C++. The above line means following:

· Type of array is int.

· Name of array is “prices”.

· Total number of elements this array can store is 10.

There is a very important point to be noted. The array index starts from 0. It means that if the total size of array is 10, the first index will be zero and the last index will be 9. The first element will be at zero index while the last element will be at 9th index. This concept can be elaborated by the following example.

Suppose we have prices of 10 fruits and we want to store their prices. Elements can be allotted to array in two ways. You can either enter the values index by index as shown below i-e

prices[0] = 50

prices[1] = 55

Prices[2] = 45

.

.

.

.

.

.

Prices[9] = 39

Note, we have inserted first element at the zero index.

The second way to allot elements to array indexes is using the following technique.


int prices [] = {50, 55, 45, 40, 60, 56, 42, 56, 23, 41};

for (int i=0; i < 10; i++)

{

	cout<<prices[i]<<endl;

}

Note that in this technique we have not specified the total number of elements while declaring the array but the compiler will automatically create the index of array depending upon the number of elements on right side of the declaration. In the above program we have employed a loop to traverse through all the elements in array and print them on screen. Remember inside loop we have used index number “i” to access the corresponding element of array. The output of this program is as follows.

 

Two Dimensional Arrays:

Two dimensional arrays, also called matrix arrays, table arrays or arrays of arrays can store data in two dimensions i-e in the form of rows and columns. Two dimensional arrays are particularly useful when dealing with matrix programs or to store data which is in the form of columns and rows. Syntax of tow dimensional arrays is simple:


	int matrix [3][4] ;

Note here the syntax is almost the same as single dimensional array but we have added another pair of square brackets at the end. This square bracket at the end defines the number of column. This declaration means:

· Type of array is int

· Name of array is matrix.

· Array consists of 4 rows and 4 columns.

Like one dimensional arrays, there are two methods to allocate value to a two dimensional arrays. Remember the index for both rows and column starts from zero. First method to allocate values to two dimensional arrays is as follows.

matrix [0][0]= 10 // First row, 1st Column,

matrix [0][1]= 20 // First row, 2nd column

matrix [0][2]= 15// First row, 3rd column

.

.

.

.

.

matrix [2][3]= 19 // 3rd row, 4th column

The second method to allocate elements to a 2D array is as follows:


int matrix [3][4] = {{10, 20, 15, 40},

{12, 43, 13, 65},

{12, 45, 16, 32}

};

Now if we want to retrieve the elements from this two dimensional arrays, we need two for loops one for the rows and the other for the column nested in the outer loop as follows:


for (int i=0; i < 3; i++)

{

	for(int j=0; j< 4; j++)

		cout<<matrix[i][j]<<" ";

		cout<<endl;

}

The output of above code is as follows:

 

2- STRINGS:

Strings are a sequence of characters. They are sometimes also referred to as character arrays. There are two types of strings in C++. The native C Strings and the Standard C++ String class. We will discuss both of them.

I. C-Strings

The syntax for defining c- strings in C++ is as follows:


char name[6] = {'d','a','v','i','d','\0'};

Here in the above example we have declared a string which can hold 6 characters, remember while initializing string like this the index size of string should be one greater than the total number of characters to be stored. This is for the reason that null character has to be allocated at the last index which signals the end of string. However in the following string initialization method we don’t need to enter the null character. The compiler automatically adds it in the end.


char name[]="david";

Following program explains the strings in a simplified way.


char name[50];

cout<<"Enter Your Name:";

cin>>name;

cout <<"Welcome "<<name<<" to TBYTutorials";

In the above program a name as long as 50 characters can be entered. The output of this program is as follows.

 

Some Important String Functions:

Following are some of the string functions which can be used to manipulate strings:

  • strlen()

This function returns the length of the string which is passed as parameter to it.

Example:


char name[50];

cout<<"Enter Your Name:";

cin>>name;

cout <<"Welcome "<<name<<" to TBYTutorials\n";

cout<<"Length of name is :"<<strlen(name);

Output:

 

  • strcat()

This function is used to concatenate two strings. Its syntax is:

strcat(destination string, source string)

The source string will be appended at the end of destination string.

Example:


char fname[50];

char lname[50];

cout<<"Enter Your first name:";

cin>>fname;

cout<<"Enter Your last name:";

cin>>lname;

cout<<"Your full name is :"<<strcat(fname,lname);

Output:

In the above example we have taken the first and last name from user and then have concatenated them using strcat () function.

 

  • strspn()

This function matches the starting element of one string with the other and returns the number of characters which match starting from the first index. If the first character of both strings is different, it will return zero. The following example will elaborate this concept.

Example:


char str1[50];

char str2[50];

cout<<"Enter first string:";

cin>>str1;

cout<<"Enter second string:";

cin>>str2;

cout<<"Number of starting characters match :"<<strspn(str1,str2);

Output:

It can be seen that in string 1, there are three starting characters which are in string 2: abc. So the function returns 3.

 

  • strcpy()

This function is used to copy the contents of source string into destination string. Its syntax is strcpy(destination string, source string). Example will clear the concept.

Example:


char str1[50];

char str2[50];

cout<<"Enter source string:";

cin>>str1;

strcpy(str2,str1);

cout<<"Your string has been copied and its value is: "<<str2;

In the above example, the string is input from user one into str1, then this str1 is copied to second string str2, and this str2 is displayed which shows the copied value from str1.

 

  • strcmp()

This function is used to compare the length of two strings. It’s syntax is as follows:


Strcmp(string1, string2);

If string1 < string 2, returns less than 0.

If string1 > string 2, return greater than 1.

If string 1 == string 2, returns 0.

Example:


char str1[] = "abcd";

char str2[] = "ab";

cout << strcmp(str1, str2)<<endl;

char str3[] = "abcd";

char str4[]= "abcde";

cout << strcmp(str3, str4)<<endl;

char str5[] = "abcd";

char str6[] = "abcd";

cout << strcmp(str5, str6)<<endl;

Output:

 

II. Standard C++ Strings:

In the C-Strings we have seen that we have limitation of size. For example what will happen if user wants to enter a name which contains more than 50 characters. In that case, buffer overflow will occur. However C++ has its own string class which solves this issue. This string class is based on C-Strings and behind the scene performs the same functionality; however it hides the complexities of memory management from the user. The syntax for standard C++ strings is as follows.

Example:


#include <iostream>

#include <string>

using namespace std;

string name;

cout<< "Enter your Name: ";

cin >> name;

cout <<"Welcome "<<name<<"\n";

cout <<name + "Roberts\n";

cout << name.size();

Output:

It can be seen that C++ standard string class contains its own functions. Size is example of one of those functions which returns the length of string as was the case with strlen() function in the native C-Strings. Remember, in order to use string classes in our programs we have to include <string> library as in this example. In this example we have also used concatenation operator which is simply “+”. In native C-Strings we observed that we had to use strcat() function for this purpose. And finally there is no restriction on number of characters. It can be concluded that standard C++ string classes are more powerful and robust.

 

PROJECTS:

1. Student Result Card:

This project uses two dimensional arrays to store marks of each student in a paper. It takes input from the user as marks in the form of marks per paper/ per student. It then stores the value in a two dimensional array and then prints the result card. It displays the individual as well as the total marks of the students. Following is the output.

 


#include <iostream>

#include <string>

using namespace std;

int main()

{

	int result[3][3];

	for (int i=0; i < 3; i++)

	{

		for(int j=0; j< 3; j++)

		{

			cout<<"Enter Marks for student " << i+1 <<" Paper " <<j+1<<": ";

			cin >> result[i][j];

		}

		cout<<endl;

	}

	cout <<"\n\n======================= Result =============================\n";

	for (int i=0; i < 3; i++)

	{

		int sum =0;

		for(int j=0; j< 3; j++)

		{

			cout<<"Marks for student " << i+1 <<" Paper " <<j+1<<": "<<result[i][j]<<"\n";

			sum = sum+result[i][j];

		}

		cout <<"Total Marks for student "<<i+1<<" = "<<sum<<endl<<endl;

	}

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

OUTPUT:

 

2. Login System.

The simplest use of string can be explained using the login function of any program. Suppose you are signing up for some website. You sometimes notice that website prompts you that user name or passwords are too small or username or passwords should be of minimum 6 characters. Behind the scene string length functions are used for these field validations. Here is the simplest code for login and signup system where if username and password are less than six characters the program prompts you.

Code:


#include <iostream>

#include <string>

using namespace std;

int main()

{

	string username;

	string password;

	do

	{

		cout << "Enter user name:";

		cin >> username;

		if(username.size()<6)

		{

			cout<<"Username must be at least 6 characters.\n";

			continue;

		}

		cout<<"Username is valid.\n";

		break;

	}

	while(true);

	do

	{

		cout << "Enter Password:";

		cin>>password;

		if(password.size()<6)

		{

			cout<<"Password must be at least 6 characters.\n";

			continue;

		}

		cout<<"\Password is valid";

		break;

	}

	while (true);

	getchar();// Just to prevent screen from disappearing

	cin.get();// Just to prevent screen from disappearing

}

OUTPUT:

 

You might want to read:

C++ for Beginners Part 8 – Functions

C++ for Beginners Part 7 – Pointers

C++ for beginners Part 6 – Arrays & Strings

C++ for beginners Part 5 – “switch and loops”

C++ for beginners Part 4 – else if Statement in C++

C++ for beginners Part 3 – Conditional “if” Statement

C++ for beginners Part 2 – The Basics of C++

C++ for beginners Part 1 – Installing Visual C++ Express

 

More C / C++ and Dev Programming Tutorials:

 

If you liked this tutorial, please share with your friends:

Leave a Reply

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