Arrays in C++

Arrays are used to store a number of items of the same type in one single variable. They are usually placed in the same segment of memory with accessible elements for each. This tutorial will explain you the tricks to C++ arrays.

Array Declaration

To declare arrays in C++ you need to specify the type of the array elements, name of array variable and the number of elements required by an array.

type variableName [size];


int foo[5];

Array Initialization

In C++ array elements can be initialized one by one or through a single statement.

int bar[12];
bar[0] = 8;
bar[3] = 2;


int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6};

The number of values between braces {} can not exceed the size of array which was specified at the time of array declaration.

Accessing Array Elements

The value of any of the elements in an array can be accessed by indexing the array name. You can access the value of 5th element of bar[] array as follows.

count << bar[4];


#include <iostream>
using namespace std;

int main () {

int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6}; // bar is an array of 12 integers

// output each element of array
for(int i = 0; i < 12; i++ ){

cout << bar[i] << “\n”;


return 1;


Multidimensional Arrays

Arrays of arrays are called multidimensional arrays. C++ allows multidimensional arrays.

Multidimensional array declaration

int foo[2][4];

Multidimensional Arrays Example

#include <iostream>
using namespace std;

int main () {

// an array with 5 rows and 2 columns.
int foo[5][2] = { {1,3}, {0,2}, {2,6}, {3,1},{9,1}};

// output each array element’s value
for ( int i = 0; i < 5; i++ ) {

for ( int j = 0; j < 2; j++ ) {

cout << “foo[” << i << “][” << j << “]: “;
cout << foo[i][j]<< endl;



return 0;



foo[0][0]: 1
foo[0][1]: 3
foo[1][0]: 0
foo[1][1]: 2
foo[2][0]: 2
foo[2][1]: 6
foo[3][0]: 3
foo[3][1]: 1
foo[4][0]: 9
foo[4][1]: 1

C++ Strings

C++ Strings are character type array and string literals are words surrounded by double quotation marks.

String Declaration

C++ strings are declared as one-dimensional array of characters which is terminated by a null (‘\0’) character. The the size of the character array containing the string is one more than the number of characters it holds due to the null character at the end.


char myString[6] = {‘G’, ‘e’, ‘n’, ‘l’, ‘e’, ‘\0’};

You can also declare and initialize myString as

 char myString[] = “Genie”;

This would declare a string with a length of 6 characters. Do not forget that arrays begin at zero. A string ends with a null character so remember that there will be an extra character at the end on a string. Technically, in a 6 character array you could only hold 5 letters and one null character at the end to terminate the string.

char *arr; can also be used as a string. If you have read the tutorial on pointers, you can do something such as:

arr = new char[256];

which allows you to access arr just as it is an array. Keep in mind that to use delete you must put [] between delete and arr to tell it to free all 256 bytes of memory allocated.

delete [] arr;

The getline() function

Strings are useful for holding all types of long input. If you want the user to input his or her name, you must use a string. Using cin>> to input a string works, but it will terminate the string after it reads the first space. The best way to handle this situation is to use the function cin.getline. Technically cin is a class (similar to a structure), and you are calling one of its member functions. The most important thing is to understand how to use the function however.

getline(char *buffer, int length, char terminal_char);

The char *buffer is a pointer to the first element of the character array, so that it can actually be used to access the array. The int length is simply how long the string to be input can be at its maximum (how big the array is). The char terminal_char means that the string will terminate if the user inputs whatever that character is. Keep in mind that it will discard whatever the terminal character is.

It is possible to make a function call of cin.getline(arry, 50); without the terminal character. Note that ‘\n’ is the way of actually telling the compiler you mean a new line, i.e. someone hitting the enter key.

getline() example

#include <iostream>

using namespace std;

int main()

char string[256];

cout<<“Please enter a long string: “;
cin.getline ( string, 256, ‘\n’ );
cout<<“Your long string was: “<< string;


Remember that you are actually passing the address of the array when you pass string because arrays do not require an address operator (&) to be used to pass their address. Other than that, you could make ‘\n’ any character you want (make sure to enclose it with single quotes to inform the compiler of its character status) to have the getline terminate on that character.

C++ String Functions

<string> is a header file that contains many functions for manipulating strings. See some of string function below.

strcmp() function

int strcmp (s1, s2);

strcmp accept two strings and return an integer. This integer will either be:

Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.

strcat() function

char strcat (dest, src);

strcat is short for string concatenate. It appends the second string at the end of the first string. Beware this function, it assumes that dest is large enough to hold the entire contents of src as well as its own contents.

strcpt() function

char strcpy (dest, src);

strcpy is short for string copy, it copies the entire contents of src into dest.

strlen() function

size_t strlen (s);

strlen() will return the length of the string excluding the null character. The size_t is nothing to worry about. Just treat it as an integer that cannot be negative.

C++ Structures

C++ structures provides a way to store many different values in variables of potentially different types under the same name. It makes the program more modular, which is easier to modify because its design makes things more compact. Structures are useful whenever a lot of data needs to be grouped together e.g. they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct will hold all of the information about a single contact for example name, address, phone number etc.

Defining structures

struct structName {

member definition;
member definition;

} structureVariables;

structName is the name of the entire type of structure which is optional and members are the variables within the struct, structureVariables are one or more structure variables which is optional.

struct Contacts {

char fristName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;


Accessing Structure Members

The dot (.) operator is used to access any member of a structure. Dot operator is used between the structure variable name and the structure member that we are going to access. struct keyword is used to define variables of structure type.

#include <iostream>
#include <cstring>

using namespace std;

struct Contacts {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;


int main( ) {

//Declaring Contact1 of type Contact
struct Contacts Contact1;

strcpy( Contact1.firstName, “Scott”);
strcpy( Contact1.lastName, “Tiger”);
strcpy( Contact1.emailAddress, “”);
Contact1.age = 28;
Contact1.contact_id = 1071;

//Printing Contacts
cout << “Contact1 firstName : ” << Contact1.firstName <<endl;
cout << “Contact1 lastName : ” << Contact1.lastName <<endl;
cout << “Contact1 emailAddress : ” << Contact1.emailAddress <<endl;
cout << “Contact1 age : ” << Contact1.age <<endl;
cout << “Contact1 id : ” << Contact1.contact_id <<endl;

return 0;


Output of the above program will be

Contact1 firstName : Scott
Contact1 lastName : Tiger
Contact1 emailAddress :
Contact1 age : 28
Contact1 id : 1071

typedef Keyword

The typedef Keyword can be used to define structures.

typedef struct {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;


Now Contacts can be used to directly define variables of Contacts type without using struct keyword.

C++ File Handling

C++ has a standard library fstream which is used for file handling. <fstream> header file must be included in your program to process files. It has three data types ofstream, ifstream and fstream.


ofstream is the output file stream which is used to create files and to write information to files.


ifstream is the input file stream which is used to read information from files.


fstream is the general file stream which can be used to create files, write information to files, and read information from files.

Opening a file

If you want to write or read from a file first you must open the file. ifstream object is used to open a file to just read from it, ofstream and fstream objects can be used to open a file for writing. The open() function is a member of fstream, ifstream, and ofstream objects. The first argument specifies the name and location of the file and second argument specifies the mode in which the file should be opened.

fstream myFile;“myFile.txt”, ios::out | ios::in );

Mode Description
ios::app The output to that file will be appended to the end.
ios::ate Move the read/write control to the end of the file.
ios::in Open the file for reading.
ios::out Open the file for writing.
ios::trunc The contents will be truncated before opening the file if it already exists.

Closing a file

The close() function is is a member of fstream, ifstream, and ofstream objects and used to close opened files. C++ automatically flush all the streams, opened files and release allocated memory when a program terminates. But it is good practice to close all the opened files before program termination. Following is the syntax to close a file.

void close();

Writing & reading from a file

The stream insertion operator (<<) is used with the ofstream or fstream object to write information to a file. The stream extraction operator (>>) is used with the ifstream or fstream object to read information from a file.

File Handling Example

#include <fstream>
#include <iostream>

using namespace std;

int main () {

char data[50];

ofstream myFile;“myFile.txt”);

cin.getline(data, 50);

//writing information into the file
myFile << data << endl;

//closing file

//opening the file in read mode
ifstream oldFile;“myFile.txt”);

oldFile >> data;

//printing the data on screen.
cout << data << endl;

//closing file

return 0;


C++ Type Casting

Type casting causes the program to treat a variable of one type such as an int to act like another type such as a char for one single operation. The implicit castings are automatically performed when value of a variable is copied to another variable of a compatible type.

Implicit Casting Example

#include <iostream>
using namespace std;
int main()

short distance = 24;
int milage;
milage = distance;
cout << “milage = ” << milage;
return 1;


In this example the value of distance is copied from ‘short’ to ‘int’ without using type cast operator.

C++ Type Casting

In c++ many conversions require an explicit conversion and a cast operator is used to force one data type to act like another. There is also a functional notation which can be used for type casting. The cast operator is unary and has the same precedence as other unary operators.

#include <iostream>
using namespace std;
int main()

double a = 41.63;
double b = 54.23;
int c, d;

c = (int) a;
cout << “Value of c = ” << c << endl ;

d = int(b);
cout << “Value of d = ” << d << endl ;
return 1;



Value of c = 41
Value of d = 54