Arrays and String in C++

Discussion in 'C++' started by usmanmalik, Dec 29, 2013.

  1. usmanmalik

    usmanmalik New Member

    Joined:
    Dec 28, 2013
    Messages:
    19
    Likes Received:
    14
    Trophy Points:
    0
    This tutorial will give you a basic overview on two of the most fundamental concepts in every programming language: Arrays and Strings. We will individually explain what arrays and strings are, why they are important, how to deal with them and how we can use them to perform certain functions.

    Arrays



    We usually deal with everything in groups. For example, when we go to store we buy a pack of chewing gums, a carton of eggs or a bundle of cheese or butter boxes. Arrays are a similar concept. When we declare a variable we can store one value in it. Often times we need to store large number of data of same type. For instance, if we are storing percentages of, let us say 10 students. It will require us to declare 10 variables and then store information in those variables individually. This will result in large amount of code which is not easy to manage.

    The simplest definition of array is that it is group of variable of same type stored on contiguous locations in the memory of the system. It helps us to organize items of similar data type. For example if you want to store percentage of 10 students, you will simply have to declare an array of size 10 and can store those percentages. This will result in smaller and more organized code. There are two types of arrays: Linear or One Dimensional arrays and Multidimensional arrays. We will explain both of them one by one.

    Linear (One Dimensional Arrays)



    Linear arrays, as the name suggests are the type of arrays which store data in one dimension. Data is stored in memory in form of single row or column, whereas, two dimensional arrays store data in the form of matrix or collection of rows and column. We will explain two dimensional arrays later. Here we will explain what the syntax of 1-D Arrays is.

    Pay attention to the following line of code

    Code:
    int percentages [10];
    The above line is the syntax to declare an array of type int, with name percentages and size 10. It means that the array named ‘percentages,’ is able to store 10 items of type integer.

    Again look at the syntax, the array has three basic parts.
    1. The type of the array, which is integer in the above case.
    2. The name of the array which is ‘percentages’ in this case.
    3. The number of items an array can store which is stored inside square brackets which is 10 in this case.
    In this array there are 10 indexes to store data. Remember, the index of an array starts from 0. Which means that the first item of the array is actually stored at the zero index A linear array of size 10 will have the first index at 0th place and last index at the 9th place. Hence in the array of size N, the first index is at 0th place and last index at N- 1th place.

    Let us store the items in the above array.

    There are two ways to store items in the array.

    1. You can store item on a particular index in the following way.
    Code:
    percentages[0] = 77;
    percentages[1] = 70;
    percentages[2] = 91;
    .
    .
    .
    .
    percentages[9] = 82;
    
    Here we have written the name of the array, followed by the index in the square brackets where we want to store the item. Note index [1] is actually the second index and index [0] is the first index.

    2. Another way of storing data in one dimensional array is as follows:

    Code:
    int percentage [] = {77, 70, 91, 74, 65, 59, 86, 74, 94, 82};
    Now the second method has one advantage that in this case we don’t have to specify the size of the array. You can add as much items as you want on the right side of the assignment operator, within the opening and closing braces. Here remember, the first item inside the braces will be stored automatically at 0th index, the second item at first index and the Nth item at N- 1 index.

    Have a look at the code in Example1.

    Note: All the example codes of this tutorial have been written in Visual C++ with Windows

    Example1
    Code:
    #include <iostream>
    using namespace std;
    int main()
    {
    
    	int percentages [] = {77, 70, 91, 74, 65, 59, 86, 74, 94, 82};
    	for (int i=0; i < 10; i++)
    	{
    		cout<<percentages[i]<<" ";
    	}
    }
    
    In Example1, we have simply declared an array named ‘percentages’ and assigned some values to this array inside the main function. The best way to access the elements of an arrays is by using a ‘for loop’. In for loop we can define that how many times loop should be executed. If we want to access all the elements of the array, the number of time for loop should execute should be equal to the items stored inside the array. In Example1, we have an array with 10 elements; therefore we execute the loop 10 times from 0 to 9. The variable ‘i’ inside the loop definition is used to access the item of array. In first iteration ‘i’ will contain 0, hence percentages, actually means percentages[0]. Therefore the element at 0th index will be displayed which will be 77. Next time ‘i’ will be incremented and the item at 1st index will be displayed and so on. Following is the output of this code.

    Output1

    [​IMG]

    Two Dimensional Arrays



    In simplest words, two dimensional arrays can be defined as the arrays of arrays. In linear array we only had an array in the form of row and data was stored in a linear pattern. In two dimensional arrays we have column and rows to store data. It is for this reason, two dimension arrays are also known as matrix arrays as actual data storage pattern takes the form of a matrix.

    Now pay attention to the following line of code

    Code:
    int stud_perc[3][4];
    This is how simple to define a two dimensional array. The above line of code means that we have a an array named stud_perc of type which will have 3 rows and 4 columns. Think of this array in such a way that each row represents a student and each column represents subjects. So if we want to store percentages of each subjects of a particular student we can do so by assigning values to each row which we will see in Example2.

    Now how to assign values to two dimensional arrays? Like, linear arrays we have two ways for that:

    1. We can store values into each index individually like
    Code:
    stud_perc[0][0] = 79; // First row, First column
    stud_perc[0][1] = 70; // First row, Second column
    .
    .
    .
    .
    stud_perc[2][3]= 91; // Third row, Fourth column
    
    2. The second way is to initialize the array without specifying the index as we did in the case of linear arrays.
    Code:
    int stud_perc [3][4] = {
        {74, 94, 74, 84},
        {74, 95, 75, 85},
        {74, 84, 79, 86}
    };
    
    Actually we are specifying three linear arrays separated by commas which make them one two dimensional arrays having three rows.

    Example2
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	
        int stud_perc [3][4] = {
            {74, 94, 74, 84},
            {74, 95, 75, 85},
            {74, 84, 79, 86}
        };
    
        for (int i=0; i < 3; i++)
        {
            cout<< "Marks Obtained by Student " << i+1<<"\n\n";
            for(int j=0; j< 4; j++)
            {
                cout<<"Subject:"<<j+1<<" Percentage: "<<stud_perc[i][j]<<endl;
            }
            cout<<endl;
        }
    }
    
    In Example2, each row denotes a student and each column in that row denotes the percentage of the student in a particular subject. The output of the above code will be:

    Output2

    [​IMG]

    C++ Strings



    String consists of a sequence of character. We can say that a word is actually a string because word is made up of several characters. Strings can also be considered as an array holding characters. In C++ we have two types of string. Since almost all of the syntax of C language can be used in C++ as well; therefore one way to define a string is using old C string method and the other is the C++ String declaration method. We will see both of them.

    Native C Strings



    Native C Strings are nothing but linear arrays of characters, where last index contains a null character.

    Code:
    char arrays [9] = {‘T’, ‘U’, ‘T’, ‘O’, ‘R’,’ I’, ‘A’,’L’, ‘\0’};
    Note that tutorial word tutorial has 8 characters but we have declared a character array of size There is another way to declare string in C++ where we don’t specify the size of array. Have a look at this line of code:9 because we have to append a null character in the end, signifying the end of array.

    Code:
    char arrays[]="TUTORIAL";
    Here, we don’t need to specify the size of the array.

    Have a look at Example3. In this Example we take string input from the user and display it on main screen.

    Example3
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
        char name[100];
        cout<<"What is your name:";
        cin>>name;
        cout <<"Welcome "<<name;
    }
    
    In Example3, the string name can hold 99 characters that user inputs. The last character will be automatically appended i.e. null character.

    C++ Strings



    The other type of strings is the latest C++ strings. In case of native c string there were several issues like what would happen if user wants to input more number of characters than the size of the string. It will cause the memory buffer to overflow. These issues have been solved in the more advanced C++ Strings. In the back end C++ strings deal strings in the same way as the native C Strings but the memory complexities are hidden from the user. In order to use C++ strings, we need to include <string> library at the top of the program. Have a look at the following example.

    Example4
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string country, name;
        cout<< "Your name: ";
        cin >> name;
        cout<< "You belong to:";
        cin >> country;
        cout<<"Please Welcome "<< name << " from "<< country;
    }
    
    Output4

    [​IMG]

    C++ strings are basically classes that come with several functionalities. You can add the strings using built in functions. You can compare two strings; copy two strings, get a substring, and perform virtually any function using the C++ string classes. For instance in Example5, we will show you how to calculate size of the string and how to add two user provided strings.

    Example5
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
        string country, name;
        cout<< "Your name: ";
        cin >> name;
        cout<< "You belong to:";
        cin >> country;
    
        cout<<"Please Welcome "<< name << " from "<< country;
        cout <<"\nTotal length of your name is "<<name.size() <<" characters.";
        cout <<"\nYour name and country combined is " << name+country;
    }
    
    In Example5, we took name and country as the input from the user and then displayed the length of the name of the user and then concatenated the name and country of the user and then displayed it. Remember string can also be concatenated by using append function. There are several such functionalities in C++ string class.

    Arrays and Strings are one of the key concepts of programming. Actually whenever we log into a website or enter our particulars into a data base, at the back end several complex arrays and string functionalities are being performed. Whether you shopping online, reserving an airline ticket, checking your result online in some exam; you are dealing with strings. Therefore it is extremely important to have a sound foundation of strings and arrays. In this tutorial we have tried to give you a basic understanding of what strings and arrays are and how they can be used to perform basic functionalities. I will encourage you to further explore arrays and string classes. Also, arrays are used to store group of data of same type, there is another data structure which allows us to group data variables of different type which we will see in our tutorial on C++ Structures.
     
    Last edited by a moderator: Jan 21, 2017
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice