For loop Problem

Why does this code give an error line 38 to 42

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<iostream>
#include<string>
using namespace std;

//declare the function
string GetArrayEntry()
{
	string answer;

	cout << "Please enter an entry into Array field ";cin >> answer;
	return answer;
}

int main()
{
	int wait;
	//make the size of the array a constant size
	const int sizeOfArray = 5;
	//initiate the array
	string MyArray[sizeOfArray];
	
	//assign index the size of the actual array
	int index = sizeof(MyArray) / sizeof(string);

	// Input strings into an array of specified size Accending using the function
	for(int i = 0; i < index; ++i)
	{
		MyArray[i] = GetArrayEntry();
		
	}
	
	// Retrieve strings from an array of specified size Accending
	for(int i = 0; i < index; ++i)
	{
		cout << "The entry was " << MyArray[i] << endl;
	}

	// Retrieve strings from an array of specified size Deccending
	for(int i = index; i > 0; --i)
	{
		cout << "The entry was " << MyArray[i] << endl;
	}

	cin >> wait;
	
	
This is wrong:
for(int i = index; i > 0; --i) because index is outside the bounds of the array and the string at index 0 does not get printed.
Try
for(int i = index-1; i > -1; --i)

By The way This is redundant (pointless):
1
2
3
	//assign index the size of the actual array
	int index = sizeof(MyArray) / sizeof(string);

just use the sizeOfArray value.
Last edited on
Thanks for your reply, worked great!
Before someone calls me on it you can also do this:
1
2
3
	
// Retrieve strings from an array of specified size Deccending
	for(int i = index-1; i >= 0; --i)
Topic archived. No new replies allowed.