Thursday, June 27, 2013

C++ (beginner) arrays

Lets try to solve the following task.
input 5 numbers and output them separating with enter.
pretty simple right?
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
cout<<a<<endl<<b<<endl<<c<<endl<<d<<endl<<e;

now, what if the task was a bit different calculate the sum of 100 numbers
I am sure that it is not comfortable to write
int a,b,c,d,e,f,g,h.....,aa,bb;

That is why we have arrays.
Arrays are sets of integers.

we declare arrays like this

type    array name [ the number of elements in array];
  example
int a[100];
int c[200];
double b [56];

The integers in array can be called using their indexes. "a" is not a variable but "a[1]" "a[50]" "a[23]" are variables.

now our task wanted to output 100 number separated with enter.

As you can see in the picture I declared an array of 101 elements. Indexing in C++ starts with 0 so a[0] is also a variable too.

There are multi dimentional arrays in C++. so you can always write
int a[10][10][10][10];
now our array has 4 indexes. imagine arrays like they are a mathematical coordinate system.
 int a[10][10];
so in a coordinate (1,2) we can keep a number.
a[1][2]=32;
int a[12][12][12];
a[1][5][3]=567;
in a coordinate (1,5,3) we have a value of 567.




No comments:

Post a Comment