Access data in an Array

How to access a data in an Array?
for example??


this code prints
the entire array
values


1 2 3 4 5


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//array.cpp
//##

#include <iostream>
using std::cout;
using std::endl;



int main(){


int const SIZE=5;
int array[SIZE]={1,2,3,4,5};

//print array values
for(int i=0;i<SIZE;i++){
        cout<<array[i]<<' ';
}//end for loop
cout<<endl;


return 0; //indicates success
}//end main 
There are many ways to access arrays. A simple example is a 2d array initialized to all zeroes; we should modify the values and display them, such as below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

int main()
{
    //initialize 10x10 array to be all zeroes
    int array[10][10]= {0};
    //double loop increments all array values and displays them
    for (int y=0; y<10; y++)
    {
        for (int x=0; x<10; x++)
        {
            array[y][x]++;
            cout<<array[y][x]<<" ";
        }
        cout<<endl;//go to next line before displaying each horizontal row
    }
    return 0;
}

It can be important to remember that in a 2D array, the first value is it's vertical position, and not horizontal, so this is why I chose to go with x and y as descriptive variables. The above code should output all 1's in a 10x10 grid with a space between each. Similarly, array values can be modified as needed by supplying values based on user input or basic math depending on what you are trying to do.

A simple example would be Tic-Tac-Toe; a 3x3 grid can contain 0's for empty spaces, or 1 for X's or 2 for O's. Simple loop based logic can scan the array for a vertical, horizontal or diagonal row containing all 1's or 2's that would signify a victory, or check to ensure that empty spaces still exist within the array, and if none remain and nobody won consider the game a draw.
Last edited on
with operator[].
Last edited on
Last edited on
Did you try to google this first?

http://goo.gl/zAuVig
Topic archived. No new replies allowed.