FORUM Dedicated to Programming
HomePortalCalendarFAQSearchMemberlistUsergroupsRegisterLog in

Share | 

 Declaring Arrays in C++

Go down 

Number of posts : 18
Age : 27
Registration date : 2008-11-12

PostSubject: Declaring Arrays in C++   05/12/08, 07:27 pm

Declaring C++ Arrays of int type:

The c++ arrays are declared with the data type name and the number of elements inside the square brackets.

int var_name[50]; // C++ Array of type int with maximum size = 50.

The above declaration means, the var_name is an array of integer type. The values inside this var_name array can be accessed by referring to the position of their elements like var_name[0], var_name[1] etc.,

All the C++ arrays are based on Zero index values. That means the position reference starts at 0 and counts till the n-1th position. So in the above array, 50 elements can be stored starting from 0 to 49. The values can be stored and accessed as given in the following code snippet.

var_name[0] = 0;
var_name[1] = 1;
var_name[2] = 30;

Care should be taken while using or referring to the position of the element. The position reference should not exceed the maximum size specified in the declaration. If it exceeds, the program will not generate any compiler errors. But it will raise run time errors and exceptions.

Declaration of a two dimensional array is also similar. A great example for a two dimensional c++ integer array will be matrix.

int array_matrix[3][3]; //Matrix of 3 * 3 type using c++ array of int data type

Declaring C++ arrays of type float:

The declaration and use of c++ arrays in float type are the same as int. The declaration is written as follows.

float var_float[100]; //A c++ array of float type

The above declaration means, the c++ float array contains 100 elements starting from position 0 till 99. The elements can be accessed as var_float[0], var_float[1], var_float[2] .. var_float[99].

var_float[0] = 10.05;
var_float[1] = 11.04;
var_float[99] = 87.65;

Declaring C++ arrays of type char:

This is one of the most widely used and problematic type of c++ array. When an array of char is declared, this char array can be used as a string with the maximum size as specified in the array declaration. When this c++ char array is declared with two dimensions, this can be thought as an array of strings.

char var_char_array[50]; //Memory reserved for 50 characters.
char var_char_init[] = "c++ char array string example"; // initialization without specifying the size

Like the above the c++ char array can be declared with or without initializing values.
Back to top Go down
View user profile
Declaring Arrays in C++
Back to top 
Page 1 of 1
 Similar topics
» Creating the account (URL) globally and using that variable where ever it needed

Permissions in this forum:You cannot reply to topics in this forum
Programming :: C & C++ Programming :: C & C++ Discussions & Solutions-
Jump to: