-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Saturday, 8 August 2015

Arrays in C++

 Concept of arrays

One of the most important concepts in C++ is arrays.Today I will explain the concept of  arrays with daily life examples.For this article,I am taking help from the Android application "C++ little drops".

Suppose we want to calculate the average of the marks for a class of 20 students ,we certainly do not want to create 30 variables: std1,st2,std3,.......std.20.Instead,we can use a single variable,called an array with 30 elements.

Definition of arrays

An array is a list of elements of the same type(e.g., int), identified by a pair of square brackets [ ]. 

Declaration of arrays

To use an array, we need to declare the array with 3 things: a name, a type and a dimension( or size, or length).Remember that an array always starts with index 0.It means that the first value in an array is stored in index 0.The syntax is as follows:

Syntax

type arrayName[array length];

It is recommended to use a plural name for array.e.g., marks,numbers, books,etc.

int  books[10];

We can also initialize the array during declaration with a comma-separated list of values,as follows:

int numbers{2,4,5,6,3,9,12,14};

Example

A simple program will help you understand this concept more clearly.

Source code

#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int numbers[5]={1,2,3,4,5};  //an array "numbers"
cout<<"The first number: "<<numbers[0]<<endl;  // number stored in index 0;
cout<<"The second number: "<<numbers[1]<<endl;
cout<<"The third number: "<<numbers[2]<<endl;
cout<<"The fourth number: "<<numbers[3]<<endl;
cout<<"The fifth number:"<<numbers[4]<<endl;
}

Output

Output of arrays

No comments:

Post a Comment