I need help with two things I cant get to work?? (Arrays)

I am in the middle of doing a project and is a bit confused about two things.

1. How do you print out the last 4 items in an array, I know how to print out a full array but not certain parts of one.

2. How to make an array adjustable. ex between 5-25 items in an array.

Thanks in advance.

1) http://www.cplusplus.com/doc/tutorial/arrays/
2) If you're referring to how to resize an array - well, you can't.

For your first question, you print out the last 4 items of the array by either accessing their specific positions or by doing some simple math.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Example 1
// Declare and initialize an array called myArray that holds 5 elements of type int
int myArray[5] = {10, 20, 30, 40, 50};     

// To find the length of the array (pretend you didn't know it, btw it's 5)
// An integer is 4 bytes, so we take the size of the array which is a total of 20 bytes,
// then we divide it by one element in the array which is 4 bytes
// thus: 20/4 = 5  so this means that the array has a size of 5 elements
int arraySize = sizeof(myArray)/sizeof(int);  

// Counter to keep track of how many positions we are moving
// We want to move four back from the end because you want the last 
// four items of the array.
int j = 0;

//Loop through the array starting at the last position of the array
//arraySize-1 = position 4
//(Don't forget that we have an array of 5 elements where the first element is at position 0).
//Each time we decrement the position and increment our j counter
for(int i = arraySize-1; j < 4; i--)
{
  j++;
  cout << myArray[i] << endl;
}


Program output:
50
40
30
20


Or, if you know the size of the array already (which you should, since arrays are declared and initialized statically in C++ and you, yourself have created it.) In this case you can just literally print out the last four positions of the array (i.e. the last four elements)

1
2
3
4
5
6
7
8
//Example 2
int myArray[5] = {10, 20, 30, 40, 50};

//Start at the last position and literally print out the last four elements in the array
for(int i = 4; i > 0; i--)
{
  cout << myArray[i] << endl;
}


Program output:
50
40
30
20


Or, similarly;
1
2
3
4
5
6
7
//Example 3
int myArray = {10, 20, 30, 40, 50};

cout << myArray[4] << endl;
cout << myArray[3] << endl;
cout << myArray[2] << endl;
cout << myArray[1] << endl;


Program output:
50
40
30
20
Topic archived. No new replies allowed.