Arrays & Strings in C++

Here we are with Part 6 for the beginner 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. The 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 values to each variable. This technique is time consuming, less efficient and requires lots of coding.

In such situations we can use arrays. Arrays hold a series of elements of same data type. Array occupies contiguous memory locations in memory and elements of the same type can be stored using a single array. These elements are stored and accessed using an 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 the 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 arrays 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 the 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 two dimensional arrays is simple:

int matrix [3][4] ;

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

· Type of array is int

· Name of array is matrix.

· Array consists of 3 rows and 4 columns.

Like one dimensional arrays, there are two methods to allocate values to a two dimensional array. Remember the index for both rows and column starts from zero. The 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 loops one for the rows and the other for the columns 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 << "\n"; //move cursor to next row
}

The output of the 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. Character Strings

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

char name[6] = {'d','a','v','i','d','
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 strings like this, the index size of the string should be one greater than the total number of characters to be stored. This is for the reason that a 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";

The 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

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

  • strlen()
  • strcat()
  • strspn()
  • strcpy()
  • strcmp()

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() or strcat_s()

These functions are used to concatenate two strings. The first works for most other C++ compilers. The syntax is:

strcat(destination string, source string)

The second one is for C++ in Visual Studio as the first one is depreciated. The syntax is:

strcat_s(destination string, size, 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;

strcat_s(fname, 50, lname);

cout << "Your full name is :" << fname;

Output:

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

strspn()

This function finds a match within two strings and returns the number of characters that 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 the source string into destination string.

The syntax’s are (second one is for Visual Studio C++) :

strcpy(destination string, source string)

strcpy_s(destination string, source string)

The example will clear the concept.

Example:

char str1[50];

char str2[50];

cout << "Enter source string:"; 

cin >> str1;

strcpy_s(str2,str1);

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

In the above example, the string is input from user into str1, then it is copied into string str2, then str2 is printed to the console screen.

strcmp()

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

strcmp(string1, string2)

If string 1 < string 2, then print -1.

If string 1 > string 2, then print 1.

If string 1 == string 2, then print 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;

Note we are using the keyword endl in place of “/n” for next line.

Output:

II. Standard C++ Strings:

In the native C++ Strings we have seen that we have a limitation of size. For example what will happen if a user wants to enter a name which contains more than 50 characters. In that case, a buffer overflow will occur. However C++ has its own string class which solves this issue. This string class performs the same functionality; however it hides the complexities of memory management from the user.

Add the include statement above your main() function to enable the string keyword.

#include <string>

Then copy and paste the code below in between main() and the return keyword.

Example:

string name;

cout <<  "Enter your Name: "; 

cin >> name;

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

cout << name + "Roberts\n";

cout << name.size();

Output:

It can be seen the string class contains its own functions. Size is an example of one of those functions which returns the length of string as was the case with the strlen() function. Remember, in order to use string classes in our programs we have to include the <string> library. In this example we have also used the concatenation operator which is simply “+”. In native strings we observed that we had to use strcat() function for this purpose. And finally there is no restriction on the 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 results. It displays the individual as well as the total marks of the students.

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

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 should be of minimum 6 characters. Behind the scene string length functions are used for these field validations. Here is the simplest code for a login and signup system where the program will prompt you if the username and password are less than six characters.

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

OUTPUT:

You might also want to read:

Part 1 – Installing Visual Studio C++

Part 2 – The Basics of C++

Part 3 – Conditional “if” Statement

Part 4 – else if Statement in C++

Part 5 – “switch and loops”

Part 6 – Arrays & Strings

Part 7 – Pointers

Part 8 – Functions in C++

If you like this page please share with your friends.

Leave a Comment

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