Array Basics in C++ programming language:
Arrays are extremely important for every computer programming language including C++. There are situations when we need arrays in every programming language. In this chapter I will explain the basics of arrays in C++ programming language.
When we need an array?
When many variables are required of same data type and they all need to be treated the same way. For example: To store the first 10 even numbers we can declare an array of size 10.
Why we need array?
In the above example: rather than declaring 10 different integers, we can declare an array with no headache of memorizing 10 different variable names.
What is an array?
Array is a collection of variables of same data type under a single name.
How we use array?
There are different kinds of arrays: 1D, 2 D, 3D [D=Dimensions] for each data type. But here I am going to explain 1D array for integer or float data type. Char data type arrays have a different approach. I will explain them in the different chapters.
For example: if we need to store the first 10 even numbers, we can declare an array of integers like this:
rather than creating 10 variables like int a,b,c,d,e,f,g,h,I,j;
In memory 10 integers are declared in sequential memory locations:
In an array subscript or index always starts with ZERO. The subscripts are used by the compiler to locate the array item. For example to refer to the values 2,4,6,…,20 the compiler refers them in this way:
arr[0], arr[1], arr[2],… arr[9]
Try this code in C++ compiler.
//Program to store first 10 even numbers and print them
#include<iostream.h>
void main()
{
int arr[10], i,val;
/* In the following loop i is used to run the loop 10 times. i is initialized with ZERO because subscript starts with ZERO. val is used to store values starting from 2 and incrementing by 2 each time.*/
for(i=0,val=2; i<=9;i++,val=val+2)
arr[i]=val;
for (i=0;i<=9;i++)
cout<<arr[i]<<endl;
}
The Output of this program is:
2
4
6
8
10
12
14
16
18
20
The above C++ program is run in turbo c compiler.
The integer and float arrays have the same concept. The only difference is of their data types. integers store whole numbers while floats store decimal numbers.
Character arrays have a different concept which I have explained in this article:
No comments:
Post a Comment