Professional Documents
Culture Documents
Declaration syntax
Example
char grades[5];
Sometimes, the programmer can declare an array and
assign values to it at the same time.
The values supplied during initialization forms the
intializer list of the array declaration
Declaration with initialization syntax
Example
char grades[] = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
Reminders: 1. If initializer is given, you may leave out the array size.
2. If the array size is specified, the number of
elements in the initializer list should NOT exceed
the specified array size.
C++ supports two versions of array dimensions
Single dimension – which is declared with a single []
bracket.
Example:
int values[11]; //this declares an array equivalent to a
single row matrix with eleven columns
One row
Eleven columns
Multi-dimension – which is declared with multiple
[] brackets.
Example: Two dimension
int twoDimPlane[4][4]; //this declares an array
equivalent to a 4 by 4 matrix
Example: Three dimension
int threeDimPlane[5][5][3]; // this declares an array
equivalent to a cube
4 columns
You can assign a value to a specific position on the
array using the following syntax
arrayName[index] = value;
Example
grades[0] = ‘A’;
grades[1] = ‘B’;
grades[2] = ‘C’;
grades[3] = ‘D’;
grades[4] = ‘E’;
int numberOfGrades = 5;
2.
char grades[numberOfGrades ];
3.
const int NUMBER_OF_GRADES = 5;
char grades[NUMBER_OF_GRADES];
The first case uses a direct literal to specify the
array length :: NOT ADVISED
The second one offers an improvement but yet
is not very good one.
These two alternatives may require you to edit
several places if you want to change the size
The third one is the best. Declared as global
variable, the constant defines the array size for
all of your program (within main and other
functions):: MOST ADVISED
Change once and the effect occurs everywhere.
CODE
U can use the sizeof operator to work out
the length of the array
REMEMBER
Array is of data type T where data type T
needs y bytes for storage
If we want to know how many elements are
CODE
void printGrades( char grades[], int arraySize )
{
for(int i = 0; i < arraySize; i++)
{
cout << grades[i] << endl;
}
}
#include <iostream>
void printGrades( char grades[], int arraySize )
{
for(int i = 0; i < arraySize; i++)
{
cout << grades[i] << endl;
}
}
int main()
{
char grades[] = {‘A’,’B’,’C’,’D’,’F’};
printGrades(grades,5);
cin.get();
}