Sunday 26 July 2015

Arrays in C++

In the previous 4 posts (part 1, part 2, part 3, part 4) we covered the topic of Functions in C++. Today we'll jump onto the next topic and start with arrays.

Introduction:

We have already seen some of the commonly used data types of C++:
                            int, float, double, char 
Now, lets have a look at Composite Data Structures

Composite Data Structures:

In computer science, a composite data type is any data type which can be constructed in a program using the programming language's primitive data types and other composite types. So C++ has data structures for storing;
•Data items of same types
•Data items of different types

Arrays:

 Arrays are used to store related data items of the same type, Structures and Classes are used to store related data items of different types. We will study structures and classes later.
          Arrays are used to store related data items of same type
          Arrays are static entities, ie their size remains the same throughout program execution
          An array is a: 
          Consecutive group of memory locations
          Same name and type (int, char, etc.)
          To refer to an element of an array:
          Specify array name and position number (index)
          Format: arrayname[ position number ]
          First element at will be always at position 0
          N-element array c
int c[N]; //declaration
c[ 0 ], c[ 1 ] c[ N - 1 ] are the array items
          Nth element at position N-1

•Array elements are like other variables
–Assignment followed by printing for an integer array c
int c[1];
c[ 0 ] =  3;      // 0 is the Subscript here
cout << c[ 0 ];
•Can perform operations inside subscript
c[ 5 – 2 ] same as c[3]

Declaring Arrays:

•When declaring arrays, you have to specify; 
–Name
–Type of array ie any data type
–Number of elements/size
type arrayName[ arraySize ];
int c[ 10 ];  // array of 10 integers
float d[ 3284 ]; // array of 3284 floats
•When it comes to declaring multiple arrays of same type
–Use comma separated list, like regular variables
int b[ 100 ], x[ 27 ];

Example Using Arrays:

•Arrays can be initialized using:
–a for loop
•Set each element
–An initializer list
•Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
•If not enough initializers, rightmost elements 0
•If too many syntax errors
–If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
•5 initializers, therefore 5 element array

About the Author

Unknown

Editorial Team

Post a Comment

 
Codexify © 2015 - Designed by Templateism.com